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
use parlov_core::{
    ImpactClass, NormativeStrength, OracleClass, OracleResult, OracleVerdict, Severity, Vector,
};
use proptest::prelude::*;

use super::*;

fn make_result(confidence: u8) -> OracleResult {
    OracleResult {
        class: OracleClass::Existence,
        verdict: OracleVerdict::Confirmed,
        severity: Some(Severity::High),
        confidence,
        impact_class: Some(ImpactClass::High),
        reasons: vec![],
        signals: vec![],
        technique_id: None,
        vector: None,
        normative_strength: None,
        label: None,
        leaks: None,
        rfc_basis: None,
    }
}

fn meta(v: Vector) -> StrategyMetaForStop {
    StrategyMetaForStop {
        vector: v,
        normative_strength: NormativeStrength::Must,
    }
}

// Test 1: fresh accumulator has posterior == 0.5
#[test]
fn fresh_accumulator_posterior_is_half() {
    let acc = EvidenceAccumulator::new();
    assert!(
        (acc.posterior_probability() - 0.5).abs() < 1e-10,
        "expected 0.5, got {}",
        acc.posterior_probability()
    );
}

// Test 2: single Positive at confidence 85 raises posterior above 0.5
#[test]
fn positive_outcome_raises_posterior() {
    let mut acc = EvidenceAccumulator::new();
    let outcome = StrategyOutcome::Positive(make_result(85));
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    assert!(
        acc.posterior_probability() > 0.5,
        "expected posterior > 0.5, got {}",
        acc.posterior_probability()
    );
}

// Test 3: single Contradictory at confidence 85, weight 1.0 lowers posterior below 0.5
#[test]
fn contradictory_outcome_lowers_posterior() {
    let mut acc = EvidenceAccumulator::new();
    let outcome = StrategyOutcome::Contradictory(make_result(85), 1.0);
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    assert!(
        acc.posterior_probability() < 0.5,
        "expected posterior < 0.5, got {}",
        acc.posterior_probability()
    );
}

// Test 4: NoSignal leaves posterior at exactly 0.5
#[test]
fn no_signal_leaves_posterior_unchanged() {
    let mut acc = EvidenceAccumulator::new();
    let outcome = StrategyOutcome::NoSignal(make_result(85));
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    assert!(
        (acc.posterior_probability() - 0.5).abs() < 1e-10,
        "expected 0.5, got {}",
        acc.posterior_probability()
    );
}

// Test 5: Inapplicable leaves posterior at exactly 0.5
#[test]
fn inapplicable_leaves_posterior_unchanged() {
    let mut acc = EvidenceAccumulator::new();
    let outcome = StrategyOutcome::Inapplicable("no ETag support".into());
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    assert!(
        (acc.posterior_probability() - 0.5).abs() < 1e-10,
        "expected 0.5, got {}",
        acc.posterior_probability()
    );
}

// Test 6: two Positive from same family — second contributes half, posterior < 2x distance from 0.5
//
// Under the offline reducer, a single Positive at confidence=85 already saturates the cap
// (logit(0.85)≈1.735 > 0.75). Use confidence=65 (logit≈0.619) so the single-event contribution
// stays under the cap, allowing the second event to add measurable value via slot 1 (×0.5)
// before the group total clamps at 0.75.
#[test]
fn two_positives_same_family_diminishing_returns() {
    let outcome = StrategyOutcome::Positive(make_result(65));

    // StatusCodeDiff maps to General family
    let mut acc_one = EvidenceAccumulator::new();
    acc_one.ingest(&outcome, Vector::StatusCodeDiff);
    let p_one = acc_one.posterior_probability();
    let dist_one = p_one - 0.5;

    let mut acc_two = EvidenceAccumulator::new();
    acc_two.ingest(&outcome, Vector::StatusCodeDiff);
    acc_two.ingest(&outcome, Vector::StatusCodeDiff);
    let p_two = acc_two.posterior_probability();
    let dist_two = p_two - 0.5;

    // Second is larger but less than 2x the first
    assert!(
        dist_two > dist_one,
        "two positives must be stronger than one"
    );
    assert!(
        dist_two < 2.0 * dist_one,
        "second positive contributes less; distance ({dist_two}) must be < 2x first ({dist_one})"
    );
}

// Test 7: third Positive from same family contributes zero — posterior unchanged from after second
#[test]
fn third_positive_same_family_zero_contribution() {
    let outcome = StrategyOutcome::Positive(make_result(85));

    let mut acc = EvidenceAccumulator::new();
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    let p_after_two = acc.posterior_probability();

    acc.ingest(&outcome, Vector::StatusCodeDiff);
    let p_after_three = acc.posterior_probability();

    assert!(
        (p_after_three - p_after_two).abs() < 1e-10,
        "third positive from same family must not change posterior: after_two={p_after_two}, after_three={p_after_three}"
    );
}

// Test 8: two Positives from different families — both contribute full weight
#[test]
fn two_positives_different_families_full_weight() {
    let outcome = StrategyOutcome::Positive(make_result(85));

    // StatusCodeDiff → General; CacheProbing → CacheValidator: different families
    let mut acc_single = EvidenceAccumulator::new();
    acc_single.ingest(&outcome, Vector::StatusCodeDiff);
    let p_single = acc_single.posterior_probability();

    let mut acc_two = EvidenceAccumulator::new();
    acc_two.ingest(&outcome, Vector::StatusCodeDiff);
    acc_two.ingest(&outcome, Vector::CacheProbing);
    let p_two = acc_two.posterior_probability();

    // Each contributes full weight; combined must be strictly higher than single
    assert!(
        p_two > p_single,
        "two full-weight positives must exceed one: p_single={p_single}, p_two={p_two}"
    );
    // Also verify the log_odds doubled (both multiplier=1.0)
    assert!(
        (acc_two.log_odds_current() - 2.0 * acc_single.log_odds_current()).abs() < 1e-10,
        "log_odds must be exactly double for two independent families"
    );
}

// Test 9: posterior always in [0.0, 1.0] with extreme confidence values
#[test]
fn posterior_clamped_to_unit_interval() {
    let mut acc = EvidenceAccumulator::new();
    // confidence=100 clamped to 0.99 — very high log-odds
    let high = StrategyOutcome::Positive(make_result(100));
    for _ in 0..20 {
        acc.ingest(&high, Vector::StatusCodeDiff);
    }
    let p = acc.posterior_probability();
    assert!((0.0..=1.0).contains(&p), "posterior {p} out of [0, 1]");

    let mut acc2 = EvidenceAccumulator::new();
    // confidence=0 clamped to 0.01 — very low log-odds via Contradictory
    let low = StrategyOutcome::Contradictory(make_result(0), 1.0);
    for _ in 0..20 {
        acc2.ingest(&low, Vector::StatusCodeDiff);
    }
    let p2 = acc2.posterior_probability();
    assert!((0.0..=1.0).contains(&p2), "posterior {p2} out of [0, 1]");
}

// Test 10: max_positive_remaining returns 0.0 for empty slice
#[test]
fn max_positive_remaining_empty_is_zero() {
    let acc = EvidenceAccumulator::new();
    assert!(
        acc.max_positive_remaining(&[]).abs() < 1e-10,
        "expected 0.0 for empty remaining"
    );
}

// Test 10b: Positive with zero confidence fires debug_assert in debug builds
#[test]
#[cfg(debug_assertions)]
fn ingest_positive_with_zero_confidence_fires_debug_assert() {
    use parlov_core::StrategyOutcome;
    let result = OracleResult {
        class: OracleClass::Existence,
        verdict: OracleVerdict::Confirmed,
        severity: None,
        confidence: 0,
        impact_class: None,
        reasons: vec![],
        signals: vec![],
        technique_id: None,
        vector: None,
        normative_strength: None,
        label: None,
        leaks: None,
        rfc_basis: None,
    };
    let outcome = StrategyOutcome::Positive(result);
    // Sub-60 Positive is now skipped defensively — no panic, no event ingested.
    let mut acc = EvidenceAccumulator::new();
    acc.ingest(&outcome, Vector::StatusCodeDiff);
    assert_eq!(acc.event_count(), 0, "sub-60 Positive must be skipped");
    assert!(
        (acc.posterior_probability() - 0.5).abs() < 1e-10,
        "posterior must remain 0.5 after skipped ingest; got {}",
        acc.posterior_probability()
    );
}

// Test 11: max_positive_remaining respects already-saturated families.
//
// Under the offline reducer, an already-capped family swallows additional hypothetical events:
// the augmented reduction stays at the cap, so `max_positive_remaining` reports `0.0` for that
// family. This pins the contract that the bound is a real (achievable) extreme rather than a
// fixed-multiplier projection.
#[test]
fn max_positive_remaining_zero_when_family_already_capped() {
    // Saturate CacheValidator with a single high-confidence positive: logit(0.85)≈1.735, well
    // above the 0.75 per-group cap. After ingest the family is at the cap.
    let mut acc = EvidenceAccumulator::new();
    let pos = StrategyOutcome::Positive(make_result(85));
    acc.ingest(&pos, Vector::CacheProbing);

    // One remaining CacheProbing spec maps to the same family. Adding the hypothetical maxed
    // event still leaves the group at the cap, so the augmented total equals the current total.
    let remaining = vec![meta(Vector::CacheProbing)];
    let max_pos = acc.max_positive_remaining(&remaining);
    assert!(
        max_pos.abs() < 1e-9,
        "saturated family must yield 0.0 max_positive_remaining; got {max_pos}"
    );
}

// Test 11b: a remaining spec in an unsaturated family must report a strictly positive bound.
#[test]
fn max_positive_remaining_positive_for_fresh_family() {
    let acc = EvidenceAccumulator::new();
    let remaining = vec![meta(Vector::StatusCodeDiff)];
    let max_pos = acc.max_positive_remaining(&remaining);
    assert!(
        max_pos > 0.0,
        "fresh family must yield positive max_positive_remaining; got {max_pos}"
    );
}

// ----- Order invariance and unit-interval property tests -----

/// One ingest item: outcome + vector. Captured as a small enum so we can permute easily.
#[derive(Debug, Clone)]
enum Step {
    Positive(u8, Vector),
    Contradictory(u8, f32, Vector),
    NoSignal(Vector),
}

fn arb_vector() -> impl Strategy<Value = Vector> {
    prop_oneof![
        Just(Vector::StatusCodeDiff),
        Just(Vector::CacheProbing),
        Just(Vector::ErrorMessageGranularity),
        Just(Vector::RedirectDiff),
    ]
}

fn arb_step() -> impl Strategy<Value = Step> {
    prop_oneof![
        (60u8..=99, arb_vector()).prop_map(|(c, v)| Step::Positive(c, v)),
        (0u8..=99, 0.01f32..=1.0, arb_vector()).prop_map(|(c, w, v)| Step::Contradictory(c, w, v)),
        arb_vector().prop_map(Step::NoSignal),
    ]
}

fn arb_steps() -> impl Strategy<Value = Vec<Step>> {
    prop::collection::vec(arb_step(), 0..12)
}

fn permute_indices(len: usize, seeds: &[u32]) -> Vec<usize> {
    let mut indices: Vec<usize> = (0..len).collect();
    for (offset, i) in (1..len).rev().enumerate() {
        let seed = seeds.get(offset).copied().unwrap_or(0);
        let j = (seed as usize) % (i + 1);
        indices.swap(i, j);
    }
    indices
}

fn ingest_steps(steps: &[Step]) -> EvidenceAccumulator {
    let mut acc = EvidenceAccumulator::new();
    for step in steps {
        match step {
            Step::Positive(c, v) => {
                acc.ingest(&StrategyOutcome::Positive(make_result(*c)), *v);
            }
            Step::Contradictory(c, w, v) => {
                acc.ingest(&StrategyOutcome::Contradictory(make_result(*c), *w), *v);
            }
            Step::NoSignal(v) => {
                acc.ingest(&StrategyOutcome::NoSignal(make_result(0)), *v);
            }
        }
    }
    acc
}

proptest! {
    /// Posterior is order-invariant under any ingest permutation.
    #[test]
    fn posterior_is_order_invariant(
        steps in arb_steps(),
        seeds in prop::collection::vec(any::<u32>(), 0..12),
    ) {
        let baseline = ingest_steps(&steps).posterior_probability();
        let perm = permute_indices(steps.len(), &seeds);
        let permuted: Vec<Step> = perm.into_iter().map(|i| steps[i].clone()).collect();
        let permuted_post = ingest_steps(&permuted).posterior_probability();
        prop_assert!((baseline - permuted_post).abs() < 1e-9);
    }

    /// Posterior is always within `[0.0, 1.0]`.
    #[test]
    fn posterior_in_unit_interval(steps in arb_steps()) {
        let p = ingest_steps(&steps).posterior_probability();
        prop_assert!((0.0..=1.0).contains(&p));
    }

    /// For any confidence in 60..=100, a single Positive ingest must push posterior > 0.5.
    #[test]
    fn ingest_positive_above_threshold_always_raises_posterior(confidence in 60u8..=100u8) {
        let result = make_result(confidence);
        let mut acc = EvidenceAccumulator::new();
        acc.ingest(&StrategyOutcome::Positive(result), Vector::StatusCodeDiff);
        prop_assert!(
            acc.posterior_probability() > 0.5,
            "confidence={confidence} should raise posterior above 0.5, got {}",
            acc.posterior_probability()
        );
    }
}

// SEC-02 tests — sub-60 Positive outcomes are skipped, not panicked

/// `ingest` silently drops a Positive outcome below the Likely threshold (confidence=59).
///
/// The scanner must not crash on a buggy upstream strategy. After the skip the accumulator
/// has no events and the posterior is exactly 0.5 (neutral prior).
#[test]
fn ingest_positive_below_threshold_skipped() {
    let mut acc = EvidenceAccumulator::new();
    acc.ingest(
        &StrategyOutcome::Positive(make_result(59)),
        Vector::StatusCodeDiff,
    );
    assert_eq!(
        acc.event_count(),
        0,
        "sub-60 Positive must produce zero events"
    );
    assert!(
        (acc.posterior_probability() - 0.5).abs() < 1e-10,
        "posterior must be 0.5 after skipped ingest; got {}",
        acc.posterior_probability()
    );
}

/// `ingest` accepts a Positive outcome at the exact Likely threshold (confidence=60).
///
/// The event is ingested and raises the posterior above 0.5.
#[test]
fn ingest_positive_at_threshold_accepted() {
    let mut acc = EvidenceAccumulator::new();
    acc.ingest(
        &StrategyOutcome::Positive(make_result(60)),
        Vector::StatusCodeDiff,
    );
    assert!(
        acc.posterior_probability() > 0.5,
        "confidence=60 Positive must raise posterior above 0.5; got {}",
        acc.posterior_probability()
    );
}