ripr 0.10.0

Find static mutation-exposure gaps before expensive mutation testing
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
443
444
445
446
447
448
449
450
451
452
453
use super::super::rust_index::{FunctionSummary, TestSummary};
use crate::domain::*;

pub(in crate::analysis) fn ensure_unknown_stop_reason(
    class: &ExposureClass,
    stop_reasons: &mut Vec<StopReason>,
) {
    if class.requires_stop_reason()
        && stop_reasons.is_empty()
        && let Some(reason) = StopReason::for_unknown_class(class)
    {
        stop_reasons.push(reason);
    }
}

pub(in crate::analysis) fn classify(
    reach: &StageEvidence,
    infect: &StageEvidence,
    propagate: &StageEvidence,
    observe: &StageEvidence,
    discriminate: &StageEvidence,
    probe: &Probe,
) -> ExposureClass {
    if matches!(probe.family, ProbeFamily::StaticUnknown) {
        return ExposureClass::StaticUnknown;
    }
    if reach.state == StageState::No {
        return ExposureClass::NoStaticPath;
    }
    if infect.state == StageState::Unknown || infect.state == StageState::Opaque {
        return ExposureClass::InfectionUnknown;
    }
    if propagate.state == StageState::Unknown || propagate.state == StageState::Opaque {
        return ExposureClass::PropagationUnknown;
    }
    if observe.state == StageState::No {
        return ExposureClass::ReachableUnrevealed;
    }
    if discriminate.state == StageState::Yes
        && infect.state == StageState::Yes
        && propagate.state == StageState::Yes
    {
        ExposureClass::Exposed
    } else {
        ExposureClass::WeaklyExposed
    }
}

/// Maximum headline confidence permitted for a given per-stage `Confidence`
/// marker.  `High` and `Medium` return `1.0` so genuine all-Yes/Medium
/// exposures are never suppressed.  Only `Low` and `Unknown` stages produce a
/// real ceiling, capping an over-stated aggregate score without affecting the
/// classification at all.
fn confidence_ceiling(c: &Confidence) -> f32 {
    match c {
        Confidence::High | Confidence::Medium => 1.0,
        Confidence::Low => 0.66,
        Confidence::Unknown => 0.50,
    }
}

pub(in crate::analysis) fn confidence_score(
    reach: &StageEvidence,
    infect: &StageEvidence,
    propagate: &StageEvidence,
    observe: &StageEvidence,
    discriminate: &StageEvidence,
    class: &ExposureClass,
) -> f32 {
    let stages = [reach, infect, propagate, observe, discriminate];
    let mut score = 0.0;
    for stage in &stages {
        score += match stage.state {
            StageState::Yes => 0.2,
            StageState::Weak => 0.12,
            StageState::Unknown => 0.07,
            StageState::Opaque => 0.05,
            StageState::No => 0.02,
            StageState::NotApplicable => 0.1,
        };
    }
    if matches!(
        class,
        ExposureClass::NoStaticPath | ExposureClass::ReachableUnrevealed
    ) {
        score = (score + 0.15_f32).min(0.95_f32);
    }
    // Cap the headline score by the weakest contributing stage's per-stage
    // Confidence ceiling (RIPR-SPEC-0109).  Applied AFTER the +0.15 bump so
    // it can only lower, never raise.  High/Medium stages → cap = 1.0 (no
    // effect); Low → cap = 0.66; Unknown → cap = 0.50.
    let cap = stages
        .iter()
        .map(|s| confidence_ceiling(&s.confidence))
        .fold(1.0_f32, f32::min);
    (score.min(cap) * 100.0).round() / 100.0
}

pub(in crate::analysis) fn missing_evidence(
    probe: &Probe,
    class: &ExposureClass,
    infect: &StageEvidence,
    observe: &StageEvidence,
    discriminate: &StageEvidence,
    activation: &ActivationEvidence,
) -> Vec<String> {
    let mut missing = Vec::new();
    match class {
        ExposureClass::Exposed => {}
        ExposureClass::NoStaticPath => {
            missing.push("No static test path reaches the changed owner".to_string())
        }
        ExposureClass::ReachableUnrevealed => missing.push(
            "No detected assertion observes the changed value, error, field, or effect".to_string(),
        ),
        ExposureClass::InfectionUnknown => missing.push(infect.summary.clone()),
        ExposureClass::PropagationUnknown => missing.push(
            "No clear propagation path from changed behavior to an observable sink".to_string(),
        ),
        ExposureClass::StaticUnknown => missing.push(
            "Syntax-first analysis cannot classify this change; use deep mode or real mutation"
                .to_string(),
        ),
        ExposureClass::WeaklyExposed => {}
    }
    if matches!(probe.family, ProbeFamily::Predicate)
        && infect.state != StageState::Yes
        && !activation
            .missing_discriminators
            .iter()
            .any(|fact| fact.value.contains("=="))
    {
        missing.push("No detected boundary input for the changed predicate".to_string());
    }
    if observe.state != StageState::Yes {
        missing.push("No relevant oracle was detected".to_string());
    }
    if discriminate.state != StageState::Yes {
        if matches!(probe.family, ProbeFamily::ErrorPath) {
            missing.push("No exact error variant discriminator was detected".to_string());
        } else {
            missing.push("No strong discriminator was detected".to_string());
        }
    }
    missing.extend(
        activation
            .missing_discriminators
            .iter()
            .map(|fact| format!("Missing discriminator value: {}", fact.value)),
    );
    missing.sort();
    missing.dedup();
    missing
}

pub(in crate::analysis) fn stop_reasons(
    probe: &Probe,
    owner_fn: Option<&FunctionSummary>,
    related_tests: &[&TestSummary],
) -> Vec<StopReason> {
    let mut reasons = Vec::new();
    if owner_fn.is_none() {
        reasons.push(StopReason::NoChangedRustLine);
    }
    if related_tests.iter().any(|test| {
        test.body.contains("fixture") || test.body.contains("builder") || test.body.contains("arb_")
    }) {
        reasons.push(StopReason::FixtureOpaque);
    }
    if probe.expression.contains("async")
        || probe.expression.contains("spawn")
        || probe.expression.contains("await")
    {
        reasons.push(StopReason::AsyncBoundaryOpaque);
    }
    if contains_macro_invocation(&probe.expression) {
        reasons.push(StopReason::ProcMacroOpaque);
    }
    reasons.sort_by(|a, b| a.as_str().cmp(b.as_str()));
    reasons.dedup_by(|a, b| a.as_str() == b.as_str());
    reasons
}

fn contains_macro_invocation(expression: &str) -> bool {
    for (idx, ch) in expression.char_indices() {
        if ch != '!' || expression[idx + 1..].starts_with('=') {
            continue;
        }
        let before_bang = expression[..idx].trim_end();
        if before_bang
            .chars()
            .last()
            .is_some_and(|ch| ch == '_' || ch == ')' || ch.is_ascii_alphanumeric())
        {
            return true;
        }
    }
    false
}

pub(in crate::analysis) fn recommended_next_step(
    probe: &Probe,
    class: &ExposureClass,
) -> Option<String> {
    match class {
        ExposureClass::Exposed => None,
        ExposureClass::WeaklyExposed => {
            Some(weakly_exposed_guidance_for_family(&probe.family).to_string())
        }
        ExposureClass::ReachableUnrevealed => Some("Add a meaningful assertion that observes the changed value, branch, error, field, event, or side effect.".to_string()),
        ExposureClass::NoStaticPath => Some("Add a co-located test that reaches and observes the changed owner so a discriminator exists; ripr found no static test path for this change.".to_string()),
        ExposureClass::InfectionUnknown => Some("Add a targeted boundary or negative-path test, or teach ripr about the fixture/builder in ripr.toml.".to_string()),
        ExposureClass::PropagationUnknown | ExposureClass::StaticUnknown => Some("Escalate to real mutation testing or deep static analysis for this probe.".to_string()),
    }
}

fn weakly_exposed_guidance_for_family(family: &ProbeFamily) -> &'static str {
    match family {
        ProbeFamily::Predicate => {
            "Add boundary tests for below, equal, and above the changed threshold with exact assertions."
        }
        ProbeFamily::ErrorPath => {
            "Assert the exact error variant or payload instead of only is_err()."
        }
        ProbeFamily::SideEffect => {
            "Add a mock expectation, event receiver assertion, persisted-state check, or metric assertion for the changed effect."
        }
        ProbeFamily::ReturnValue => {
            "Replace broad assertions with exact equality or a property that constrains the changed returned value."
        }
        _ => "Strengthen the related assertion so it discriminates the changed behavior.",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classify_maps_reachable_but_unobserved_probe_to_reachable_unrevealed() {
        let class = classify(
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::No),
            &stage(StageState::Yes),
            &probe(ProbeFamily::ReturnValue, "value + 1"),
        );

        assert_eq!(class, ExposureClass::ReachableUnrevealed);
    }

    #[test]
    fn confidence_score_handles_opaque_no_and_not_applicable_stage_states() {
        let score = confidence_score(
            &stage(StageState::Opaque),
            &stage(StageState::No),
            &stage(StageState::NotApplicable),
            &stage(StageState::Yes),
            &stage(StageState::Weak),
            &ExposureClass::NoStaticPath,
        );

        assert!(
            (score - 0.64).abs() < f32::EPSILON,
            "confidence score should equal 0.64 (got {score})"
        );
    }

    #[test]
    fn missing_evidence_reports_reachable_unrevealed_gap() {
        let probe = probe(ProbeFamily::ReturnValue, "value + 1");
        let missing = missing_evidence(
            &probe,
            &ExposureClass::ReachableUnrevealed,
            &stage(StageState::Yes),
            &stage(StageState::No),
            &stage(StageState::Yes),
            &ActivationEvidence::default(),
        );

        assert!(
            missing.contains(
                &"No detected assertion observes the changed value, error, field, or effect"
                    .to_string()
            )
        );
    }

    #[test]
    fn recommended_next_step_covers_side_effect_and_default_weak_guidance() {
        let side_effect = recommended_next_step(
            &probe(ProbeFamily::SideEffect, "client.send(value)"),
            &ExposureClass::WeaklyExposed,
        );
        assert_eq!(
            side_effect.as_deref(),
            Some(
                "Add a mock expectation, event receiver assertion, persisted-state check, or metric assertion for the changed effect."
            )
        );

        let match_arm = recommended_next_step(
            &probe(ProbeFamily::MatchArm, "None => 0"),
            &ExposureClass::WeaklyExposed,
        );
        assert_eq!(
            match_arm.as_deref(),
            Some("Strengthen the related assertion so it discriminates the changed behavior.")
        );
    }

    #[test]
    fn recommended_next_step_covers_targeted_weak_guidance_families() {
        let predicate = recommended_next_step(
            &probe(ProbeFamily::Predicate, "value >= threshold"),
            &ExposureClass::WeaklyExposed,
        );
        assert_eq!(
            predicate.as_deref(),
            Some(
                "Add boundary tests for below, equal, and above the changed threshold with exact assertions."
            )
        );

        let error_path = recommended_next_step(
            &probe(ProbeFamily::ErrorPath, "Err(AppError::Denied)"),
            &ExposureClass::WeaklyExposed,
        );
        assert_eq!(
            error_path.as_deref(),
            Some("Assert the exact error variant or payload instead of only is_err().")
        );

        let return_value = recommended_next_step(
            &probe(ProbeFamily::ReturnValue, "count + 1"),
            &ExposureClass::WeaklyExposed,
        );
        assert_eq!(
            return_value.as_deref(),
            Some(
                "Replace broad assertions with exact equality or a property that constrains the changed returned value."
            )
        );
    }

    // RIPR-SPEC-0109 control (a): genuine all-Yes/Medium exposure must not be
    // suppressed — the cap is 1.0 for Medium stages.
    #[test]
    fn confidence_score_genuine_exposure_all_yes_medium_is_not_capped() {
        let score = confidence_score(
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &ExposureClass::Exposed,
        );
        // 5 × Yes = 5 × 0.20 = 1.00; cap = 1.0 (all Medium) → unchanged.
        assert!(
            (score - 1.0).abs() < f32::EPSILON,
            "genuine exposure must report confidence 1.0, got {score}"
        );
    }

    // RIPR-SPEC-0109 control (b): a propagation_unknown finding with
    // propagate.confidence = Low must be capped to ≤ 0.66, and its class
    // must NOT change (class is determined by `classify`, not here).
    #[test]
    fn confidence_score_low_propagate_confidence_caps_score_to_0_66() {
        let low_propagate =
            StageEvidence::new(StageState::Unknown, Confidence::Low, "propagation unknown");
        let score = confidence_score(
            &stage(StageState::Yes),  // reach
            &stage(StageState::Yes),  // infect
            &low_propagate,           // propagate — Low confidence
            &stage(StageState::Yes),  // observe
            &stage(StageState::Weak), // discriminate
            &ExposureClass::PropagationUnknown,
        );
        // Raw: 0.20+0.20+0.07+0.20+0.12 = 0.79; Low cap = 0.66 → score = 0.66.
        assert!(
            score <= 0.66,
            "propagation_unknown with Low confidence must be capped to ≤ 0.66, got {score}"
        );
        // Confirm class is determined independently — classification is
        // asserted via the `classify` fn contract, not here.  The score must
        // be strictly below the uncapped value of 0.79.
        assert!(
            score < 0.79,
            "score must be below uncapped 0.79, got {score}"
        );
    }

    // RIPR-SPEC-0109 control (c): #1232 no-regression — infection_unknown and
    // propagation_unknown classifications must remain unchanged; only the
    // numeric confidence may drop.
    #[test]
    fn confidence_score_cap_does_not_change_classification() {
        // infection_unknown: `let _ = expr` pattern — infect.confidence = Low
        let low_infect =
            StageEvidence::new(StageState::Unknown, Confidence::Low, "infection unknown");
        let infect_class = classify(
            &stage(StageState::Yes),
            &low_infect,
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &probe(ProbeFamily::ReturnValue, "compute()"),
        );
        assert_eq!(
            infect_class,
            ExposureClass::InfectionUnknown,
            "infection_unknown class must be unchanged after RIPR-SPEC-0109"
        );

        // propagation_unknown: `.ok()` swallow — propagate.confidence = Low
        let low_propagate =
            StageEvidence::new(StageState::Unknown, Confidence::Low, "propagation unknown");
        let prop_class = classify(
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &low_propagate,
            &stage(StageState::Yes),
            &stage(StageState::Yes),
            &probe(ProbeFamily::ReturnValue, "self.persist(amount).ok();"),
        );
        assert_eq!(
            prop_class,
            ExposureClass::PropagationUnknown,
            "propagation_unknown class must be unchanged after RIPR-SPEC-0109"
        );
    }

    fn stage(state: StageState) -> StageEvidence {
        StageEvidence::new(state, Confidence::Medium, "stage")
    }

    fn probe(family: ProbeFamily, expression: &str) -> Probe {
        Probe {
            id: ProbeId("probe:test".to_string()),
            location: SourceLocation::new("src/lib.rs", 1, 1),
            owner: None,
            family,
            delta: DeltaKind::Value,
            before: None,
            after: None,
            expression: expression.to_string(),
            expected_sinks: Vec::new(),
            required_oracles: Vec::new(),
        }
    }
}