terni 0.7.0

Ternary error handling: Success, Partial with measured loss, Failure. Because computation is not binary.
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
//! Tests for `Transparency<P>` — the Loss monoid of substrate-located
//! opacities. Tick: prism/transparency 🔴.

use std::collections::BTreeMap;

use terni::{verdict_union, Diagnostic, Loss, PropertyVerdict, Transparency};

// ---------------------------------------------------------------------------
// PropertyVerdict::merge_with
// ---------------------------------------------------------------------------

#[test]
fn merge_with_fail_dominates_partial() {
    let mut a = PropertyVerdict::Partial {
        confidence: 0.9,
        diagnostics: vec![Diagnostic::new("first")],
    };
    let b = PropertyVerdict::Fail(Diagnostic::new("boom"));
    a.merge_with(&b);
    match a {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "boom"),
        other => panic!("expected Fail, got {:?}", other),
    }
}

#[test]
fn merge_with_fail_self_stays_fail() {
    let mut a = PropertyVerdict::Fail(Diagnostic::new("first-boom"));
    let b = PropertyVerdict::Partial {
        confidence: 0.5,
        diagnostics: vec![Diagnostic::new("second")],
    };
    a.merge_with(&b);
    match a {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "first-boom"),
        other => panic!("expected Fail unchanged, got {:?}", other),
    }
}

#[test]
fn merge_with_partials_unions_diagnostics_min_confidence() {
    let mut a = PropertyVerdict::Partial {
        confidence: 0.8,
        diagnostics: vec![Diagnostic::new("d1")],
    };
    let b = PropertyVerdict::Partial {
        confidence: 0.5,
        diagnostics: vec![Diagnostic::new("d2"), Diagnostic::new("d3")],
    };
    a.merge_with(&b);
    match a {
        PropertyVerdict::Partial {
            confidence,
            diagnostics,
        } => {
            assert!(
                (confidence - 0.5).abs() < 1e-12,
                "min wins, got {confidence}"
            );
            let strs: Vec<&str> = diagnostics.iter().map(|d| d.as_str()).collect();
            assert_eq!(strs, vec!["d1", "d2", "d3"]);
        }
        other => panic!("expected Partial, got {:?}", other),
    }
}

#[test]
fn merge_with_pass_is_neutral() {
    // Pass + Partial → Partial unchanged on the other side.
    let mut a = PropertyVerdict::Pass;
    let b = PropertyVerdict::Partial {
        confidence: 0.7,
        diagnostics: vec![Diagnostic::new("d")],
    };
    a.merge_with(&b);
    match a {
        PropertyVerdict::Partial {
            confidence,
            diagnostics,
        } => {
            assert!((confidence - 0.7).abs() < 1e-12);
            assert_eq!(diagnostics.len(), 1);
        }
        other => panic!("expected Partial, got {:?}", other),
    }

    // Partial + Pass → Partial unchanged.
    let mut c = PropertyVerdict::Partial {
        confidence: 0.6,
        diagnostics: vec![Diagnostic::new("c")],
    };
    let d = PropertyVerdict::Pass;
    c.merge_with(&d);
    match c {
        PropertyVerdict::Partial {
            confidence,
            diagnostics,
        } => {
            assert!((confidence - 0.6).abs() < 1e-12);
            assert_eq!(diagnostics.len(), 1);
        }
        other => panic!("expected Partial unchanged, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// PropertyVerdict::merge_with — Pass-paired completeness (Seam I5).
//
// `merge_with_pass_is_neutral` above exercises Pass+Partial and Partial+Pass.
// The remaining Pass-paired arms (Pass+Pass, Pass+Fail, Fail+Pass) round out
// the coverage of the documented monoid. These cases shouldn't usually arise
// inside an Opaque map — the per-location verdict carriers are populated
// only for non-Pass locations — but the code paths exist and must remain
// witnessed.
// ---------------------------------------------------------------------------

#[test]
fn merge_with_pass_and_pass_stays_pass() {
    let mut a = PropertyVerdict::Pass;
    let b = PropertyVerdict::Pass;
    a.merge_with(&b);
    match a {
        PropertyVerdict::Pass => {}
        other => panic!("expected Pass, got {:?}", other),
    }
}

#[test]
fn merge_with_pass_and_fail_yields_fail() {
    let mut a = PropertyVerdict::Pass;
    let b = PropertyVerdict::Fail(Diagnostic::new("boom"));
    a.merge_with(&b);
    match a {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "boom"),
        other => panic!("expected Fail, got {:?}", other),
    }
}

#[test]
fn merge_with_fail_and_pass_stays_fail() {
    // Fail-self short-circuits in the first arm of merge_with, but the
    // observable behaviour from a caller's perspective is the same: Fail
    // survives a Pass on the right.
    let mut a = PropertyVerdict::Fail(Diagnostic::new("boom"));
    let b = PropertyVerdict::Pass;
    a.merge_with(&b);
    match a {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "boom"),
        other => panic!("expected Fail, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// verdict_union
// ---------------------------------------------------------------------------

#[test]
fn verdict_union_disjoint_keys_merge() {
    let mut a: BTreeMap<String, PropertyVerdict> = BTreeMap::new();
    a.insert(
        "@a".into(),
        PropertyVerdict::Partial {
            confidence: 0.9,
            diagnostics: vec![Diagnostic::new("a")],
        },
    );
    let mut b: BTreeMap<String, PropertyVerdict> = BTreeMap::new();
    b.insert(
        "@b".into(),
        PropertyVerdict::Fail(Diagnostic::new("b-boom")),
    );
    let merged = verdict_union(a, b);
    assert_eq!(merged.len(), 2);
    assert!(matches!(merged["@a"], PropertyVerdict::Partial { .. }));
    assert!(matches!(merged["@b"], PropertyVerdict::Fail(_)));
}

#[test]
fn verdict_union_colliding_keys_merge_via_merge_with() {
    let mut a: BTreeMap<String, PropertyVerdict> = BTreeMap::new();
    a.insert(
        "@x".into(),
        PropertyVerdict::Partial {
            confidence: 0.8,
            diagnostics: vec![Diagnostic::new("d1")],
        },
    );
    let mut b: BTreeMap<String, PropertyVerdict> = BTreeMap::new();
    b.insert("@x".into(), PropertyVerdict::Fail(Diagnostic::new("boom")));
    let merged = verdict_union(a, b);
    assert_eq!(merged.len(), 1);
    match &merged["@x"] {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "boom"),
        other => panic!("expected Fail to dominate, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// Transparency<P> — Clear/Opaque enum + Loss laws
// ---------------------------------------------------------------------------

#[test]
fn clear_is_zero_is_default() {
    let z: Transparency<String> = Transparency::zero();
    assert!(z.is_zero());
    assert!(matches!(z, Transparency::Clear));
    let d: Transparency<String> = Transparency::default();
    assert!(d.is_zero());
}

#[test]
fn catastrophic_is_total_and_opaque() {
    let t: Transparency<String> = Transparency::total();
    assert!(!t.is_zero());
    assert!(t.is_catastrophic());
    assert!(t.is_opaque());
    let c: Transparency<String> = Transparency::catastrophic();
    assert!(c.is_catastrophic());
    assert_eq!(t, c);
}

#[test]
fn single_constructs_opaque_with_one_entry() {
    let t = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("nope")),
    );
    let map = t.opacities().expect("single should produce Opaque");
    assert_eq!(map.len(), 1);
    assert!(map.contains_key("@p"));
}

#[test]
fn combine_clear_neutral_left() {
    let z: Transparency<String> = Transparency::clear();
    let t = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("x")),
    );
    let combined = z.combine(t.clone());
    assert_eq!(combined, t);
}

#[test]
fn combine_clear_neutral_right() {
    let z: Transparency<String> = Transparency::clear();
    let t = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("x")),
    );
    let combined = t.clone().combine(z);
    assert_eq!(combined, t);
}

#[test]
fn combine_two_opaques_unions_maps() {
    let a = Transparency::single(
        "@a".to_string(),
        PropertyVerdict::Partial {
            confidence: 0.9,
            diagnostics: vec![Diagnostic::new("a")],
        },
    );
    let b = Transparency::single(
        "@b".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("b-boom")),
    );
    let merged = a.combine(b);
    let map = merged
        .opacities()
        .expect("combined opaques should be Opaque");
    assert_eq!(map.len(), 2, "disjoint keys union");
    assert!(map.contains_key("@a"));
    assert!(map.contains_key("@b"));
}

#[test]
fn combine_catastrophic_left_absorbs() {
    let cat: Transparency<String> = Transparency::catastrophic();
    let t = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Partial {
            confidence: 0.5,
            diagnostics: vec![],
        },
    );
    let out = cat.combine(t);
    assert!(out.is_catastrophic(), "catastrophic absorbs from the left");
}

#[test]
fn combine_catastrophic_right_absorbs() {
    let cat: Transparency<String> = Transparency::catastrophic();
    let t = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Partial {
            confidence: 0.5,
            diagnostics: vec![],
        },
    );
    let out = t.combine(cat);
    assert!(out.is_catastrophic(), "catastrophic absorbs from the right");
}

#[test]
fn combine_colliding_paths_merges_verdicts() {
    let a = Transparency::single(
        "@x".to_string(),
        PropertyVerdict::Partial {
            confidence: 0.9,
            diagnostics: vec![Diagnostic::new("d1")],
        },
    );
    let b = Transparency::single(
        "@x".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("d2-boom")),
    );
    let merged = a.combine(b);
    let map = merged
        .opacities()
        .expect("combined opaques should be Opaque");
    assert_eq!(map.len(), 1);
    match &map["@x"] {
        PropertyVerdict::Fail(d) => assert_eq!(d.as_str(), "d2-boom"),
        other => panic!("expected Fail to dominate at collision, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// P is not Default — instantiate Transparency over a non-Default type to
// witness that the bound is gone.
// ---------------------------------------------------------------------------

/// A path-shaped type with NO `Default` impl. If Transparency required
/// `P: Default`, this test wouldn't compile.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct NoDefaultPath(String);

#[test]
fn transparency_does_not_require_p_default() {
    let p = NoDefaultPath("@no-default".to_string());
    let t: Transparency<NoDefaultPath> = Transparency::single(
        p.clone(),
        PropertyVerdict::Partial {
            confidence: 0.5,
            diagnostics: vec![Diagnostic::new("hi")],
        },
    );
    let z: Transparency<NoDefaultPath> = Transparency::zero();
    let cat: Transparency<NoDefaultPath> = Transparency::total();
    assert!(z.is_zero());
    assert!(cat.is_catastrophic());
    assert!(t.is_opaque_at(&p));
}

// ---------------------------------------------------------------------------
// Loss laws sanity
// ---------------------------------------------------------------------------

#[test]
fn combine_associative_disjoint_paths() {
    // (a + b) + c == a + (b + c) on disjoint paths.
    let mk = |path: &str, msg: &str| {
        Transparency::single(
            path.to_string(),
            PropertyVerdict::Partial {
                confidence: 1.0,
                diagnostics: vec![Diagnostic::new(msg)],
            },
        )
    };
    let a = mk("@a", "a");
    let b = mk("@b", "b");
    let c = mk("@c", "c");
    let lhs = a.clone().combine(b.clone()).combine(c.clone());
    let rhs = a.combine(b.combine(c));
    assert_eq!(lhs, rhs);
}

// ---------------------------------------------------------------------------
// Transparency::opaque — public constructor that prevents empty-map forge
// by input shape (Seam I1).
//
// The raw `Opaque(BTreeMap)` variant is `pub(crate)`: outside callers can
// no longer write `Transparency::Opaque(BTreeMap::new())` to forge the
// catastrophic sentinel. The new `opaque(ref, verdict)` constructor takes
// a required first verdict, making empty construction structurally
// impossible from the call site.
// ---------------------------------------------------------------------------

#[test]
fn opaque_constructor_builds_non_empty_opaque() {
    let t: Transparency<String> = Transparency::opaque(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("boom")),
    );
    assert!(t.is_opaque());
    assert!(
        !t.is_catastrophic(),
        "opaque() must never forge catastrophic"
    );
    let map = t.opacities().expect("opaque must produce Opaque");
    assert_eq!(map.len(), 1);
    assert!(map.contains_key("@p"));
}

#[test]
fn opaque_constructor_matches_single() {
    // Today `opaque` is the renamed-canonical form alongside `single` (which
    // stays for the existing callers). They produce structurally identical
    // values for the single-pair case.
    let a: Transparency<String> = Transparency::opaque(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("x")),
    );
    let b: Transparency<String> = Transparency::single(
        "@p".to_string(),
        PropertyVerdict::Fail(Diagnostic::new("x")),
    );
    assert_eq!(a, b);
}