evidencebook 0.0.23

Evidence book: records, epistemic types, typed links, retention, disclosure, index classes, request answers and reconcile/close over an embedded Checkpointed Local Log -- a Rust implementation of the Evidence Layer semantics.
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Reconcile two independently held accounts, and read a Close's status.
//!
//! I-D section: *Reconcile and Close*.
//!
//! Reconciliation pairs one side's halves with the other's and puts every
//! half seen on either side into exactly one of six states. It is code, not
//! judgment: the only content test is the profile's [`Comparator`].
//!
//! **One half unavailable is not disagreement.** An unpaired half is
//! `A_ONLY`/`B_ONLY` when the other side's account is complete, `INSUFFICIENT`
//! otherwise, and never `CONFLICTING`.
//!
//! The correlation keys are the calling profile's. A [`JoinPolicy`] names
//! them: a primary key, a secondary key tried only for halves the primary
//! left unpaired, and an optional grouping key that is recorded when both
//! halves carry the same value and never joined on. Pairing and
//! classification follow the Go implementation's `ReconcileHalves` given a
//! policy of its three keys: a correlation id as the primary key, the request
//! digest as the secondary, and a paired-run id as the grouping key. The
//! consuming plugin's `tests/reconcile_parity.rs` checks that on the fixture
//! Go and Python both check. Result member names (`group`) are this
//! crate's own.

use crate::record::{Header, LinkType};
use crate::store::{CheckpointedLog, RecordSource};
use crate::substrate::SubstrateError;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// A pairing's state (I-D *Reconcile and Close*).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PairState {
    /// Both sides hold covered, trusted, corresponding records that agree.
    Matched,
    /// Only side A holds it, and B's account is complete.
    AOnly,
    /// Only side B holds it, and A's account is complete.
    BOnly,
    /// Both sides hold a corresponding record and they disagree.
    Conflicting,
    /// The evidence cannot decide: a half is uncovered, or absence is not
    /// provable because the other account is incomplete.
    Insufficient,
    /// Paired and covered, but a half does not verify.
    Unresolved,
}

impl PairState {
    pub const ALL: [PairState; 6] = [
        PairState::Matched,
        PairState::AOnly,
        PairState::BOnly,
        PairState::Conflicting,
        PairState::Insufficient,
        PairState::Unresolved,
    ];
}

/// Which correlation keys pair two halves, in preference order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JoinPolicy {
    /// Tried first. An agreeing primary key whose secondary keys both exist
    /// and disagree is `CONFLICTING`, never re-paired on the secondary.
    pub primary: String,
    /// Tried for halves still unpaired after the primary pass.
    pub secondary: String,
    /// Recorded on a pair when both halves carry the same value; never a join
    /// key.
    pub group: Option<String>,
}

/// One side's record of one interaction, as reconciliation sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Half {
    pub record_id: String,
    pub seq: u64,
    /// Correlation keys by name; an empty value is treated as absent.
    pub correlation: BTreeMap<String, String>,
    pub payload_commitments: Vec<String>,
    /// Inside an authenticated checkpoint.
    pub covered: bool,
    /// The record verifies and its header matches what it committed.
    pub trusted: bool,
    /// Records an interaction that did not complete (refused, errored, timed out
    /// or dropped). A header carries no outcome, so the caller sets it from
    /// the record's own outcome; the default is a completed one. A failed
    /// half has no payload commitments to compare, so its pair is decided by
    /// the outcomes, never by the content test.
    pub failed: bool,
}

impl Half {
    fn key(&self, name: &str) -> Option<&str> {
        self.correlation
            .get(name)
            .map(String::as_str)
            .filter(|v| !v.is_empty())
    }

    /// No correlation value at all, under any key name. Such a half could be
    /// anyone's counterpart, so its absence on the other side is not provable.
    fn has_no_keys(&self) -> bool {
        self.correlation.values().all(String::is_empty)
    }
}

/// One side's account of a period. `complete` means the account is
/// checkpoint-covered end to end, so a missing counterpart on this side is a
/// provable absence rather than an unknown.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HalfSet {
    pub halves: Vec<Half>,
    pub complete: bool,
}

impl HalfSet {
    /// One side's halves read from its store: the records whose committed
    /// entries are `ids`, in that order (an id the store does not hold is no
    /// half). A half is `covered` when the store's latest stated checkpoint
    /// covers its leaf, and `trusted` when its octets recompute its entry
    /// ([`RecordSource::entry_of`]) and are a header that validates; an
    /// untrusted half keeps no correlation keys or commitments, so it can
    /// pair with nothing. `complete` is the caller's judgment of the account
    /// as a whole.
    pub fn from_store(
        log: &dyn CheckpointedLog,
        records: &dyn RecordSource,
        ids: &[String],
        complete: bool,
    ) -> Result<Self, SubstrateError> {
        let covered = match log.stated_checkpoints()?.last() {
            Some(cp) => cp.checkpoint.leaf_count()?,
            None => 0,
        };
        let halves = ids
            .iter()
            .filter_map(|id| records.record_by_digest(id).filter(|r| r.digest == *id))
            .map(|r| {
                let header = (records.entry_of(&r.body).as_deref() == Some(r.digest.as_str()))
                    .then(|| serde_json::from_slice::<Header>(&r.body).ok())
                    .flatten()
                    .filter(|h| h.validate().is_ok());
                let (seq, correlation, payload_commitments, trusted) = match header {
                    Some(h) => (h.seq, h.correlation, h.payload_commitments, true),
                    None => (0, BTreeMap::new(), Vec::new(), false),
                };
                Half {
                    record_id: r.digest,
                    seq,
                    correlation,
                    payload_commitments,
                    covered: r.leaf_index < covered,
                    trusted,
                    failed: false,
                }
            })
            .collect();
        Ok(Self { halves, complete })
    }
}

/// The profile's content test. Runs only on covered, trusted, correlated
/// pairs; returns whether their contents agree.
pub type Comparator<'a> = &'a dyn Fn(&Half, &Half) -> bool;

/// A comparator for deterministic content: both halves committed the same,
/// non-empty list of payload digests. Sampled content needs a comparator over
/// the disclosed content instead.
pub fn same_payload_commitments(a: &Half, b: &Half) -> bool {
    !a.payload_commitments.is_empty() && a.payload_commitments == b.payload_commitments
}

/// One classified pairing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PairResult {
    pub state: PairState,
    /// The name of the key the pair was joined on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub join_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub a: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub b: Option<String>,
    /// The grouping key's value, when both halves carry the same one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
}

/// Count of pairings per state.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tallies {
    #[serde(rename = "MATCHED")]
    pub matched: usize,
    #[serde(rename = "A_ONLY")]
    pub a_only: usize,
    #[serde(rename = "B_ONLY")]
    pub b_only: usize,
    #[serde(rename = "CONFLICTING")]
    pub conflicting: usize,
    #[serde(rename = "INSUFFICIENT")]
    pub insufficient: usize,
    #[serde(rename = "UNRESOLVED")]
    pub unresolved: usize,
}

impl Tallies {
    fn add(&mut self, state: PairState) {
        match state {
            PairState::Matched => self.matched += 1,
            PairState::AOnly => self.a_only += 1,
            PairState::BOnly => self.b_only += 1,
            PairState::Conflicting => self.conflicting += 1,
            PairState::Insufficient => self.insufficient += 1,
            PairState::Unresolved => self.unresolved += 1,
        }
    }
}

/// Pair side A's halves with side B's and classify every half seen on either
/// side into exactly one of the six states.
///
/// Correlation runs in two passes over all halves, so the result does not
/// depend on input order within a side: first the primary key (preferring a
/// counterpart of the same outcome whose secondary key also agrees), then the
/// secondary key for halves still unpaired.
///
/// Classification keeps the key conflict, then an uncovered half
/// (`INSUFFICIENT`), then an untrusted half (`UNRESOLVED`), then the outcomes:
/// two failed halves are `MATCHED` (each side's reason is its own view and is
/// not compared), and a failed half against a served one is `CONFLICTING`, so
/// one side that timed out while the other finished is a disagreement,
/// never a missing peer half. Only two served halves reach the content test.
pub fn reconcile_halves(
    a: &HalfSet,
    b: &HalfSet,
    policy: &JoinPolicy,
    compare: Comparator<'_>,
) -> (Vec<PairResult>, Tallies) {
    let mut partner: Vec<Option<usize>> = vec![None; a.halves.len()];
    let mut joined_on: Vec<Option<&str>> = vec![None; a.halves.len()];
    let mut used = vec![false; b.halves.len()];

    // First unused B half satisfying `matches`.
    let pick = |used: &[bool], matches: &dyn Fn(&Half) -> bool| {
        b.halves
            .iter()
            .enumerate()
            .find(|(j, h)| !used[*j] && matches(h))
            .map(|(j, _)| j)
    };

    // The primary join runs in tiers over all of side A before the next tier
    // starts, so an earlier half's fallback never takes the partner a later
    // half matches better: the same outcome with the same secondary key, the
    // same outcome with a compatible one, the same outcome (a secondary
    // disagreement is then reported as the key conflict), then any outcome (a
    // one side that timed out against another that finished). A failed
    // half carries no secondary key, so without the outcome tiers it would
    // rank with a served half.
    let compatible = |x: &Half, y: &Half| match (x.key(&policy.secondary), y.key(&policy.secondary))
    {
        (Some(p), Some(q)) => p == q,
        _ => true,
    };
    type Tier<'t> = &'t dyn Fn(&Half, &Half) -> bool;
    let tiers: [Tier<'_>; 5] = [
        &|own, h| {
            h.failed == own.failed
                && own.key(&policy.secondary).is_some()
                && own.key(&policy.secondary) == h.key(&policy.secondary)
        },
        &|own, h| h.failed == own.failed && compatible(own, h),
        &|own, h| h.failed == own.failed,
        &|own, h| compatible(own, h),
        &|_, _| true,
    ];
    for tier in tiers {
        for (i, own) in a.halves.iter().enumerate() {
            if partner[i].is_some() {
                continue;
            }
            let Some(primary) = own.key(&policy.primary) else {
                continue;
            };
            if let Some(j) = pick(&used, &|h| {
                h.key(&policy.primary) == Some(primary) && tier(own, h)
            }) {
                partner[i] = Some(j);
                joined_on[i] = Some(&policy.primary);
                used[j] = true;
            }
        }
    }
    for (i, own) in a.halves.iter().enumerate() {
        if partner[i].is_some() {
            continue;
        }
        let Some(secondary) = own.key(&policy.secondary) else {
            continue;
        };
        if let Some(j) = pick(&used, &|h| h.key(&policy.secondary) == Some(secondary)) {
            partner[i] = Some(j);
            joined_on[i] = Some(&policy.secondary);
            used[j] = true;
        }
    }

    let mut results = Vec::with_capacity(a.halves.len() + b.halves.len());
    for (i, own) in a.halves.iter().enumerate() {
        let Some(j) = partner[i] else {
            let provable = own.covered && b.complete && !own.has_no_keys();
            results.push(PairResult {
                state: if provable {
                    PairState::AOnly
                } else {
                    PairState::Insufficient
                },
                join_key: None,
                a: Some(own.record_id.clone()),
                b: None,
                group: None,
            });
            continue;
        };
        let peer = &b.halves[j];
        let key = joined_on[i].expect("a paired half records its join key");
        let group = policy
            .group
            .as_deref()
            .and_then(|g| own.key(g).filter(|v| peer.key(g) == Some(*v)))
            .map(str::to_string);
        let secondaries_disagree = matches!(
            (own.key(&policy.secondary), peer.key(&policy.secondary)),
            (Some(x), Some(y)) if x != y
        );
        let state = if key == policy.primary && secondaries_disagree {
            PairState::Conflicting
        } else if !own.covered || !peer.covered {
            PairState::Insufficient
        } else if !own.trusted || !peer.trusted {
            PairState::Unresolved
        } else if own.failed && peer.failed {
            PairState::Matched
        } else if own.failed != peer.failed {
            PairState::Conflicting
        } else if compare(own, peer) {
            PairState::Matched
        } else {
            PairState::Conflicting
        };
        results.push(PairResult {
            state,
            join_key: Some(key.to_string()),
            a: Some(own.record_id.clone()),
            b: Some(peer.record_id.clone()),
            group,
        });
    }
    for (j, peer) in b.halves.iter().enumerate() {
        if used[j] {
            continue;
        }
        let provable = peer.covered && a.complete && !peer.has_no_keys();
        results.push(PairResult {
            state: if provable {
                PairState::BOnly
            } else {
                PairState::Insufficient
            },
            join_key: None,
            a: None,
            b: Some(peer.record_id.clone()),
            group: None,
        });
    }

    let mut tallies = Tallies::default();
    for r in &results {
        tallies.add(r.state);
    }
    (results, tallies)
}

/// A Close's status, read from the links the counterparty's records make to
/// it -- never from a field the Close sets itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CloseStatus {
    /// A counterparty record carries an `acknowledges` link to the Close.
    Agreed,
    /// No counterparty record links to the Close yet.
    Unilateral,
    /// A counterparty record carries a `rebuts` link to the Close.
    Contested,
}

/// The status of Close `close_id`, given the links carried by records the
/// caller has already authenticated as the counterparty's. A rebuttal
/// outranks an acknowledgement. A later adjustment is a new Close carrying a
/// `supersedes` link; the original is never rewritten.
pub fn close_status<'a>(
    close_id: &str,
    counterparty_links: impl IntoIterator<Item = (LinkType, &'a str)>,
) -> CloseStatus {
    let mut status = CloseStatus::Unilateral;
    for (link_type, target) in counterparty_links {
        if target != close_id {
            continue;
        }
        match link_type {
            LinkType::Rebuts => return CloseStatus::Contested,
            LinkType::Acknowledges => status = CloseStatus::Agreed,
            _ => {}
        }
    }
    status
}

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

    fn policy() -> JoinPolicy {
        JoinPolicy {
            primary: "k1".into(),
            secondary: "k2".into(),
            group: Some("g".into()),
        }
    }

    fn keys(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    fn half(id: &str, correlation: &[(&str, &str)], payload: &str) -> Half {
        Half {
            record_id: id.into(),
            seq: 1,
            correlation: keys(correlation),
            payload_commitments: vec![crate::canonical::json_digest(&payload.into()).unwrap()],
            covered: true,
            trusted: true,
            failed: false,
        }
    }

    fn failed(id: &str, correlation: &[(&str, &str)]) -> Half {
        Half {
            payload_commitments: Vec::new(),
            failed: true,
            ..half(id, correlation, "")
        }
    }

    fn by_pair(results: &[PairResult]) -> BTreeMap<String, PairState> {
        results
            .iter()
            .map(|r| {
                (
                    format!(
                        "{}|{}",
                        r.a.as_deref().unwrap_or(""),
                        r.b.as_deref().unwrap_or("")
                    ),
                    r.state,
                )
            })
            .collect()
    }

    /// Port of the Go implementation's TestReconcileSixStates.
    #[test]
    fn every_state_is_reachable_and_each_half_lands_in_exactly_one() {
        let mut uncovered = half("a-uncovered", &[("k1", "x4")], "u");
        uncovered.covered = false;
        let mut untrusted = half("a-untrusted", &[("k1", "x5")], "t");
        untrusted.trusted = false;
        let a = HalfSet {
            complete: true,
            halves: vec![
                half("a-matched", &[("k1", "x1")], "same"),
                half("a-conflicting", &[("k1", "x2")], "mine"),
                half("a-only", &[("k1", "x3")], "lonely"),
                uncovered,
                untrusted,
            ],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                half("b-matched", &[("k1", "x1")], "same"),
                half("b-conflicting", &[("k1", "x2")], "theirs"),
                half("b-uncovered-pair", &[("k1", "x4")], "p"),
                half("b-untrusted-pair", &[("k1", "x5")], "q"),
                half("b-only", &[("k1", "x6")], "alone"),
            ],
        };
        let (results, tallies) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(
            tallies,
            Tallies {
                matched: 1,
                a_only: 1,
                b_only: 1,
                conflicting: 1,
                insufficient: 1,
                unresolved: 1
            }
        );
        let got = by_pair(&results);
        for (pair, state) in [
            ("a-matched|b-matched", PairState::Matched),
            ("a-conflicting|b-conflicting", PairState::Conflicting),
            ("a-only|", PairState::AOnly),
            ("a-uncovered|b-uncovered-pair", PairState::Insufficient),
            ("a-untrusted|b-untrusted-pair", PairState::Unresolved),
            ("|b-only", PairState::BOnly),
        ] {
            assert_eq!(got.get(pair), Some(&state), "{pair}: {results:?}");
        }
    }

    /// Port of the Go implementation's TestOneHalfUnavailableIsNotDisagreement:
    /// a comparator that always disagrees never turns an unpaired half into
    /// CONFLICTING.
    #[test]
    fn one_half_unavailable_is_not_disagreement() {
        let disagree = |_: &Half, _: &Half| false;
        for complete in [true, false] {
            let a = HalfSet {
                complete,
                halves: vec![half("a1", &[("k2", "r1")], "x")],
            };
            let b = HalfSet {
                complete,
                halves: vec![half("b1", &[("k2", "r2")], "y")],
            };
            let (_, t) = reconcile_halves(&a, &b, &policy(), &disagree);
            assert_eq!(t.conflicting, 0, "complete={complete}: {t:?}");
            let only = usize::from(complete);
            assert_eq!(
                (t.a_only, t.b_only, t.insufficient),
                (only, only, 2 - 2 * only)
            );
        }
    }

    #[test]
    fn agreeing_primary_with_disagreeing_secondary_conflicts_and_is_not_repaired() {
        let a = HalfSet {
            complete: true,
            halves: vec![half("a", &[("k1", "x"), ("k2", "r1")], "p")],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                half("b", &[("k1", "x"), ("k2", "r2")], "p"),
                half("b-other", &[("k2", "r1")], "p"),
            ],
        };
        let (results, t) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(results[0].state, PairState::Conflicting);
        assert_eq!(results[0].join_key.as_deref(), Some("k1"));
        assert_eq!(results[0].b.as_deref(), Some("b"));
        assert_eq!(t.b_only, 1, "b-other stays unpaired: {results:?}");
    }

    #[test]
    fn primary_pass_prefers_a_counterpart_whose_secondary_agrees() {
        let a = HalfSet {
            complete: true,
            halves: vec![half("a", &[("k1", "x"), ("k2", "r1")], "p")],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                half("b-wrong", &[("k1", "x"), ("k2", "r9")], "p"),
                half("b-right", &[("k1", "x"), ("k2", "r1")], "p"),
            ],
        };
        let (results, _) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(results[0].b.as_deref(), Some("b-right"));
        assert_eq!(results[0].state, PairState::Matched);
    }

    #[test]
    fn secondary_joins_only_what_the_primary_left_unpaired() {
        let a = HalfSet {
            complete: true,
            halves: vec![half("a", &[("k1", "x"), ("k2", "r1")], "p")],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![half("b", &[("k1", "y"), ("k2", "r1")], "p")],
        };
        let (results, _) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].join_key.as_deref(), Some("k2"));
        assert_eq!(results[0].state, PairState::Matched);
    }

    #[test]
    fn the_group_key_is_recorded_when_shared_and_never_joins() {
        let a = HalfSet {
            complete: true,
            halves: vec![
                half("a1", &[("k1", "x"), ("g", "grp")], "p"),
                half("a2", &[("g", "grp-2")], "p"),
            ],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                half("b1", &[("k1", "x"), ("g", "grp")], "p"),
                half("b2", &[("g", "grp-2")], "p"),
            ],
        };
        let (results, t) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(results[0].group.as_deref(), Some("grp"));
        assert_eq!(t.matched, 1);
        assert_eq!((t.a_only, t.b_only), (1, 1), "{results:?}");
    }

    #[test]
    fn the_group_key_is_not_recorded_unless_both_halves_carry_the_same_value() {
        for peer_group in [None, Some("other")] {
            let mut peer_keys = vec![("k1", "x")];
            peer_keys.extend(peer_group.map(|g| ("g", g)));
            let a = HalfSet {
                complete: true,
                halves: vec![half("a", &[("k1", "x"), ("g", "grp")], "p")],
            };
            let b = HalfSet {
                complete: true,
                halves: vec![half("b", &peer_keys, "p")],
            };
            let (results, _) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
            assert_eq!(results[0].state, PairState::Matched);
            assert_eq!(results[0].group, None, "peer group {peer_group:?}");
        }
    }

    #[test]
    fn a_half_carrying_only_a_group_key_is_provably_absent_without_a_group_policy() {
        let no_group = JoinPolicy {
            group: None,
            ..policy()
        };
        let a = HalfSet {
            complete: true,
            halves: vec![half("a", &[("g", "grp")], "p")],
        };
        let (_, t) = reconcile_halves(
            &a,
            &HalfSet {
                complete: true,
                halves: vec![],
            },
            &no_group,
            &same_payload_commitments,
        );
        assert_eq!((t.a_only, t.insufficient), (1, 0));
    }

    #[test]
    fn a_half_with_no_keys_is_insufficient_even_against_a_complete_account() {
        let a = HalfSet {
            complete: true,
            halves: vec![half("a", &[], "p")],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![],
        };
        let (_, t) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(t.insufficient, 1);
        assert_eq!(t.a_only, 0);
    }

    /// Mirror of the Go TestReconcileFailedHalves.
    #[test]
    fn failed_halves_pair_by_outcome_and_never_reach_the_content_test() {
        let a = HalfSet {
            complete: true,
            halves: vec![
                failed("a-402", &[("k1", "x1")]),
                failed("a-timeout", &[("k1", "x2")]),
                half("a-served", &[("k1", "x3"), ("k2", "d3")], "same"),
                failed("a-alone", &[("k1", "x4")]),
            ],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                failed("b-402", &[("k1", "x1")]),
                half("b-finished", &[("k1", "x2"), ("k2", "d2")], "done"),
                failed("b-failed", &[("k1", "x3")]),
            ],
        };
        let never = |_: &Half, _: &Half| -> bool { panic!("content test ran on a failed half") };
        let (results, tallies) = reconcile_halves(&a, &b, &policy(), &never);
        assert_eq!(
            tallies,
            Tallies {
                matched: 1,
                conflicting: 2,
                a_only: 1,
                ..Tallies::default()
            }
        );
        let got = by_pair(&results);
        for (pair, state) in [
            ("a-402|b-402", PairState::Matched),
            ("a-timeout|b-finished", PairState::Conflicting),
            ("a-served|b-failed", PairState::Conflicting),
            ("a-alone|", PairState::AOnly),
        ] {
            assert_eq!(got.get(pair), Some(&state), "{pair}: {results:?}");
        }
    }

    #[test]
    fn a_failed_half_is_still_gated_by_coverage_and_trust() {
        let mut uncovered = failed("a-uncovered", &[("k1", "x1")]);
        uncovered.covered = false;
        let mut untrusted = failed("a-untrusted", &[("k1", "x2")]);
        untrusted.trusted = false;
        let a = HalfSet {
            complete: true,
            halves: vec![uncovered, untrusted],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![failed("b1", &[("k1", "x1")]), failed("b2", &[("k1", "x2")])],
        };
        let (_, tallies) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        assert_eq!(
            tallies,
            Tallies {
                insufficient: 1,
                unresolved: 1,
                ..Tallies::default()
            }
        );
    }

    /// A failed attempt and a served retry can share a primary key on one
    /// side; each pairs with the same-outcome half whatever the input order.
    #[test]
    fn a_failed_attempt_and_a_served_retry_pair_by_outcome() {
        let served = |id: &str| half(id, &[("k1", "x1"), ("k2", "d1")], "same");
        for b_halves in [
            vec![failed("b-failed", &[("k1", "x1")]), served("b-served")],
            vec![served("b-served"), failed("b-failed", &[("k1", "x1")])],
        ] {
            let a = HalfSet {
                complete: true,
                halves: vec![served("a-served"), failed("a-failed", &[("k1", "x1")])],
            };
            let b = HalfSet {
                complete: true,
                halves: b_halves,
            };
            let (results, tallies) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
            assert_eq!(
                tallies,
                Tallies {
                    matched: 2,
                    ..Tallies::default()
                },
                "{results:?}"
            );
            let got = by_pair(&results);
            assert_eq!(got.get("a-served|b-served"), Some(&PairState::Matched));
            assert_eq!(got.get("a-failed|b-failed"), Some(&PairState::Matched));
        }
    }

    /// The tiers run over all of side A before the next starts, so an earlier
    /// half's fallback never takes the partner a later half matches better.
    #[test]
    fn an_earlier_halfs_fallback_never_takes_a_later_halfs_better_partner() {
        let a = HalfSet {
            complete: true,
            halves: vec![
                half("a1", &[("k1", "x")], "same"),
                half("a2", &[("k1", "x"), ("k2", "d1")], "same"),
            ],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![
                half("b1", &[("k1", "x"), ("k2", "d1")], "same"),
                half("b2", &[("k1", "x"), ("k2", "d9")], "same"),
            ],
        };
        let (results, tallies) = reconcile_halves(&a, &b, &policy(), &same_payload_commitments);
        let got = by_pair(&results);
        assert_eq!(got.get("a2|b1"), Some(&PairState::Matched), "{results:?}");
        assert_eq!(got.get("a1|b2"), Some(&PairState::Matched), "{results:?}");
        assert_eq!(
            tallies,
            Tallies {
                matched: 2,
                ..Tallies::default()
            }
        );
    }

    /// A key conflict outranks the outcomes: two failed halves whose secondary
    /// keys disagree are CONFLICTING, not MATCHED.
    #[test]
    fn a_key_conflict_outranks_two_failed_halves() {
        let a = HalfSet {
            complete: true,
            halves: vec![failed("a", &[("k1", "x"), ("k2", "r1")])],
        };
        let b = HalfSet {
            complete: true,
            halves: vec![failed("b", &[("k1", "x"), ("k2", "r2")])],
        };
        let never = |_: &Half, _: &Half| -> bool { panic!("content test ran on a failed half") };
        let (results, tallies) = reconcile_halves(&a, &b, &policy(), &never);
        assert_eq!(by_pair(&results).get("a|b"), Some(&PairState::Conflicting));
        assert_eq!(
            tallies,
            Tallies {
                conflicting: 1,
                ..Tallies::default()
            }
        );
    }

    #[test]
    fn tallies_serialize_under_the_state_tokens() {
        let v = serde_json::to_value(Tallies::default()).unwrap();
        for s in PairState::ALL {
            let token = serde_json::to_value(s).unwrap();
            assert!(v.get(token.as_str().unwrap()).is_some(), "{token}");
        }
    }

    #[test]
    fn close_status_reads_the_counterpartys_links() {
        let id = "c".repeat(64);
        let other = "d".repeat(64);
        assert_eq!(close_status(&id, []), CloseStatus::Unilateral);
        assert_eq!(
            close_status(&id, [(LinkType::Acknowledges, other.as_str())]),
            CloseStatus::Unilateral
        );
        assert_eq!(
            close_status(&id, [(LinkType::Acknowledges, id.as_str())]),
            CloseStatus::Agreed
        );
        assert_eq!(
            close_status(
                &id,
                [
                    (LinkType::Acknowledges, id.as_str()),
                    (LinkType::Rebuts, id.as_str())
                ]
            ),
            CloseStatus::Contested
        );
        assert_eq!(
            close_status(&id, [(LinkType::Cites, id.as_str())]),
            CloseStatus::Unilateral
        );
    }
}