rabs-cas 2.1.0

Durable RABS content-addressed storage, action-cache indexing, object lifecycle, and publication transactions
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! Append-only evidence indexing and versioned trust promotion/demotion
//! (bead H033; invariant I42; risk R99).
//!
//! A committed publication is history: promotion, demotion, policy
//! change, and post-publication compromise NEVER rewrite its canonical
//! bytes. Everything that moves lives in three places the store already
//! separates —
//!
//! - the **evidence index** (`action_evidence_index`, H011): append-only,
//!   idempotent per digest; its canonically sorted + deduplicated ID set
//!   names the evidence state via [`evidence_set_digest`] (the same
//!   canonicalization law as `rabs_protocol::serving::
//!   evidence_set_digest_input` — insertion order and duplicates can
//!   never rename a set);
//! - the **trust-evaluation ledger** (`action_trust_evaluations`, H038):
//!   append-only, strictly versioned, authority-gated;
//! - the **mutable serving disposition** (`action_serving_states`).
//!
//! [`reevaluate_action`] recomputes serving from the CURRENT evidence
//! under the LATEST NON-REVOKED policy. Only distinct, attributable
//! attempts belonging to this action derive a positive observed tier.
//! Failed samples remain adverse evidence. Neither positive evidence nor
//! a weaker policy releases existing quarantine or named blockers: that
//! requires the explicit repair flow, not ordinary reevaluation.
//! Observable-only divergence retains its narrower presentation quarantine;
//! stronger blockers or adverse evidence still require full quarantine.
//!
//! With no active policy an ordinary evaluation leaves state untouched.
//! A compromise report is different: durable quarantine is written
//! BEFORE appending the report or evaluating policy, so a missing policy
//! or interrupted evaluation cannot leave the compromised result usable.
//!
//! Write ordering inside one evaluation (each store call is its own
//! transaction): quarantine first, ledger second, disposition LAST — a
//! crash between steps can leave a stricter-than-necessary state, never
//! a more permissive one. The serving gate independently checks durable
//! quarantine, including when the disposition update has not landed.

use std::collections::{BTreeMap, BTreeSet};

use rabs_protocol::result_identity::TypedDigest;
use rabs_protocol::serving::TrustEvidenceTier;

use crate::metadata_store::{
    QuarantineScope, RabsMetadataStore, SqlValue, StoreError, TrustEvaluationRow, digest_key,
};
use crate::serving_state::{action_quarantine_present, divergence_quarantine_disposition};

/// Domain separator for the canonical evidence-set digest.
pub const EVIDENCE_SET_DOMAIN: &str = "rabs.evidence-set.sha256.v1";
/// Digest domain that MARKS an evidence bundle as a post-publication
/// compromise report. The domain is the class authority (R121); no
/// reason-string parsing decides quarantine.
pub const COMPROMISE_REPORT_DOMAIN: &str = "rabs.compromise-report.sha256.v1";

/// Serving disposition written when the evaluated tier satisfies policy.
pub const DISPOSITION_SERVABLE: &str = "servable";
/// Serving disposition while required evidence is still missing.
pub const DISPOSITION_EVIDENCE_PENDING: &str = "evidence-pending";
/// Serving disposition under adverse evidence or compromise.
pub const DISPOSITION_QUARANTINED: &str = "quarantined";

/// One versioned, revocable trust policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrustPolicy {
    /// Policy version (higher supersedes).
    pub version: u32,
    /// A revoked policy is never evaluated against.
    pub revoked: bool,
    /// Minimum evidence tier required for serving eligibility.
    pub required_tier: TrustEvidenceTier,
}

/// The latest non-revoked policy, if any (the ONLY policy evaluations
/// may use).
#[must_use]
pub fn latest_nonrevoked_policy(policies: &[TrustPolicy]) -> Option<&TrustPolicy> {
    policies
        .iter()
        .filter(|policy| !policy.revoked)
        .max_by_key(|policy| policy.version)
}

/// Typed H033 errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrustEvidenceError {
    /// Underlying store error.
    Store(StoreError),
    /// Every supplied policy is revoked (or none were supplied).
    /// Ordinary reevaluation leaves state untouched; a compromise
    /// report remains durably quarantined even when evaluation fails.
    NoActivePolicy,
    /// The append-only ledger cannot advance without overflowing.
    LedgerVersionExhausted,
    /// The action has no committed publication to evaluate.
    NotPublished,
    /// A compromise report must carry [`COMPROMISE_REPORT_DOMAIN`]; any
    /// other domain is refused, never silently reclassified.
    NotACompromiseReport {
        /// The domain that was presented.
        presented: String,
    },
}

impl From<StoreError> for TrustEvidenceError {
    fn from(error: StoreError) -> Self {
        Self::Store(error)
    }
}

/// Reject an already-stale caller before the non-authority-gated
/// evidence/quarantine writes. The ledger write still performs its own
/// transactional authority check; this is not a replacement for it.
pub(crate) fn require_active_authority(
    store: &mut dyn RabsMetadataStore,
    authority: &TypedDigest,
) -> Result<(), StoreError> {
    match store.active_authority()? {
        Some(current) if &current.digest == authority => Ok(()),
        _ => Err(StoreError::NotActiveAuthority),
    }
}

use crate::publication::{DISPOSITION_PRESENTATION_QUARANTINED, Framing};

/// Canonical digest over an evidence-ID set: IDs are sorted and
/// deduplicated before framing, so append-only growth changes the digest
/// deterministically and insertion order can never produce two names for
/// one set.
#[must_use]
pub fn evidence_set_digest(keys: &[String]) -> TypedDigest {
    let mut canonical: Vec<&str> = keys.iter().map(String::as_str).collect();
    canonical.sort_unstable();
    canonical.dedup();
    let mut framing = Framing::new(EVIDENCE_SET_DOMAIN);
    framing.u64(canonical.len() as u64);
    for key in canonical {
        framing.field(key.as_bytes());
    }
    framing.finish(EVIDENCE_SET_DOMAIN)
}

const fn tier_tag(tier: TrustEvidenceTier) -> &'static str {
    match tier {
        TrustEvidenceTier::UnverifiedCandidate => "unverified-candidate",
        TrustEvidenceTier::ShadowMatched => "shadow-matched",
        TrustEvidenceTier::ReproducibleSameWorker => "reproducible-same-worker",
        TrustEvidenceTier::ReproducibleCrossWorker => "reproducible-cross-worker",
        TrustEvidenceTier::CiPolicyApproved => "ci-policy-approved",
        TrustEvidenceTier::ProjectReleaseEligible => "project-release-eligible",
    }
}

/// One completed re-evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrustReevaluation {
    /// The policy version evaluated against.
    pub policy_version: u32,
    /// Tier derived from the current verification evidence.
    pub observed_tier: TrustEvidenceTier,
    /// Whether a compromise report is present in the evidence set.
    pub compromised: bool,
    /// Number of failed verification samples (adverse evidence).
    pub adverse_samples: u64,
    /// Canonical digest of the evidence-ID set at evaluation time.
    pub evidence_set: TypedDigest,
    /// The serving disposition written.
    pub disposition: &'static str,
    /// The ledger version appended by this evaluation.
    pub ledger_version: u32,
}

/// Evidence counts shared by tier evaluation and sampled-serving policy.
/// Each known same-action attempt counts once; a failed observation
/// dominates any passed observations of that SAME attempt.
pub(crate) struct VerificationEvidence {
    /// Distinct, attributable attempts with at least one observation.
    pub(crate) attempts: u64,
    /// Attributable attempts with no failed observation.
    pub(crate) passed_attempts: u64,
    /// Distinct worker identities among passing attempts.
    pub(crate) passed_workers: usize,
    /// All failed samples, including unattributed ones, remain adverse.
    pub(crate) adverse_samples: u64,
}

/// Aggregate verification evidence without inventing executions or
/// worker identities. Unknown and foreign-action attempts never count
/// as positive evidence; their negative observations are still retained.
pub(crate) fn verification_evidence(
    store: &mut dyn RabsMetadataStore,
    action: &TypedDigest,
) -> Result<VerificationEvidence, StoreError> {
    let samples = store.list_verification_samples(action)?;
    let adverse_samples = samples.iter().filter(|sample| !sample.passed).count() as u64;
    let rows = store.query(
        "SELECT DISTINCT a.id_hex, a.worker FROM verification_samples s \
         JOIN action_attempts a ON a.id_hex = s.attempt_hex \
         JOIN action_generations g ON g.id_hex = a.generation_hex \
         WHERE s.action_key = ?1 AND g.action_key = ?1 \
         ORDER BY a.id_hex",
        &[SqlValue::Text(digest_key(action))],
    )?;
    let mut attempts = BTreeMap::new();
    for row in rows {
        match row.as_slice() {
            [SqlValue::Text(attempt), SqlValue::Text(worker)] => {
                if !worker.is_empty() {
                    attempts.insert(attempt.clone(), (worker.clone(), true));
                }
            }
            _ => {
                return Err(StoreError::Backend(
                    "invalid verification attempt attribution row".to_owned(),
                ));
            }
        }
    }
    for sample in &samples {
        if let Some((_, passed)) = attempts.get_mut(&sample.attempt_hex) {
            *passed &= sample.passed;
        }
    }
    let mut passed_workers = BTreeSet::new();
    let mut passed_attempts = 0_u64;
    for (worker, passed) in attempts.values() {
        if *passed {
            passed_attempts += 1;
            passed_workers.insert(worker.as_str());
        }
    }
    Ok(VerificationEvidence {
        attempts: attempts.len() as u64,
        passed_attempts,
        passed_workers: passed_workers.len(),
        adverse_samples,
    })
}

/// Derive an observed evidence tier, never a semantic-correctness claim
/// (plan §113), from independent attributable verification attempts.
fn observed_tier(
    store: &mut dyn RabsMetadataStore,
    action: &TypedDigest,
) -> Result<(TrustEvidenceTier, u64), StoreError> {
    let evidence = verification_evidence(store, action)?;
    let tier = match (evidence.passed_attempts, evidence.passed_workers) {
        (0, _) => TrustEvidenceTier::UnverifiedCandidate,
        (1, _) => TrustEvidenceTier::ShadowMatched,
        (_, 0 | 1) => TrustEvidenceTier::ReproducibleSameWorker,
        (_, _) => TrustEvidenceTier::ReproducibleCrossWorker,
    };
    Ok((tier, evidence.adverse_samples))
}

/// Re-evaluate one action's serving from its CURRENT evidence under the
/// latest non-revoked policy. Appends a ledger row and rewrites the
/// serving disposition; the publication row is never touched (I42 — the
/// tests pin this byte-for-byte). Existing quarantine and named blocking
/// references remain authoritative, even when all new evidence passes.
pub fn reevaluate_action(
    store: &mut dyn RabsMetadataStore,
    authority: &TypedDigest,
    action: &TypedDigest,
    policies: &[TrustPolicy],
    seq: u64,
) -> Result<TrustReevaluation, TrustEvidenceError> {
    if !store.has_publication(action)? {
        return Err(TrustEvidenceError::NotPublished);
    }
    let policy = latest_nonrevoked_policy(policies).ok_or(TrustEvidenceError::NoActivePolicy)?;
    require_active_authority(store, authority)?;
    let action_key = digest_key(action);
    let action_quarantined = action_quarantine_present(store, &action_key)?;
    let incident_disposition = divergence_quarantine_disposition(store, &action_key)?;
    let serving = store.serving_record(&action_key)?;
    let serving_blocked = incident_disposition == Some(DISPOSITION_QUARANTINED)
        || serving.as_ref().is_some_and(|record| {
            record.disposition == DISPOSITION_QUARANTINED || !record.blocking.is_empty()
        });
    // H026 observable-only divergence is narrower than action quarantine,
    // but still forbids replay. Verification and policy changes are not a
    // repair, including when the new policy would only leave evidence pending.
    let presentation_quarantined = incident_disposition
        == Some(DISPOSITION_PRESENTATION_QUARANTINED)
        || serving
            .as_ref()
            .is_some_and(|record| record.disposition == DISPOSITION_PRESENTATION_QUARANTINED);
    let keys = store.list_evidence_keys(action)?;
    let compromised = keys
        .iter()
        .any(|key| key.starts_with(&format!("{COMPROMISE_REPORT_DOMAIN}:")));
    let evidence_set = evidence_set_digest(&keys);
    let (tier, adverse_samples) = observed_tier(store, action)?;

    let (disposition, state_tag) = if compromised {
        (DISPOSITION_QUARANTINED, "compromised")
    } else if adverse_samples > 0 {
        (DISPOSITION_QUARANTINED, "adverse-evidence")
    } else if action_quarantined || serving_blocked {
        (DISPOSITION_QUARANTINED, "unresolved-quarantine")
    } else if presentation_quarantined {
        (
            DISPOSITION_PRESENTATION_QUARANTINED,
            "unresolved-presentation-quarantine",
        )
    } else if tier >= policy.required_tier {
        (DISPOSITION_SERVABLE, tier_tag(tier))
    } else {
        (DISPOSITION_EVIDENCE_PENDING, tier_tag(tier))
    };

    // Quarantine FIRST, but do not overwrite an unresolved incident's
    // original reason. Named object/location blockers remain in the
    // serving record; reevaluation neither drops nor repairs them.
    if !action_quarantined && (compromised || adverse_samples > 0) {
        store.add_quarantine(
            QuarantineScope::ActionEntry,
            &action_key,
            if compromised {
                "post-publication compromise report in evidence set"
            } else {
                "failed verification sample"
            },
        )?;
    }
    let ledger_version = store
        .latest_trust_evaluation(action)?
        .map_or(Some(1), |latest| latest.version.checked_add(1))
        .ok_or(TrustEvidenceError::LedgerVersionExhausted)?;
    store.append_trust_evaluation(
        authority,
        action,
        &TrustEvaluationRow {
            version: ledger_version,
            state: state_tag.to_owned(),
            reason: format!(
                "policy v{}; evidence-set {}; adverse {}; compromised {}; prior-blocker {}",
                policy.version,
                digest_key(&evidence_set),
                adverse_samples,
                compromised,
                action_quarantined || serving_blocked || presentation_quarantined
            ),
            evaluated_seq: seq,
        },
    )?;
    store.set_serving_disposition_key(&action_key, disposition)?;
    Ok(TrustReevaluation {
        policy_version: policy.version,
        observed_tier: tier,
        compromised,
        adverse_samples,
        evidence_set,
        disposition,
        ledger_version,
    })
}

/// Attach a post-publication compromise report to an action's evidence
/// set (append-only) and immediately re-evaluate. The report digest MUST
/// carry [`COMPROMISE_REPORT_DOMAIN`]; wrong domains, unpublished actions,
/// and already-stale authorities are refused before any store write.
///
/// Once admitted, quarantine lands FIRST. A later error, including
/// [`TrustEvidenceError::NoActivePolicy`], does not undo that protection.
/// Recovery must use the explicit repair flow rather than retrying with
/// a more permissive policy.
#[allow(clippy::too_many_arguments)]
pub fn report_compromise(
    store: &mut dyn RabsMetadataStore,
    authority: &TypedDigest,
    action: &TypedDigest,
    report: &TypedDigest,
    generation: u128,
    attempt: u128,
    policies: &[TrustPolicy],
    seq: u64,
) -> Result<TrustReevaluation, TrustEvidenceError> {
    if report.domain != COMPROMISE_REPORT_DOMAIN {
        return Err(TrustEvidenceError::NotACompromiseReport {
            presented: report.domain.to_owned(),
        });
    }
    // The report is evidence about the COMMITTED canonical result, so it
    // binds to the published manifest key (H029; I37).
    let manifest_key = store
        .published_manifest_key(action)?
        .ok_or(TrustEvidenceError::NotPublished)?;
    require_active_authority(store, authority)?;
    let action_key = digest_key(action);
    if !action_quarantine_present(store, &action_key)? {
        store.add_quarantine(
            QuarantineScope::ActionEntry,
            &action_key,
            "post-publication compromise report admitted",
        )?;
    }
    store.append_evidence(action, &manifest_key, report, generation, attempt)?;
    reevaluate_action(store, authority, action, policies, seq)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata_store::{
        ActionEntryRow, AuthorityRow, CommitOutcome, FsqliteEngine, PublicationRow, ResultKindTag,
        RusqliteEngine, SqlMetadataStore,
    };
    use crate::serving_state::{ServeDecision, serving_gate};
    use rabs_protocol::result_identity::DigestAlgorithm;
    use rabs_protocol::serving::ServingValidity;
    use std::sync::atomic::{AtomicU64, Ordering};

    static DB_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn fresh_path(tag: &str) -> std::path::PathBuf {
        let n = DB_COUNTER.fetch_add(1, Ordering::SeqCst);
        std::env::temp_dir().join(format!("rabs-h033-{}-{}-{}.db", std::process::id(), tag, n))
    }

    fn digest(domain: &'static str, tag: u8) -> TypedDigest {
        TypedDigest {
            algorithm: DigestAlgorithm::Sha256V1,
            domain,
            bytes: [tag; 32],
        }
    }

    fn authority_row(tag: u8) -> AuthorityRow {
        AuthorityRow {
            digest: digest("rabs.authority.sha256.v1", tag),
            cluster_id: "cluster-a".to_owned(),
            incarnation: u128::from(tag),
            term: u64::from(tag),
            acquired_seq: 1,
        }
    }

    fn policy(version: u32, revoked: bool, required: TrustEvidenceTier) -> TrustPolicy {
        TrustPolicy {
            version,
            revoked,
            required_tier: required,
        }
    }

    /// Publish action 7 with generation 10 and attempts 20 (worker-a) +
    /// 21 (worker-b); returns (active authority, action key).
    fn published_fixture(store: &mut dyn RabsMetadataStore) -> (TypedDigest, TypedDigest) {
        store.acquire_authority(&authority_row(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        let action = ActionEntryRow {
            action_key: digest("rabs.action-key.sha256.v1", 7),
            key_epoch: 0,
            projection_epoch: 0,
        };
        store.upsert_action_entry(&action).unwrap();
        store
            .create_generation(&active, 10, &action.action_key)
            .unwrap();
        store.record_attempt(20, 10, "worker-a", 5).unwrap();
        store.record_attempt(21, 10, "worker-b", 6).unwrap();
        let row = PublicationRow {
            action_key: action.action_key.clone(),
            descriptor_digest: digest("rabs.descriptor.sha256.v1", 1),
            manifest_digest: digest("rabs.result-manifest.sha256.v1", 1),
            evidence_digest: digest("rabs.evidence-bundle.sha256.v1", 1),
            winner_generation: 10,
            winner_attempt: 20,
            result_kind: ResultKindTag::Success,
            pin_id: 40,
            pin_owner: "coordinator".to_owned(),
            provisional_ancestors: Vec::new(),
        };
        assert_eq!(
            store.commit_publication(&active, None, &row).unwrap(),
            CommitOutcome::Committed
        );
        (active, action.action_key)
    }

    /// The publication's dump lines — the canonical bytes that H033 must
    /// NEVER rewrite.
    fn publication_lines(store: &mut dyn RabsMetadataStore) -> Vec<String> {
        store
            .differential_snapshot()
            .unwrap()
            .into_iter()
            .filter(|line| line.starts_with("action_publications|"))
            .collect()
    }

    /// T032: evidence promotion and demotion move the ledger + serving,
    /// never the publication.
    fn t032_promotion_demotion(store: &mut dyn RabsMetadataStore) -> Vec<String> {
        let (active, action) = published_fixture(store);
        let frozen = publication_lines(store);
        let policies = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];

        // No verification evidence yet: pending, ledger v1.
        let eval = reevaluate_action(store, &active, &action, &policies, 100).unwrap();
        assert_eq!(eval.observed_tier, TrustEvidenceTier::UnverifiedCandidate);
        assert_eq!(eval.disposition, DISPOSITION_EVIDENCE_PENDING);
        assert_eq!(eval.ledger_version, 1);

        // One passed verification: PROMOTION to servable.
        store
            .record_verification_sample(&action, 20, true, 101)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 102).unwrap();
        assert_eq!(eval.observed_tier, TrustEvidenceTier::ShadowMatched);
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);
        assert_eq!(eval.ledger_version, 2);
        assert_eq!(
            store.serving_disposition_key(&digest_key(&action)).unwrap(),
            Some(DISPOSITION_SERVABLE.to_owned())
        );

        // A second passed verification from a DIFFERENT worker.
        store
            .record_verification_sample(&action, 21, true, 103)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 104).unwrap();
        assert_eq!(
            eval.observed_tier,
            TrustEvidenceTier::ReproducibleCrossWorker
        );
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);

        // A failed verification is adverse evidence: DEMOTION to
        // quarantined, and the quarantine row exists.
        store
            .record_verification_sample(&action, 21, false, 105)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 106).unwrap();
        assert_eq!(eval.adverse_samples, 1);
        assert_eq!(eval.disposition, DISPOSITION_QUARANTINED);
        assert_eq!(eval.ledger_version, 4);
        assert_eq!(
            store.serving_disposition_key(&digest_key(&action)).unwrap(),
            Some(DISPOSITION_QUARANTINED.to_owned())
        );

        // I42: the publication rows are byte-identical through all of it.
        assert_eq!(publication_lines(store), frozen);
        store.differential_snapshot().unwrap()
    }

    #[test]
    fn t032_promotion_demotion_reference() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        t032_promotion_demotion(&mut store);
    }

    #[test]
    fn t032_promotion_demotion_differential_reference_vs_frankensqlite() {
        let reference_engine = RusqliteEngine::open(&fresh_path("ref")).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let candidate_engine = FsqliteEngine::open(&fresh_path("fsq")).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        assert_eq!(
            t032_promotion_demotion(&mut reference),
            t032_promotion_demotion(&mut candidate)
        );
    }

    #[test]
    fn t032_policy_change_reevaluates_serving() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        let (active, action) = published_fixture(&mut store);
        store
            .record_verification_sample(&action, 20, true, 100)
            .unwrap();

        // Policy v1 accepts a shadow match: servable.
        let v1 = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];
        let eval = reevaluate_action(&mut store, &active, &action, &v1, 101).unwrap();
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);

        // Policy v2 (stricter) supersedes: the SAME evidence no longer
        // suffices — serving demotes without any new evidence.
        let v2 = vec![
            policy(1, false, TrustEvidenceTier::ShadowMatched),
            policy(2, false, TrustEvidenceTier::ReproducibleCrossWorker),
        ];
        let eval = reevaluate_action(&mut store, &active, &action, &v2, 102).unwrap();
        assert_eq!(eval.policy_version, 2);
        assert_eq!(eval.disposition, DISPOSITION_EVIDENCE_PENDING);

        // v2 revoked: evaluation falls back to the latest NON-revoked
        // policy (v1) and serving returns.
        let v2_revoked = vec![
            policy(1, false, TrustEvidenceTier::ShadowMatched),
            policy(2, true, TrustEvidenceTier::ReproducibleCrossWorker),
        ];
        let eval = reevaluate_action(&mut store, &active, &action, &v2_revoked, 103).unwrap();
        assert_eq!(eval.policy_version, 1);
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);

        // Every policy revoked: typed refusal, serving state untouched.
        let all_revoked = vec![policy(1, true, TrustEvidenceTier::ShadowMatched)];
        assert_eq!(
            reevaluate_action(&mut store, &active, &action, &all_revoked, 104),
            Err(TrustEvidenceError::NoActivePolicy)
        );
        assert_eq!(
            store.serving_disposition_key(&digest_key(&action)).unwrap(),
            Some(DISPOSITION_SERVABLE.to_owned()),
            "refused evaluation must not move serving state"
        );
    }

    #[test]
    fn t032_post_publication_compromise() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        let (active, action) = published_fixture(&mut store);
        store
            .record_verification_sample(&action, 20, true, 100)
            .unwrap();
        let policies = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];
        let eval = reevaluate_action(&mut store, &active, &action, &policies, 101).unwrap();
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);
        let frozen = publication_lines(&mut store);

        // A report under the WRONG domain is refused before any write.
        let ledger_before = store.latest_trust_evaluation(&action).unwrap();
        let bogus = digest("rabs.evidence-bundle.sha256.v1", 66);
        assert_eq!(
            report_compromise(&mut store, &active, &action, &bogus, 10, 20, &policies, 102),
            Err(TrustEvidenceError::NotACompromiseReport {
                presented: "rabs.evidence-bundle.sha256.v1".to_owned()
            })
        );
        assert_eq!(
            store.latest_trust_evaluation(&action).unwrap(),
            ledger_before,
            "refused report must append nothing"
        );

        // The real compromise report: appended to the index, quarantined,
        // ledger demoted — the publication untouched.
        let report = digest(COMPROMISE_REPORT_DOMAIN, 66);
        let eval = report_compromise(
            &mut store, &active, &action, &report, 10, 20, &policies, 103,
        )
        .unwrap();
        assert!(eval.compromised);
        assert_eq!(eval.disposition, DISPOSITION_QUARANTINED);
        assert!(
            store
                .list_evidence_keys(&action)
                .unwrap()
                .iter()
                .any(|key| key.starts_with(&format!("{COMPROMISE_REPORT_DOMAIN}:"))),
            "compromise report must live in the append-only index"
        );
        assert_eq!(
            store
                .latest_trust_evaluation(&action)
                .unwrap()
                .unwrap()
                .state,
            "compromised"
        );

        // Re-evaluating WITHOUT new evidence stays quarantined: the
        // append-only index cannot forget the report.
        let eval = reevaluate_action(&mut store, &active, &action, &policies, 104).unwrap();
        assert!(eval.compromised);
        assert_eq!(eval.disposition, DISPOSITION_QUARANTINED);

        assert_eq!(publication_lines(&mut store), frozen);
    }

    #[test]
    fn evidence_set_digest_is_order_insensitive_and_deduplicated() {
        let a = evidence_set_digest(&["d:aa".to_owned(), "d:bb".to_owned(), "d:cc".to_owned()]);
        let b = evidence_set_digest(&[
            "d:cc".to_owned(),
            "d:aa".to_owned(),
            "d:bb".to_owned(),
            "d:aa".to_owned(),
        ]);
        assert_eq!(a, b, "insertion order and duplicates never rename a set");
        let grown = evidence_set_digest(&[
            "d:aa".to_owned(),
            "d:bb".to_owned(),
            "d:cc".to_owned(),
            "d:dd".to_owned(),
        ]);
        assert_ne!(a, grown, "growth must rename the set");
        // Length-delimited framing: a boundary shift is a different set.
        let shifted = evidence_set_digest(&["d:aab".to_owned(), "d:b".to_owned()]);
        let plain = evidence_set_digest(&["d:aa".to_owned(), "d:bb".to_owned()]);
        assert_ne!(shifted, plain);
    }

    #[test]
    fn duplicate_evidence_appends_do_not_rename_the_set() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        let (_, action) = published_fixture(&mut store);
        let before = store.list_evidence_keys(&action).unwrap();
        let manifest_key = store.published_manifest_key(&action).unwrap().unwrap();
        // Re-append the winner's evidence digest (idempotent per H011).
        store
            .append_evidence(
                &action,
                &manifest_key,
                &digest("rabs.evidence-bundle.sha256.v1", 1),
                10,
                20,
            )
            .unwrap();
        let after = store.list_evidence_keys(&action).unwrap();
        assert_eq!(before, after);
        assert_eq!(evidence_set_digest(&before), evidence_set_digest(&after));
    }

    #[test]
    fn unpublished_actions_are_refused() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        store.acquire_authority(&authority_row(1)).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        let unpublished = digest("rabs.action-key.sha256.v1", 99);
        let policies = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];
        assert_eq!(
            reevaluate_action(&mut store, &active, &unpublished, &policies, 100),
            Err(TrustEvidenceError::NotPublished)
        );
    }

    /// Unattributed, foreign-action and repeated samples never invent
    /// independent executions. Real independent attempts still promote.
    /// Once quarantined, even a weaker policy cannot restore serving.
    fn independent_evidence_and_sticky_quarantine(
        store: &mut dyn RabsMetadataStore,
    ) -> Vec<String> {
        let (active, action) = published_fixture(store);
        let action_key = digest_key(&action);
        let frozen = publication_lines(store);
        let policies = vec![policy(1, false, TrustEvidenceTier::ReproducibleCrossWorker)];

        // Unknown attempts used to fabricate distinct worker identities.
        for (attempt, seq) in [(90_u128, 90_u64), (91, 91)] {
            store
                .record_verification_sample(&action, attempt, true, seq)
                .unwrap();
        }
        // A real worker on another action is not evidence for this one.
        let foreign = digest("rabs.action-key.sha256.v1", 8);
        store
            .upsert_action_entry(&ActionEntryRow {
                action_key: foreign.clone(),
                key_epoch: 0,
                projection_epoch: 0,
            })
            .unwrap();
        store.create_generation(&active, 11, &foreign).unwrap();
        store.record_attempt(30, 11, "worker-c", 92).unwrap();
        store
            .record_verification_sample(&action, 30, true, 93)
            .unwrap();
        // Empty attribution is not a worker identity either.
        store.record_attempt(31, 10, "", 94).unwrap();
        store
            .record_verification_sample(&action, 31, true, 95)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 100).unwrap();
        assert_eq!(eval.observed_tier, TrustEvidenceTier::UnverifiedCandidate);
        assert_eq!(eval.disposition, DISPOSITION_EVIDENCE_PENDING);

        for seq in [101, 102, 103] {
            store
                .record_verification_sample(&action, 20, true, seq)
                .unwrap();
        }
        let eval = reevaluate_action(store, &active, &action, &policies, 104).unwrap();
        assert_eq!(eval.observed_tier, TrustEvidenceTier::ShadowMatched);
        assert_eq!(eval.disposition, DISPOSITION_EVIDENCE_PENDING);

        store.record_attempt(22, 10, "worker-a", 105).unwrap();
        store
            .record_verification_sample(&action, 22, true, 106)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 107).unwrap();
        assert_eq!(
            eval.observed_tier,
            TrustEvidenceTier::ReproducibleSameWorker
        );
        assert_eq!(eval.disposition, DISPOSITION_EVIDENCE_PENDING);
        store
            .record_verification_sample(&action, 21, true, 108)
            .unwrap();
        let eval = reevaluate_action(store, &active, &action, &policies, 109).unwrap();
        assert_eq!(
            eval.observed_tier,
            TrustEvidenceTier::ReproducibleCrossWorker
        );
        assert_eq!(eval.disposition, DISPOSITION_SERVABLE);

        store
            .add_quarantine(
                QuarantineScope::ActionEntry,
                &action_key,
                "closure corruption",
            )
            .unwrap();
        let record = store.serving_record(&action_key).unwrap().unwrap();
        assert_eq!(record.disposition, DISPOSITION_SERVABLE);
        assert!(record.blocking.is_empty());
        let weaker = vec![policy(2, false, TrustEvidenceTier::UnverifiedCandidate)];
        let eval = reevaluate_action(store, &active, &action, &weaker, 110).unwrap();
        assert_eq!(eval.disposition, DISPOSITION_QUARANTINED);
        assert_eq!(
            store
                .latest_trust_evaluation(&action)
                .unwrap()
                .unwrap()
                .state,
            "unresolved-quarantine"
        );
        assert_eq!(
            store
                .query(
                    "SELECT reason FROM quarantines WHERE scope = 'action-entry' AND subject = ?1",
                    &[SqlValue::Text(action_key.clone())],
                )
                .unwrap(),
            vec![vec![SqlValue::Text("closure corruption".to_owned())]]
        );
        assert!(matches!(
            serving_gate(store, &action_key, 200, 0).unwrap(),
            ServeDecision::NotServable { .. }
        ));

        // A later passing observation cannot erase an attempt's failed
        // observation or count it as an additional successful execution.
        store
            .record_verification_sample(&action, 20, false, 111)
            .unwrap();
        store
            .record_verification_sample(&action, 20, true, 112)
            .unwrap();
        let evidence = verification_evidence(store, &action).unwrap();
        assert_eq!(evidence.attempts, 3);
        assert_eq!(evidence.passed_attempts, 2);
        assert_eq!(evidence.adverse_samples, 1);
        assert_eq!(publication_lines(store), frozen);
        store.differential_snapshot().unwrap()
    }

    #[test]
    fn independent_evidence_and_quarantine_reference() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        independent_evidence_and_sticky_quarantine(&mut store);
    }

    #[test]
    fn independent_evidence_and_quarantine_differential() {
        let reference_engine = RusqliteEngine::open(&fresh_path("evidence-ref")).unwrap();
        let candidate_engine = FsqliteEngine::open(&fresh_path("evidence-fsq")).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        assert_eq!(
            independent_evidence_and_sticky_quarantine(&mut reference),
            independent_evidence_and_sticky_quarantine(&mut candidate)
        );
    }

    #[test]
    fn positive_evidence_preserves_named_blockers_and_quarantined_disposition() {
        for named_blocker in [false, true] {
            let engine = RusqliteEngine::open_in_memory().unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            let (active, action) = published_fixture(&mut store);
            let action_key = digest_key(&action);
            let policies = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];
            store
                .record_verification_sample(&action, 20, true, 100)
                .unwrap();
            let blocking = if named_blocker {
                store
                    .add_quarantine(
                        QuarantineScope::LogicalObject,
                        "object:damaged",
                        "bad bytes",
                    )
                    .unwrap();
                vec![(QuarantineScope::LogicalObject, "object:damaged".to_owned())]
            } else {
                Vec::new()
            };
            store
                .put_serving_record(
                    &active,
                    &action_key,
                    if named_blocker {
                        DISPOSITION_SERVABLE
                    } else {
                        DISPOSITION_QUARANTINED
                    },
                    1,
                    &ServingValidity {
                        evaluated_at_unix_micros: 0,
                        maximum_age_micros: None,
                        clock_uncertainty_micros: 0,
                        coordinator_clock_epoch: 0,
                    },
                    &blocking,
                )
                .unwrap();
            let before = store.serving_record(&action_key).unwrap().unwrap();
            let eval = reevaluate_action(&mut store, &active, &action, &policies, 101).unwrap();
            assert_eq!(eval.disposition, DISPOSITION_QUARANTINED);
            let after = store.serving_record(&action_key).unwrap().unwrap();
            assert_eq!(after.blocking, before.blocking);
            assert_eq!(
                after.state_revision,
                before.state_revision + u64::from(named_blocker)
            );
            assert!(matches!(
                serving_gate(&mut store, &action_key, 200, 0).unwrap(),
                ServeDecision::NotServable { .. }
            ));
        }
    }

    fn compromise_without_policy_is_still_blocked(
        store: &mut dyn RabsMetadataStore,
    ) -> Vec<String> {
        let (active, action) = published_fixture(store);
        let action_key = digest_key(&action);
        let frozen = publication_lines(store);
        let report = digest(COMPROMISE_REPORT_DOMAIN, 66);
        let policies = vec![policy(1, false, TrustEvidenceTier::ShadowMatched)];
        let wrong = digest("rabs.authority.sha256.v1", 2);
        let before = store.differential_snapshot().unwrap();
        assert_eq!(
            report_compromise(store, &wrong, &action, &report, 10, 20, &policies, 100),
            Err(TrustEvidenceError::Store(StoreError::NotActiveAuthority))
        );
        assert_eq!(
            reevaluate_action(store, &wrong, &action, &policies, 100),
            Err(TrustEvidenceError::Store(StoreError::NotActiveAuthority))
        );
        assert_eq!(store.differential_snapshot().unwrap(), before);
        assert_eq!(
            serving_gate(store, &action_key, 200, 0).unwrap(),
            ServeDecision::Servable
        );

        assert_eq!(
            report_compromise(store, &active, &action, &report, 10, 20, &[], 101),
            Err(TrustEvidenceError::NoActivePolicy)
        );
        assert!(
            store
                .list_evidence_keys(&action)
                .unwrap()
                .contains(&digest_key(&report))
        );
        assert_eq!(
            serving_gate(store, &action_key, 200, 0).unwrap(),
            ServeDecision::Blocked {
                references: vec![("action-entry".to_owned(), action_key.clone())],
            }
        );
        let revoked = vec![policy(1, true, TrustEvidenceTier::ShadowMatched)];
        assert_eq!(
            report_compromise(store, &active, &action, &report, 10, 20, &revoked, 102),
            Err(TrustEvidenceError::NoActivePolicy)
        );
        assert!(matches!(
            serving_gate(store, &action_key, 200, 0).unwrap(),
            ServeDecision::Blocked { .. }
        ));
        assert_eq!(publication_lines(store), frozen);
        store.differential_snapshot().unwrap()
    }

    #[test]
    fn compromise_without_policy_reference() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        compromise_without_policy_is_still_blocked(&mut store);
    }

    #[test]
    fn compromise_without_policy_differential() {
        let reference_engine = RusqliteEngine::open(&fresh_path("compromise-ref")).unwrap();
        let candidate_engine = FsqliteEngine::open(&fresh_path("compromise-fsq")).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        assert_eq!(
            compromise_without_policy_is_still_blocked(&mut reference),
            compromise_without_policy_is_still_blocked(&mut candidate)
        );
    }

    /// bd-rhdef / I34: evidence adequacy and incident repair are independent.
    /// The narrow disposition must survive BOTH promotion and pending evidence.
    fn presentation_quarantine_policy_matrix(store: &mut dyn RabsMetadataStore) -> Vec<String> {
        let (active, action) = published_fixture(store);
        let action_key = digest_key(&action);
        let frozen = publication_lines(store);
        store
            .record_verification_sample(&action, 20, true, 100)
            .unwrap();
        store
            .set_serving_disposition_key(&action_key, DISPOSITION_PRESENTATION_QUARANTINED)
            .unwrap();
        let before = store.serving_record(&action_key).unwrap().unwrap();
        let policies = [
            vec![policy(1, false, TrustEvidenceTier::ShadowMatched)],
            vec![policy(2, false, TrustEvidenceTier::ReproducibleCrossWorker)],
            vec![policy(3, false, TrustEvidenceTier::UnverifiedCandidate)],
            vec![
                policy(3, false, TrustEvidenceTier::UnverifiedCandidate),
                policy(4, true, TrustEvidenceTier::ProjectReleaseEligible),
            ],
        ];
        for (index, policies) in policies.iter().enumerate() {
            let evaluation =
                reevaluate_action(store, &active, &action, policies, 101 + index as u64).unwrap();
            assert_eq!(evaluation.observed_tier, TrustEvidenceTier::ShadowMatched);
            assert_eq!(evaluation.disposition, DISPOSITION_PRESENTATION_QUARANTINED);
            let ledger = store.latest_trust_evaluation(&action).unwrap().unwrap();
            assert_eq!(ledger.state, "unresolved-presentation-quarantine");
            assert!(ledger.reason.contains("prior-blocker true"));
            let after = store.serving_record(&action_key).unwrap().unwrap();
            assert_eq!(after.state_revision, before.state_revision);
            assert_eq!(after.validity, before.validity);
            assert_eq!(after.blocking, before.blocking);
            assert!(!action_quarantine_present(store, &action_key).unwrap());
            assert_eq!(
                serving_gate(store, &action_key, 200, 0).unwrap(),
                ServeDecision::NotServable {
                    disposition: DISPOSITION_PRESENTATION_QUARANTINED.to_owned(),
                }
            );
            assert_eq!(publication_lines(store), frozen);
        }
        let snapshot = store.differential_snapshot().unwrap();
        assert_eq!(
            reevaluate_action(store, &active, &action, &[], 110),
            Err(TrustEvidenceError::NoActivePolicy)
        );
        let stale = digest("rabs.authority.sha256.v1", 2);
        assert_eq!(
            reevaluate_action(store, &stale, &action, &policies[0], 111),
            Err(TrustEvidenceError::Store(StoreError::NotActiveAuthority))
        );
        assert_eq!(store.differential_snapshot().unwrap(), snapshot);
        snapshot
    }

    #[test]
    fn presentation_quarantine_survives_policy_changes_reference() {
        let engine = RusqliteEngine::open_in_memory().unwrap();
        let mut store = SqlMetadataStore::open(engine).unwrap();
        presentation_quarantine_policy_matrix(&mut store);
    }

    #[test]
    fn presentation_quarantine_survives_policy_changes_differential() {
        let reference_engine = RusqliteEngine::open(&fresh_path("presentation-ref")).unwrap();
        let candidate_engine = FsqliteEngine::open(&fresh_path("presentation-fsq")).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        assert_eq!(
            presentation_quarantine_policy_matrix(&mut reference),
            presentation_quarantine_policy_matrix(&mut candidate)
        );
    }

    #[test]
    fn presentation_quarantine_never_masks_stronger_blockers() {
        for cause in ["action", "named", "adverse", "compromise"] {
            let engine = RusqliteEngine::open_in_memory().unwrap();
            let mut store = SqlMetadataStore::open(engine).unwrap();
            let (active, action) = published_fixture(&mut store);
            let action_key = digest_key(&action);
            let frozen = publication_lines(&mut store);
            let policies = [policy(1, false, TrustEvidenceTier::UnverifiedCandidate)];
            store
                .set_serving_disposition_key(&action_key, DISPOSITION_PRESENTATION_QUARANTINED)
                .unwrap();
            let expected_state = match cause {
                "action" => {
                    store
                        .add_quarantine(
                            QuarantineScope::ActionEntry,
                            &action_key,
                            "semantic divergence",
                        )
                        .unwrap();
                    "unresolved-quarantine"
                }
                "named" => {
                    store
                        .add_quarantine(
                            QuarantineScope::LogicalObject,
                            "object:damaged",
                            "bad bytes",
                        )
                        .unwrap();
                    let record = store.serving_record(&action_key).unwrap().unwrap();
                    store
                        .put_serving_record(
                            &active,
                            &action_key,
                            DISPOSITION_PRESENTATION_QUARANTINED,
                            record.state_revision + 1,
                            &record.validity,
                            &[(QuarantineScope::LogicalObject, "object:damaged".to_owned())],
                        )
                        .unwrap();
                    "unresolved-quarantine"
                }
                "adverse" => {
                    store
                        .record_verification_sample(&action, 20, false, 100)
                        .unwrap();
                    "adverse-evidence"
                }
                _ => {
                    let report = digest(COMPROMISE_REPORT_DOMAIN, 66);
                    report_compromise(
                        &mut store, &active, &action, &report, 10, 20, &policies, 100,
                    )
                    .unwrap();
                    "compromised"
                }
            };
            let evaluation =
                reevaluate_action(&mut store, &active, &action, &policies, 101).unwrap();
            assert_eq!(evaluation.disposition, DISPOSITION_QUARANTINED, "{cause}");
            assert_eq!(
                store
                    .latest_trust_evaluation(&action)
                    .unwrap()
                    .unwrap()
                    .state,
                expected_state,
                "{cause}"
            );
            if cause == "named" {
                assert_eq!(
                    store.serving_record(&action_key).unwrap().unwrap().blocking,
                    vec![("logical-object".to_owned(), "object:damaged".to_owned())]
                );
            } else {
                assert!(action_quarantine_present(&mut store, &action_key).unwrap());
            }
            assert_eq!(publication_lines(&mut store), frozen);
        }
    }

    #[test]
    fn presentation_quarantine_survives_metadata_reopen_differential() {
        let reference_path = fresh_path("presentation-reopen-ref");
        let candidate_path = fresh_path("presentation-reopen-fsq");
        let snapshot = {
            let reference_engine = RusqliteEngine::open(&reference_path).unwrap();
            let candidate_engine = FsqliteEngine::open(&candidate_path).unwrap();
            let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
            let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
            let snapshot = presentation_quarantine_policy_matrix(&mut reference);
            assert_eq!(
                presentation_quarantine_policy_matrix(&mut candidate),
                snapshot
            );
            snapshot
        };
        let reference_engine = RusqliteEngine::open(&reference_path).unwrap();
        let candidate_engine = FsqliteEngine::open(&candidate_path).unwrap();
        let mut reference = SqlMetadataStore::open(reference_engine).unwrap();
        let mut candidate = SqlMetadataStore::open(candidate_engine).unwrap();
        let active = digest("rabs.authority.sha256.v1", 1);
        let action = digest("rabs.action-key.sha256.v1", 7);
        let action_key = digest_key(&action);
        let policies = [policy(5, false, TrustEvidenceTier::UnverifiedCandidate)];
        for store in [
            &mut reference as &mut dyn RabsMetadataStore,
            &mut candidate as &mut dyn RabsMetadataStore,
        ] {
            assert_eq!(store.differential_snapshot().unwrap(), snapshot);
            // Fresh readers declare their known domains before restoring
            // prior authority, just as coordinator startup does (R121).
            store.intern_domain(active.domain);
            let evaluation = reevaluate_action(store, &active, &action, &policies, 120).unwrap();
            assert_eq!(evaluation.ledger_version, 5);
            assert_eq!(evaluation.disposition, DISPOSITION_PRESENTATION_QUARANTINED);
            assert_eq!(
                serving_gate(store, &action_key, 200, 0).unwrap(),
                ServeDecision::NotServable {
                    disposition: DISPOSITION_PRESENTATION_QUARANTINED.to_owned(),
                }
            );
            assert!(!action_quarantine_present(store, &action_key).unwrap());
        }
        assert_eq!(
            reference.differential_snapshot().unwrap(),
            candidate.differential_snapshot().unwrap()
        );
    }
}