parlov-analysis 0.7.0

Analysis engine trait and signal detection for parlov.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Unit and property tests for `EvidenceModifiers`, `ModifierResult`, and `compute_modifiers`.
//!
//! No mocks — `compute_modifiers` is exercised against real `DifferentialSet` values
//! constructed via the public `parlov-core` constructors.

use bytes::Bytes;
use http::{HeaderMap, StatusCode};
use parlov_core::{
    always_applicable, DifferentialSet, NormativeStrength, OracleClass, ProbeDefinition,
    ProbeExchange, ResponseSurface, SignalSurface, Technique, Vector,
};
use proptest::prelude::*;

use super::{compute_modifiers, EvidenceModifiers};

fn technique() -> Technique {
    Technique {
        id: "test-modifiers",
        name: "Test modifiers",
        oracle_class: OracleClass::Existence,
        vector: Vector::StatusCodeDiff,
        strength: NormativeStrength::Must,
        normalization_weight: Some(0.2),
        inverted_signal_weight: None,
        method_relevant: false,
        parser_relevant: false,
        applicability: always_applicable,
        contradiction_surface: SignalSurface::Status,
    }
}

fn make_exchange(status: u16) -> ProbeExchange {
    ProbeExchange {
        request: ProbeDefinition {
            url: "https://example.com/r/1".into(),
            method: http::Method::GET,
            headers: HeaderMap::new(),
            body: None,
        },
        response: ResponseSurface {
            status: StatusCode::from_u16(status).expect("valid status"),
            headers: HeaderMap::new(),
            body: Bytes::new(),
            timing_ns: 0,
        },
    }
}

fn diff_set_uniform_401() -> DifferentialSet {
    DifferentialSet {
        baseline: vec![make_exchange(401)],
        probe: vec![make_exchange(401)],
        canonical: None,
        technique: technique(),
    }
}

fn diff_set_distinct_status() -> DifferentialSet {
    DifferentialSet {
        baseline: vec![make_exchange(200)],
        probe: vec![make_exchange(404)],
        canonical: None,
        technique: technique(),
    }
}

// --- EvidenceModifiers value semantics -------------------------------------

#[test]
fn default_returns_all_ones() {
    let m = EvidenceModifiers::default();
    assert!((m.surface_relevance - 1.0).abs() < f64::EPSILON);
    assert!((m.precondition_confidence - 1.0).abs() < f64::EPSILON);
    assert!((m.control_integrity - 1.0).abs() < f64::EPSILON);
}

#[test]
fn default_total_is_one() {
    assert!((EvidenceModifiers::default().total() - 1.0).abs() < f64::EPSILON);
}

#[test]
fn default_is_not_blocked() {
    assert!(!EvidenceModifiers::default().is_blocked());
}

#[test]
fn total_is_multiplicative_product() {
    let m = EvidenceModifiers {
        surface_relevance: 0.5,
        precondition_confidence: 0.5,
        control_integrity: 0.5,
    };
    assert!((m.total() - 0.125).abs() < f64::EPSILON);
}

#[test]
fn total_with_one_zero_is_zero() {
    let m = EvidenceModifiers {
        surface_relevance: 0.0,
        precondition_confidence: 1.0,
        control_integrity: 1.0,
    };
    assert!(m.total().abs() < f64::EPSILON);
}

#[test]
fn is_blocked_true_when_surface_relevance_zero() {
    let m = EvidenceModifiers {
        surface_relevance: 0.0,
        precondition_confidence: 1.0,
        control_integrity: 1.0,
    };
    assert!(m.is_blocked());
}

#[test]
fn is_blocked_true_when_precondition_confidence_zero() {
    let m = EvidenceModifiers {
        surface_relevance: 1.0,
        precondition_confidence: 0.0,
        control_integrity: 1.0,
    };
    assert!(m.is_blocked());
}

#[test]
fn is_blocked_true_when_control_integrity_zero() {
    let m = EvidenceModifiers {
        surface_relevance: 1.0,
        precondition_confidence: 1.0,
        control_integrity: 0.0,
    };
    assert!(m.is_blocked());
}

#[test]
fn is_blocked_true_when_all_zero() {
    let m = EvidenceModifiers {
        surface_relevance: 0.0,
        precondition_confidence: 0.0,
        control_integrity: 0.0,
    };
    assert!(m.is_blocked());
}

#[test]
fn is_blocked_false_when_all_positive() {
    let m = EvidenceModifiers {
        surface_relevance: 0.01,
        precondition_confidence: 0.01,
        control_integrity: 0.01,
    };
    assert!(!m.is_blocked());
}

// --- compute_modifiers: precondition gate ----------------------------------

#[test]
fn compute_modifiers_blocks_uniform_401_no_auth() {
    let ds = diff_set_uniform_401();
    let mr = compute_modifiers(&technique(), &ds);
    assert!(
        mr.is_blocked(),
        "uniform 401 must zero precondition_confidence"
    );
    assert!(mr.block_reason.is_some(), "block reason must be populated");
}

#[test]
fn compute_modifiers_returns_default_on_distinct_status() {
    let ds = diff_set_distinct_status();
    let mr = compute_modifiers(&technique(), &ds);
    assert_eq!(mr.modifiers, EvidenceModifiers::default());
    assert!(mr.block_reason.is_none());
}

#[test]
fn compute_modifiers_total_is_one_on_distinct_status() {
    let ds = diff_set_distinct_status();
    let mr = compute_modifiers(&technique(), &ds);
    assert!((mr.modifiers.total() - 1.0).abs() < f64::EPSILON);
}

// --- compute_modifiers: surface_relevance gate ---------------------------------

fn make_exchange_with(status: u16, body: Bytes) -> ProbeExchange {
    ProbeExchange {
        request: ProbeDefinition {
            url: "https://example.com/r/1".into(),
            method: http::Method::GET,
            headers: HeaderMap::new(),
            body: None,
        },
        response: ResponseSurface {
            status: StatusCode::from_u16(status).expect("valid status"),
            headers: HeaderMap::new(),
            body,
            timing_ns: 0,
        },
    }
}

#[test]
fn compute_modifiers_blocks_uniform_status_with_diverging_body() {
    // Status-surface technique fires SameStatus; body lengths differ by far more than 10%.
    // Surface-relevance fires; precondition is inert (uniform 200, no auth gate).
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange_with(200, Bytes::from(vec![b'x'; 1000]))],
        probe: vec![make_exchange_with(200, Bytes::from_static(b"x"))],
        canonical: None,
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(
        mr.is_blocked(),
        "diverging body on Status-surface technique must zero surface_relevance"
    );
    assert_eq!(
        mr.block_reason,
        Some(super::PreconditionBlock::SurfaceMismatch),
        "block reason must be SurfaceMismatch"
    );
    assert!((mr.modifiers.surface_relevance).abs() < f64::EPSILON);
    assert!((mr.modifiers.precondition_confidence - 1.0).abs() < f64::EPSILON);
}

#[test]
fn compute_modifiers_precondition_takes_priority_over_surface() {
    // Uniform 405 (method gate) AND diverging body — precondition wins by priority.
    // The method-gate fires regardless of body content, so this isolates the priority order.
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange_with(405, Bytes::from(vec![b'x'; 1000]))],
        probe: vec![make_exchange_with(405, Bytes::from_static(b"x"))],
        canonical: None,
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(mr.is_blocked());
    assert_eq!(
        mr.block_reason,
        Some(super::PreconditionBlock::MethodGateBeforeResource),
        "method-gate (precondition) must be reported first when both gates fire"
    );
}

#[test]
fn compute_modifiers_inert_when_body_surface_with_diverging_body() {
    // Body-surface technique with diverging body — surface-relevance should NOT block.
    let mut t = technique();
    t.contradiction_surface = SignalSurface::Body;
    let ds = DifferentialSet {
        baseline: vec![make_exchange_with(200, Bytes::from(vec![b'x'; 1000]))],
        probe: vec![make_exchange_with(200, Bytes::from_static(b"x"))],
        canonical: None,
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(
        !mr.is_blocked(),
        "Body-surface technique must not block on body diff"
    );
    assert_eq!(mr.modifiers, EvidenceModifiers::default());
}

// --- control_integrity wiring ---------------------------------

#[test]
fn compute_modifiers_blocks_when_canonical_succeeds_mutated_fails() {
    // canonical 200, mutated 404/404 — control_integrity fires; precondition inert (no auth gate
    // on uniform 404), surface inert (uniform empty bodies).
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange(404)],
        probe: vec![make_exchange(404)],
        canonical: Some(make_exchange(200)),
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(mr.is_blocked());
    assert_eq!(
        mr.block_reason,
        Some(super::PreconditionBlock::MutationDestroyedControl),
        "block reason must be MutationDestroyedControl when canonical 2xx + mutated non-2xx"
    );
    assert!((mr.modifiers.control_integrity).abs() < f64::EPSILON);
    assert!((mr.modifiers.precondition_confidence - 1.0).abs() < f64::EPSILON);
    assert!((mr.modifiers.surface_relevance - 1.0).abs() < f64::EPSILON);
}

#[test]
fn compute_modifiers_blocks_when_canonical_returns_301() {
    // canonical 301 — control_integrity blocks regardless of mutated outcome.
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange(200)],
        probe: vec![make_exchange(200)],
        canonical: Some(make_exchange(301)),
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(mr.is_blocked());
    assert_eq!(
        mr.block_reason,
        Some(super::PreconditionBlock::MutationDestroyedControl),
    );
}

#[test]
fn compute_modifiers_inert_when_no_canonical() {
    // No canonical exchange — control_integrity stays at 1.0; precondition+surface inert.
    let t = technique();
    let ds = diff_set_distinct_status();
    let mr = compute_modifiers(&t, &ds);
    assert_eq!(mr.modifiers, EvidenceModifiers::default());
    assert_eq!(mr.block_reason, None);
}

#[test]
fn compute_modifiers_precondition_takes_priority_over_control() {
    // Uniform 401-no-auth (auth gate) AND canonical 2xx + mutated 401 (control would also fire) —
    // precondition wins by precedence.
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange(401)],
        probe: vec![make_exchange(401)],
        canonical: Some(make_exchange(200)),
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(mr.is_blocked());
    assert_eq!(
        mr.block_reason,
        Some(
            crate::aggregation::PreconditionBlock::AuthGateBeforeTechnique {
                credential_state: crate::aggregation::auth_types::CredentialBlockKind::NoCredential,
                layer: crate::aggregation::AuthBlockLayer::Origin,
            }
        ),
        "auth-gate (precondition) must be reported first when both gates fire"
    );
}

#[test]
fn compute_modifiers_control_takes_priority_over_surface() {
    // canonical 2xx + mutated 4xx (control fires) AND body diverges (surface would also fire) —
    // control wins by precedence.
    let t = technique();
    let ds = DifferentialSet {
        baseline: vec![make_exchange_with(404, Bytes::from(vec![b'x'; 1000]))],
        probe: vec![make_exchange_with(404, Bytes::from_static(b"x"))],
        canonical: Some(make_exchange(200)),
        technique: t,
    };
    let mr = compute_modifiers(&t, &ds);
    assert!(mr.is_blocked());
    assert_eq!(
        mr.block_reason,
        Some(super::PreconditionBlock::MutationDestroyedControl),
        "control must be reported before surface when both gates fire"
    );
}

// --- property tests --------------------------------------------------------

proptest! {
    /// `total()` is bounded by `[0.0, 1.0]` when each field is in `[0.0, 1.0]`.
    #[test]
    fn total_bounded_when_fields_bounded(
        sr in 0.0f64..=1.0,
        pc in 0.0f64..=1.0,
        ci in 0.0f64..=1.0,
    ) {
        let m = EvidenceModifiers {
            surface_relevance: sr,
            precondition_confidence: pc,
            control_integrity: ci,
        };
        prop_assert!(m.total() >= 0.0);
        prop_assert!(m.total() <= 1.0);
    }

    /// `is_blocked()` is true iff any field equals `0.0`.
    #[test]
    fn is_blocked_iff_any_field_zero(
        sr in 0.0f64..=1.0,
        pc in 0.0f64..=1.0,
        ci in 0.0f64..=1.0,
    ) {
        let m = EvidenceModifiers {
            surface_relevance: sr,
            precondition_confidence: pc,
            control_integrity: ci,
        };
        let any_zero = sr == 0.0 || pc == 0.0 || ci == 0.0;
        prop_assert_eq!(m.is_blocked(), any_zero);
    }

    /// `total()` is invariant under permutation of the three fields (multiplication is commutative).
    #[test]
    fn total_commutative_under_permutation(
        a in 0.0f64..=1.0,
        b in 0.0f64..=1.0,
        c in 0.0f64..=1.0,
    ) {
        let m1 = EvidenceModifiers {
            surface_relevance: a,
            precondition_confidence: b,
            control_integrity: c,
        };
        let m2 = EvidenceModifiers {
            surface_relevance: c,
            precondition_confidence: a,
            control_integrity: b,
        };
        let m3 = EvidenceModifiers {
            surface_relevance: b,
            precondition_confidence: c,
            control_integrity: a,
        };
        prop_assert!((m1.total() - m2.total()).abs() < f64::EPSILON);
        prop_assert!((m1.total() - m3.total()).abs() < f64::EPSILON);
    }

    /// `compute_modifiers` is referentially transparent — same inputs produce same outputs.
    #[test]
    fn compute_modifiers_referentially_transparent(b_status in 200u16..=599, p_status in 200u16..=599) {
        let b_status = if http::StatusCode::from_u16(b_status).is_err() { 404 } else { b_status };
        let p_status = if http::StatusCode::from_u16(p_status).is_err() { 404 } else { p_status };
        let ds = DifferentialSet {
            baseline: vec![make_exchange(b_status)],
            probe: vec![make_exchange(p_status)],
            canonical: None,
            technique: technique(),
        };
        let mr1 = compute_modifiers(&technique(), &ds);
        let mr2 = compute_modifiers(&technique(), &ds);
        prop_assert_eq!(mr1, mr2);
    }
}