agentplane 0.32.0

Durable, replayable agent runtime — the journal is the plan of record
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
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
//! Case storage on redb.
//!
//! Two constraints carry the correctness here, and on redb both are the *shape*
//! of a key rather than a declaration a migration could drop:
//!
//! * [`CORR_OPEN`] is keyed by `(namespace, value)` and holds only open cases.
//!   "One open case per business key" is therefore inexpressible to violate —
//!   which is what stops two concurrent inbound messages fragmenting a process
//!   across two cases, with its obligations tracked in neither.
//! * [`DEADLINES_DUE`] is keyed by the instant an obligation first needs
//!   attention, so the sweep is a range scan rather than a table scan that
//!   quietly stops finishing on time at a hundred thousand open obligations.
//!
//! Secondary indexes are written in the **same** transaction as the row they
//! describe. redb is atomic across tables, so an index cannot be left
//! describing a row that was never committed.

use async_trait::async_trait;
use redb::{ReadableDatabase, ReadableTable, TableDefinition};
use serde_json::Value;

use crate::case::{CaseCensus, CaseStore, Correlation};
use crate::core::{
    BreachNote, Case, CaseId, CaseStatus, CaseVersion, CorrelationKey, Deadline, DeadlineState,
    Digest, RunId, StoreError, Timestamp,
};

use super::redb::{MAX_STR, RedbStore, be, begin_write, decoded};

/// What a case row holds: `kind`, `status`, `state`, `version`, `opened_at`.
type CaseRow<'a> = (&'a str, &'a str, &'a str, u64, i64);

/// `(tenant, case_id) -> `[`CaseRow`].
const CASES: TableDefinition<(&str, &str), CaseRow<'static>> = TableDefinition::new("cases");

/// `(tenant, namespace, value) -> case_id`, open cases only. One open case per key.
/// The tenant leads: a correlation key is a *business* value, and two tenants
/// will legitimately use the same one. Without it, one tenant's run joins
/// another tenant's case.
const CORR_OPEN: TableDefinition<(&str, &str, &str), &str> = TableDefinition::new("case_corr_open");

/// `(case_id, namespace, value) -> ()`, every key a case ever claimed.
const CORR_ALL: TableDefinition<(&str, &str, &str, &str), ()> =
    TableDefinition::new("case_corr_all");

/// `(case_id, written_at, digest) -> ()`, the blobs a case produced.
///
/// Keyed by time so erasure walks a case's artifacts in the order they were
/// created, and so the key is unique even when one case stores identical bytes
/// at two different moments — the digest alone would collide, which is correct
/// for storage and wrong for an index that has to enumerate.
const CASE_BLOBS: TableDefinition<(&str, &str, i64, &[u8]), ()> =
    TableDefinition::new("case_blobs");

/// `(case_id, seq) -> run_id`, in attachment order.
const CASE_RUNS: TableDefinition<(&str, &str, u64), &str> = TableDefinition::new("case_runs");

/// `(case_id, run_id) -> seq`, so attaching twice is idempotent.
const CASE_RUN_SEEN: TableDefinition<(&str, &str, &str), u64> =
    TableDefinition::new("case_run_seen");

/// `(tenant, case_id, name)` -> the obligation, and whoever has accounted for it.
///
/// The account rides on the obligation's own row rather than a second table:
/// they are written in one transaction and read in one place, so there is no
/// pair to disagree about whether a breach is still on the listing.
type DeadlineRow<'a> = (i64, &'a [u8], i64, u8, &'a str, u8, i64, &'a str, &'a str);

const DEADLINES: TableDefinition<(&str, &str, &str), DeadlineRow<'static>> =
    TableDefinition::new("case_deadlines");

/// `(trigger_at, case_id, name) -> resolved_at`, pending and warned only.
///
/// Keyed by `min(resolved_at, warn_at)` — the moment the obligation first needs
/// looking at. Keying on `resolved_at` alone would hide a deadline whose warning
/// has passed but whose due date has not, which is exactly the one a warning
/// exists to surface early.
const DEADLINES_DUE: TableDefinition<(&str, i64, &str, &str), i64> =
    TableDefinition::new("case_deadlines_due");

/// `(resolved_at, case_id, name) -> ()`, breached and unaccounted for.
///
/// An index rather than a filter over the primary, on the same terms
/// [`DEADLINES_DUE`] earns its upkeep: the obligation gauge reads it every
/// sweep tick, and a gauge computed by scanning every obligation a deployment
/// has ever registered gets slower exactly as the deployment gets busier. It is
/// written in the transaction that writes the state it reflects, so the two
/// cannot disagree.
const DEADLINES_UNACCOUNTED: TableDefinition<(&str, i64, &str, &str), ()> =
    TableDefinition::new("case_deadlines_unaccounted");

/// `(opened_at, case_id) -> ()`, cases that are not closed.
///
/// Carries the census: the count is the table's length and the oldest is its
/// first entry, so the two cannot disagree about which cases were open.
const CASES_OPEN: TableDefinition<(&str, i64, &str), ()> = TableDefinition::new("cases_open");

/// `(status, -opened_at, case_id) -> ()`. The negated stamp puts newest first
/// under redb's ascending iteration, which is the order the worklist wants.
const CASES_BY_STATUS: TableDefinition<(&str, &str, i64, &str), ()> =
    TableDefinition::new("cases_by_status");

fn ts(t: Timestamp) -> i64 {
    t.unix_timestamp()
}

fn from_ts(v: i64) -> Result<Timestamp, StoreError> {
    Timestamp::from_unix_timestamp(v).map_err(|e| StoreError::Corrupt {
        seq: 0,
        detail: format!("unrepresentable timestamp {v}: {e}"),
    })
}

fn status_from(s: &str) -> Result<CaseStatus, StoreError> {
    decoded("case status", s, CaseStatus::parse(s))
}

fn deadline_state_from(s: &str) -> Result<DeadlineState, StoreError> {
    decoded("deadline state", s, DeadlineState::parse(s))
}

/// Whether an obligation is still outstanding, and therefore indexed for the
/// sweep and blocking closure.
///
/// Takes the stored spelling because every caller holds a row, not a decoded
/// obligation; the rule itself is [`DeadlineState::is_open`], and an
/// unrecognised state is outstanding — an index that quietly dropped a row it
/// could not read would let a damaged obligation pass `close`.
fn is_outstanding(state: &str) -> bool {
    DeadlineState::parse(state).is_none_or(DeadlineState::is_open)
}

/// Whether a stored obligation is a breach nobody has accounted for.
///
/// The membership rule for [`DEADLINES_UNACCOUNTED`], written once so the
/// listing, the gauge and the four writers cannot each decide it.
fn unaccounted(state: &str, has_ack: u8) -> bool {
    state == DeadlineState::Breached.as_str() && has_ack == 0
}

/// Keep [`DEADLINES_UNACCOUNTED`] in step with one obligation's row, inside the
/// transaction that writes it.
fn reindex_unaccounted(
    w: &redb::WriteTransaction,
    tenant: &str,
    case: &str,
    name: &str,
    resolved: i64,
    was: bool,
    now: bool,
) -> Result<(), StoreError> {
    if was == now {
        return Ok(());
    }
    let mut t = w.open_table(DEADLINES_UNACCOUNTED).map_err(|e| be(&e))?;
    if now {
        t.insert((tenant, resolved, case, name), ())
            .map_err(|e| be(&e))?;
    } else {
        t.remove((tenant, resolved, case, name))
            .map_err(|e| be(&e))?;
    }
    Ok(())
}

/// Re-claim a reopened case's correlation keys.
///
/// [`close`] releases them so a genuinely new matter about the same entity opens
/// a fresh case; a case that leaves `Closed` has to take back the ones still
/// free, or it comes back as a matter no inbound message can ever correlate to
/// — live-looking and unreachable, which is the drift `close` exists to
/// prevent, read backwards.
///
/// A key another case has since claimed is **left where it is**. The identifier
/// belongs to whichever matter is open for it now, and a reopening that took one
/// back would silently redirect that matter's traffic.
///
/// [`close`]: crate::case::CaseStore::close
fn reclaim_correlation(
    w: &redb::WriteTransaction,
    tenant: &str,
    case: &str,
) -> Result<(), StoreError> {
    let mut mine: Vec<(String, String)> = Vec::new();
    {
        let corr_all = w.open_table(CORR_ALL).map_err(|e| be(&e))?;
        for e in corr_all
            .range((tenant, case, "", "")..=(tenant, case, MAX_STR, MAX_STR))
            .map_err(|e| be(&e))?
        {
            let (k, _) = e.map_err(|e| be(&e))?;
            let (_, _, ns, v) = k.value();
            mine.push((ns.to_owned(), v.to_owned()));
        }
    }
    let mut corr_open = w.open_table(CORR_OPEN).map_err(|e| be(&e))?;
    for (ns, v) in mine {
        if corr_open
            .get((tenant, ns.as_str(), v.as_str()))
            .map_err(|e| be(&e))?
            .is_none()
        {
            corr_open
                .insert((tenant, ns.as_str(), v.as_str()), case)
                .map_err(|e| be(&e))?;
        }
    }
    Ok(())
}

/// The account's four columns, present or absent.
///
/// One encoder so the four writers of a deadline row cannot spell absence four
/// ways — `has_ack` is what says whether the rest mean anything, exactly as
/// `has_warn` does for `warn_at`.
fn ack_columns(note: Option<&BreachNote>) -> (u8, i64, &str, &str) {
    note.map_or((0, 0, "", ""), |n| {
        (1, ts(n.at), n.by.as_str(), n.note.as_str())
    })
}

/// When an obligation first needs attention.
fn trigger_at(resolved_at: i64, warn_at: Option<i64>) -> i64 {
    warn_at.map_or(resolved_at, |w| w.min(resolved_at))
}

fn parse_case_id(id: &str) -> Result<CaseId, StoreError> {
    CaseId::parse(id).map_err(|e| StoreError::Corrupt {
        seq: 0,
        detail: format!("bad case id '{id}': {e}"),
    })
}

fn build_deadline(case: &str, name: &str, row: DeadlineRow<'_>) -> Result<Deadline, StoreError> {
    let (resolved_at, digest, warn_at, has_warn, state, has_ack, ack_at, by, note) = row;
    let bytes: [u8; 32] = digest.try_into().map_err(|_| StoreError::Corrupt {
        seq: 0,
        detail: "stored calendar digest is not 32 bytes".into(),
    })?;
    Ok(Deadline {
        case: parse_case_id(case)?,
        name: name.to_owned(),
        resolved_at: from_ts(resolved_at)?,
        calendar_digest: Digest::from_bytes(bytes),
        warn_at: if has_warn == 1 {
            Some(from_ts(warn_at)?)
        } else {
            None
        },
        state: deadline_state_from(state)?,
        acknowledged: if has_ack == 1 {
            Some(BreachNote {
                by: by.to_owned(),
                note: note.to_owned(),
                at: from_ts(ack_at)?,
            })
        } else {
            None
        },
    })
}

/// Create every case table, so a read on a fresh database is a miss rather than
/// a missing-table error.
///
/// redb creates a table on first *write*, so `case()` reading `CASE_RUNS` for a
/// case with no runs yet would otherwise fail rather than return an empty list.
pub(super) fn create_tables(w: &redb::WriteTransaction) -> Result<(), StoreError> {
    w.open_table(CASES).map_err(|e| be(&e))?;
    w.open_table(CORR_OPEN).map_err(|e| be(&e))?;
    w.open_table(CORR_ALL).map_err(|e| be(&e))?;
    w.open_table(DEADLINES_UNACCOUNTED).map_err(|e| be(&e))?;
    w.open_table(CASE_RUNS).map_err(|e| be(&e))?;
    w.open_table(CASE_BLOBS).map_err(|e| be(&e))?;
    w.open_table(CASE_RUN_SEEN).map_err(|e| be(&e))?;
    w.open_table(DEADLINES).map_err(|e| be(&e))?;
    w.open_table(DEADLINES_DUE).map_err(|e| be(&e))?;
    w.open_table(CASES_OPEN).map_err(|e| be(&e))?;
    w.open_table(CASES_BY_STATUS).map_err(|e| be(&e))?;
    Ok(())
}

#[async_trait]
impl CaseStore for RedbStore {
    fn tenant(&self) -> &str {
        self.tenant_str()
    }

    async fn correlate(&self, keys: &[CorrelationKey]) -> Result<Option<CaseId>, StoreError> {
        let tenant = self.tenant_name();
        if keys.is_empty() {
            return Ok(None);
        }
        let keys = keys.to_vec();
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let t = r.open_table(CORR_OPEN).map_err(|e| be(&e))?;
            for k in &keys {
                if let Some(v) = t
                    .get((tenant.as_str(), k.namespace.as_str(), k.value.as_str()))
                    .map_err(|e| be(&e))?
                {
                    return parse_case_id(v.value()).map(Some);
                }
            }
            Ok(None)
        })
        .await
    }

    async fn correlate_or_open(
        &self,
        kind: &str,
        keys: &[CorrelationKey],
        at: Timestamp,
    ) -> Result<Correlation, StoreError> {
        let tenant = self.tenant_name();
        let kind = kind.to_owned();
        let keys = keys.to_vec();
        let id = CaseId::generate();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            // Computed inside a scope so every table borrow is released before
            // the commit below; redb takes the transaction by value.
            let outcome = {
                let mut corr_open = w.open_table(CORR_OPEN).map_err(|e| be(&e))?;

                // Looked up inside the write transaction, so a concurrent
                // opener cannot slip between the check and the insert.
                let mut attached = None;
                for k in &keys {
                    if let Some(v) = corr_open
                        .get((tenant.as_str(), k.namespace.as_str(), k.value.as_str()))
                        .map_err(|e| be(&e))?
                    {
                        attached = Some(parse_case_id(v.value())?);
                        break;
                    }
                }

                if let Some(found) = attached {
                    Correlation::Attached(found)
                } else {
                    let case = id.to_string();
                    w.open_table(CASES)
                        .map_err(|e| be(&e))?
                        .insert(
                            (tenant.as_str(), case.as_str()),
                            (
                                kind.as_str(),
                                CaseStatus::Open.as_str(),
                                "null",
                                0u64,
                                ts(at),
                            ),
                        )
                        .map_err(|e| be(&e))?;

                    let mut corr_all = w.open_table(CORR_ALL).map_err(|e| be(&e))?;
                    for k in &keys {
                        // The key *is* the constraint: a prior value means
                        // someone claimed it between our read and our write.
                        let prior = corr_open
                            .insert(
                                (tenant.as_str(), k.namespace.as_str(), k.value.as_str()),
                                case.as_str(),
                            )
                            .map_err(|e| be(&e))?;
                        if prior.is_some() {
                            return Err(StoreError::Backend(format!(
                                "correlation key {k} was claimed concurrently — retry"
                            )));
                        }
                        corr_all
                            .insert(
                                (
                                    tenant.as_str(),
                                    case.as_str(),
                                    k.namespace.as_str(),
                                    k.value.as_str(),
                                ),
                                (),
                            )
                            .map_err(|e| be(&e))?;
                    }

                    w.open_table(CASES_OPEN)
                        .map_err(|e| be(&e))?
                        .insert((tenant.as_str(), ts(at), case.as_str()), ())
                        .map_err(|e| be(&e))?;
                    w.open_table(CASES_BY_STATUS)
                        .map_err(|e| be(&e))?
                        .insert(
                            (
                                tenant.as_str(),
                                CaseStatus::Open.as_str(),
                                -ts(at),
                                case.as_str(),
                            ),
                            (),
                        )
                        .map_err(|e| be(&e))?;

                    Correlation::Opened(id)
                }
            };
            w.commit().map_err(|e| be(&e))?;
            Ok(outcome)
        })
        .await
    }

    async fn case(&self, id: CaseId) -> Result<Option<Case>, StoreError> {
        let tenant = self.tenant_name();
        let key = id.to_string();
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let cases = r.open_table(CASES).map_err(|e| be(&e))?;
            let Some(row) = cases
                .get((tenant.as_str(), key.as_str()))
                .map_err(|e| be(&e))?
            else {
                return Ok(None);
            };
            let (kind, status, state, version, opened) = row.value();
            let (kind, status, state) = (kind.to_owned(), status.to_owned(), state.to_owned());
            drop(row);

            let corr = r.open_table(CORR_ALL).map_err(|e| be(&e))?;
            let mut correlation = Vec::new();
            for e in corr
                .range(
                    (tenant.as_str(), key.as_str(), "", "")
                        ..=(tenant.as_str(), key.as_str(), MAX_STR, MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                let (k, _) = e.map_err(|e| be(&e))?;
                let (_, _, ns, v) = k.value();
                correlation.push(CorrelationKey::new(ns.to_owned(), v.to_owned()));
            }

            let runs_t = r.open_table(CASE_RUNS).map_err(|e| be(&e))?;
            let mut runs = Vec::new();
            for e in runs_t
                .range(
                    (tenant.as_str(), key.as_str(), 0u64)
                        ..=(tenant.as_str(), key.as_str(), u64::MAX),
                )
                .map_err(|e| be(&e))?
            {
                let (_, v) = e.map_err(|e| be(&e))?;
                let s = v.value();
                runs.push(RunId::parse(s).map_err(|e| StoreError::Corrupt {
                    seq: 0,
                    detail: format!("bad run id '{s}': {e}"),
                })?);
            }

            Ok(Some(Case {
                id,
                kind,
                status: status_from(&status)?,
                correlation,
                state: serde_json::from_str(&state).unwrap_or(Value::Null),
                version: CaseVersion(version),
                opened_at: from_ts(opened)?,
                runs,
            }))
        })
        .await
    }

    async fn cases(&self, after: Option<CaseId>, limit: usize) -> Result<Vec<Case>, StoreError> {
        let tenant = self.tenant_name();
        let cursor = after.map(|c| c.to_string());
        // Ids first, rows second — through `case()`, so the assembly of a case
        // from its five tables exists exactly once. A second copy here would be
        // the one that drifts when a table is added, and the export is the
        // reader least able to notice a field quietly missing.
        let page: Vec<CaseId> = self
            .with_db(move |db| {
                let r = db.begin_read().map_err(|e| be(&e))?;
                let cases = r.open_table(CASES).map_err(|e| be(&e))?;
                let lower = cursor.as_deref().unwrap_or("");
                let mut out = Vec::new();
                for e in cases
                    .range((tenant.as_str(), lower)..=(tenant.as_str(), MAX_STR))
                    .map_err(|e| be(&e))?
                {
                    if out.len() >= limit {
                        break;
                    }
                    let (k, _) = e.map_err(|e| be(&e))?;
                    let (_, id) = k.value();
                    // The range's lower bound is inclusive; the cursor is the
                    // last id the caller saw, so it is skipped rather than
                    // served twice.
                    if Some(id) == cursor.as_deref() {
                        continue;
                    }
                    out.push(parse_case_id(id)?);
                }
                Ok(out)
            })
            .await?;
        let mut out = Vec::with_capacity(page.len());
        for id in page {
            if let Some(case) = self.case(id).await? {
                out.push(case);
            }
        }
        Ok(out)
    }

    // One transaction, deliberately: an import that committed the case row
    // and then failed on an index would leave exactly the partially-indexed
    // matter the read-path battery exists to catch. Length is the cost of
    // atomicity here, not of doing several jobs.
    #[allow(clippy::too_many_lines)]
    async fn import_case(
        &self,
        case: &Case,
        deadlines: &[Deadline],
        blobs: &[Digest],
    ) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let case = case.clone();
        let deadlines = deadlines.to_vec();
        let blobs = blobs.to_vec();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                let key = case.id.to_string();
                let state = serde_json::to_string(&case.state)
                    .map_err(|e| StoreError::Backend(e.to_string()))?;
                let opened = ts(case.opened_at);
                let mut cases = w.open_table(CASES).map_err(|e| be(&e))?;
                if cases
                    .get((tenant.as_str(), key.as_str()))
                    .map_err(|e| be(&e))?
                    .is_some()
                {
                    return Err(StoreError::Backend(format!(
                        "case {} already exists — a restore rebuilds a case layer, it does \
                         not merge one",
                        case.id
                    )));
                }
                cases
                    .insert(
                        (tenant.as_str(), key.as_str()),
                        (
                            case.kind.as_str(),
                            case.status.as_str(),
                            state.as_str(),
                            case.version.0,
                            opened,
                        ),
                    )
                    .map_err(|e| be(&e))?;

                // Correlation, both halves. The open half is the one with a
                // constraint to respect: one open case per business key, and a
                // restore that overwrote a claim would silently merge two
                // matters.
                let mut corr_all = w.open_table(CORR_ALL).map_err(|e| be(&e))?;
                let mut corr_open = w.open_table(CORR_OPEN).map_err(|e| be(&e))?;
                for k in &case.correlation {
                    corr_all
                        .insert(
                            (
                                tenant.as_str(),
                                key.as_str(),
                                k.namespace.as_str(),
                                k.value.as_str(),
                            ),
                            (),
                        )
                        .map_err(|e| be(&e))?;
                    if case.status != CaseStatus::Closed {
                        let prior = corr_open
                            .insert(
                                (tenant.as_str(), k.namespace.as_str(), k.value.as_str()),
                                key.as_str(),
                            )
                            .map_err(|e| be(&e))?;
                        if let Some(prior) = prior
                            && prior.value() != key
                        {
                            return Err(StoreError::Backend(format!(
                                "correlation key {k} is already claimed by another open case — \
                                 importing this one would merge two matters"
                            )));
                        }
                    }
                }

                // Runs, in the order the export recorded them attaching.
                let mut runs = w.open_table(CASE_RUNS).map_err(|e| be(&e))?;
                let mut seen = w.open_table(CASE_RUN_SEEN).map_err(|e| be(&e))?;
                for (at, run) in case.runs.iter().enumerate() {
                    let run = run.to_string();
                    let seq = at as u64;
                    runs.insert((tenant.as_str(), key.as_str(), seq), run.as_str())
                        .map_err(|e| be(&e))?;
                    seen.insert((tenant.as_str(), key.as_str(), run.as_str()), seq)
                        .map_err(|e| be(&e))?;
                }

                // The status indexes, exactly as the ordinary paths keep them:
                // every case in `by_status`, only unclosed ones in the census.
                w.open_table(CASES_BY_STATUS)
                    .map_err(|e| be(&e))?
                    .insert(
                        (tenant.as_str(), case.status.as_str(), -opened, key.as_str()),
                        (),
                    )
                    .map_err(|e| be(&e))?;
                if case.status != CaseStatus::Closed {
                    w.open_table(CASES_OPEN)
                        .map_err(|e| be(&e))?
                        .insert((tenant.as_str(), opened, key.as_str()), ())
                        .map_err(|e| be(&e))?;
                }

                let mut d = w.open_table(DEADLINES).map_err(|e| be(&e))?;
                let mut due = w.open_table(DEADLINES_DUE).map_err(|e| be(&e))?;
                for deadline in &deadlines {
                    let resolved = ts(deadline.resolved_at);
                    let warn = deadline.warn_at.map(ts);
                    let digest = deadline.calendar_digest.as_bytes().to_vec();
                    let state = deadline.state.as_str();
                    let (has_ack, ack_at, by, note) = ack_columns(deadline.acknowledged.as_ref());
                    d.insert(
                        (tenant.as_str(), key.as_str(), deadline.name.as_str()),
                        (
                            resolved,
                            digest.as_slice(),
                            warn.unwrap_or(0),
                            u8::from(warn.is_some()),
                            state,
                            has_ack,
                            ack_at,
                            by,
                            note,
                        ),
                    )
                    .map_err(|e| be(&e))?;
                    if is_outstanding(state) {
                        due.insert(
                            (
                                tenant.as_str(),
                                trigger_at(resolved, warn),
                                key.as_str(),
                                deadline.name.as_str(),
                            ),
                            resolved,
                        )
                        .map_err(|e| be(&e))?;
                    }
                    reindex_unaccounted(
                        &w,
                        &tenant,
                        &key,
                        &deadline.name,
                        resolved,
                        false,
                        unaccounted(state, has_ack),
                    )?;
                }

                // Blob links. The export carries digests without their link
                // timestamps, so these are stamped from `opened_at` plus an
                // ordinal — the key needs uniqueness and erasure needs
                // reachability, and neither needs the original instant.
                let mut case_blobs = w.open_table(CASE_BLOBS).map_err(|e| be(&e))?;
                for (at, digest) in blobs.iter().enumerate() {
                    case_blobs
                        .insert(
                            (
                                tenant.as_str(),
                                key.as_str(),
                                opened + i64::try_from(at).unwrap_or(i64::MAX),
                                digest.as_bytes().as_slice(),
                            ),
                            (),
                        )
                        .map_err(|e| be(&e))?;
                }
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn attach_run(&self, case: CaseId, run: RunId) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let (c, r) = (case.to_string(), run.to_string());
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                let mut seen = w.open_table(CASE_RUN_SEEN).map_err(|e| be(&e))?;
                if seen
                    .get((tenant.as_str(), c.as_str(), r.as_str()))
                    .map_err(|e| be(&e))?
                    .is_none()
                {
                    let mut runs = w.open_table(CASE_RUNS).map_err(|e| be(&e))?;
                    // Zero-based, matching `import_case`'s enumeration and the
                    // SQL backend — one rule for what position the first run
                    // holds, whichever door it came through.
                    let next = runs
                        .range(
                            (tenant.as_str(), c.as_str(), 0u64)
                                ..=(tenant.as_str(), c.as_str(), u64::MAX),
                        )
                        .map_err(|e| be(&e))?
                        .next_back()
                        .transpose()
                        .map_err(|e| be(&e))?
                        .map_or(0, |(k, _)| k.value().2 + 1);
                    runs.insert((tenant.as_str(), c.as_str(), next), r.as_str())
                        .map_err(|e| be(&e))?;
                    seen.insert((tenant.as_str(), c.as_str(), r.as_str()), next)
                        .map_err(|e| be(&e))?;
                }
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn detach_run(&self, case: CaseId, run: RunId) -> Result<bool, StoreError> {
        let tenant = self.tenant_name();
        let (c, r) = (case.to_string(), run.to_string());
        self.with_db(move |db| {
            let w = begin_write(db)?;
            let removed = {
                let mut seen = w.open_table(CASE_RUN_SEEN).map_err(|e| be(&e))?;
                // Both tables or neither: `CASE_RUN_SEEN` is what makes
                // `attach_run` idempotent, so leaving it behind would mean a
                // later attach of the same run silently did nothing.
                match seen
                    .remove((tenant.as_str(), c.as_str(), r.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| v.value())
                {
                    Some(seq) => {
                        w.open_table(CASE_RUNS)
                            .map_err(|e| be(&e))?
                            .remove((tenant.as_str(), c.as_str(), seq))
                            .map_err(|e| be(&e))?;
                        true
                    }
                    None => false,
                }
            };
            w.commit().map_err(|e| be(&e))?;
            Ok(removed)
        })
        .await
    }

    async fn link_blob(
        &self,
        case: CaseId,
        digest: Digest,
        at: Timestamp,
    ) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let key = case.to_string();
        let bytes = digest.as_bytes().to_vec();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                w.open_table(CASE_BLOBS)
                    .map_err(|e| be(&e))?
                    .insert(
                        (tenant.as_str(), key.as_str(), ts(at), bytes.as_slice()),
                        (),
                    )
                    .map_err(|e| be(&e))?;
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn blobs_of(&self, case: CaseId) -> Result<Vec<Digest>, StoreError> {
        let tenant = self.tenant_name();
        let key = case.to_string();
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let t = r.open_table(CASE_BLOBS).map_err(|e| be(&e))?;
            let mut out = Vec::new();
            let mut seen = std::collections::BTreeSet::new();
            for e in t
                .range(
                    (tenant.as_str(), key.as_str(), i64::MIN, [].as_slice())
                        ..=(
                            tenant.as_str(),
                            key.as_str(),
                            i64::MAX,
                            [0xffu8; 32].as_slice(),
                        ),
                )
                .map_err(|e| be(&e))?
            {
                let (k, _) = e.map_err(|e| be(&e))?;
                let raw: [u8; 32] = k.value().3.try_into().map_err(|_| StoreError::Corrupt {
                    seq: 0,
                    detail: "a linked blob digest is not 32 bytes".into(),
                })?;
                // The same bytes stored twice are one artifact; erasing it twice
                // would report a second expiry that never happened.
                if seen.insert(raw) {
                    out.push(Digest::from_bytes(raw));
                }
            }
            Ok(out)
        })
        .await
    }

    async fn put_state(
        &self,
        case: CaseId,
        expected: CaseVersion,
        state: Value,
    ) -> Result<CaseVersion, StoreError> {
        let tenant = self.tenant_name();
        let key = case.to_string();
        let encoded = serde_json::to_string(&state)?;
        let next = expected.next();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            let result = {
                let mut cases = w.open_table(CASES).map_err(|e| be(&e))?;
                let current = cases
                    .get((tenant.as_str(), key.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| {
                        let (k, s, st, ver, at) = v.value();
                        (k.to_owned(), s.to_owned(), st.to_owned(), ver, at)
                    });
                match current {
                    // Read and write inside one transaction, so the check and
                    // the write cannot be separated by another writer — the
                    // predicate the SQL backend put on the UPDATE.
                    Some((kind, status, _, ver, at)) if ver == expected.0 => {
                        cases
                            .insert(
                                (tenant.as_str(), key.as_str()),
                                (kind.as_str(), status.as_str(), encoded.as_str(), next.0, at),
                            )
                            .map_err(|e| be(&e))?;
                        Ok(next)
                    }
                    // The caller needs to know which: a missing case reported as
                    // a conflict sends them into a re-read loop against nothing.
                    Some((_, _, _, current, _)) => Err(StoreError::CaseConflict {
                        case: key.clone(),
                        expected: expected.0,
                        current,
                    }),
                    None => Err(StoreError::NotFound(key.clone())),
                }
            };
            let out = result?;
            w.commit().map_err(|e| be(&e))?;
            Ok(out)
        })
        .await
    }

    async fn set_status(&self, case: CaseId, status: CaseStatus) -> Result<(), StoreError> {
        // Closing is not an ordinary status change: it must release the
        // correlation keys and refuse an open obligation. Routing it through
        // `close` is what keeps the two spellings of "closed" — the `status`
        // column and correlation-open membership — from drifting apart, which
        // they did while `set_status(Closed)` wrote only the column and left the
        // case correlatable (a new matter would attach to a closed case).
        if status == CaseStatus::Closed {
            return self.close(case).await;
        }
        let tenant = self.tenant_name();
        let key = case.to_string();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                let mut cases = w.open_table(CASES).map_err(|e| be(&e))?;
                let Some(row) = cases
                    .get((tenant.as_str(), key.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| {
                        let (k, s, st, ver, at) = v.value();
                        (k.to_owned(), s.to_owned(), st.to_owned(), ver, at)
                    })
                else {
                    return Err(StoreError::NotFound(key));
                };
                let (kind, was, state, ver, at) = row;
                cases
                    .insert(
                        (tenant.as_str(), key.as_str()),
                        (kind.as_str(), status.as_str(), state.as_str(), ver, at),
                    )
                    .map_err(|e| be(&e))?;
                drop(cases);
                reindex_status(&w, &tenant, &key, &was, status.as_str(), at)?;
                if was == CaseStatus::Closed.as_str() {
                    reclaim_correlation(&w, &tenant, &key)?;
                }
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn close(&self, case: CaseId) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let key = case.to_string();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                // A case with an unmet obligation may not be closed — the check
                // that stops a missed regulatory window disappearing behind a
                // tidy "closed" status.
                let outstanding = {
                    let d = w.open_table(DEADLINES).map_err(|e| be(&e))?;
                    let mut n = 0usize;
                    for e in d
                        .range(
                            (tenant.as_str(), key.as_str(), "")
                                ..=(tenant.as_str(), key.as_str(), MAX_STR),
                        )
                        .map_err(|e| be(&e))?
                    {
                        let (_, v) = e.map_err(|e| be(&e))?;
                        if is_outstanding(v.value().4) {
                            n += 1;
                        }
                    }
                    n
                };
                if outstanding > 0 {
                    return Err(StoreError::ObligationsOutstanding {
                        case: case.to_string(),
                        outstanding,
                    });
                }

                let mut cases = w.open_table(CASES).map_err(|e| be(&e))?;
                let Some(row) = cases
                    .get((tenant.as_str(), key.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| {
                        let (k, s, st, ver, at) = v.value();
                        (k.to_owned(), s.to_owned(), st.to_owned(), ver, at)
                    })
                else {
                    return Err(StoreError::NotFound(key));
                };
                let (kind, was, state, ver, at) = row;
                cases
                    .insert(
                        (tenant.as_str(), key.as_str()),
                        (
                            kind.as_str(),
                            CaseStatus::Closed.as_str(),
                            state.as_str(),
                            ver,
                            at,
                        ),
                    )
                    .map_err(|e| be(&e))?;
                reindex_status(&w, &tenant, &key, &was, CaseStatus::Closed.as_str(), at)?;

                // Release the correlation keys so a genuinely new matter about
                // the same entity opens a fresh case rather than reanimating
                // this one.
                let corr_all = w.open_table(CORR_ALL).map_err(|e| be(&e))?;
                let mut owned: Vec<(String, String)> = Vec::new();
                for e in corr_all
                    .range(
                        (tenant.as_str(), key.as_str(), "", "")
                            ..=(tenant.as_str(), key.as_str(), MAX_STR, MAX_STR),
                    )
                    .map_err(|e| be(&e))?
                {
                    let (k, _) = e.map_err(|e| be(&e))?;
                    let (_, _, ns, v) = k.value();
                    owned.push((ns.to_owned(), v.to_owned()));
                }
                drop(corr_all);
                let mut corr_open = w.open_table(CORR_OPEN).map_err(|e| be(&e))?;
                for (ns, v) in owned {
                    // Only if still ours: a key released and re-claimed by a new
                    // case must not be removed out from under that case.
                    let mine = corr_open
                        .get((tenant.as_str(), ns.as_str(), v.as_str()))
                        .map_err(|e| be(&e))?
                        .is_some_and(|got| got.value() == key);
                    if mine {
                        corr_open
                            .remove((tenant.as_str(), ns.as_str(), v.as_str()))
                            .map_err(|e| be(&e))?;
                    }
                }
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn register_deadline(&self, deadline: &Deadline) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let (case, name) = (deadline.case.to_string(), deadline.name.clone());
        let resolved = ts(deadline.resolved_at);
        let warn = deadline.warn_at.map(ts);
        let digest = deadline.calendar_digest.as_bytes().to_vec();
        let state = deadline.state.as_str();
        let ack = deadline.acknowledged.clone();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                // Read inside the write transaction, which is what makes this
                // and `close` decide one at a time: redb admits one writer, so
                // the status this reads cannot change before the insert lands.
                let closed = w
                    .open_table(CASES)
                    .map_err(|e| be(&e))?
                    .get((tenant.as_str(), case.as_str()))
                    .map_err(|e| be(&e))?
                    .is_some_and(|v| v.value().1 == CaseStatus::Closed.as_str());
                if closed {
                    return Err(StoreError::CaseClosed { case });
                }
                let (has_ack, ack_at, by, note) = ack_columns(ack.as_ref());
                let mut d = w.open_table(DEADLINES).map_err(|e| be(&e))?;
                // First registration wins, as `ON CONFLICT DO NOTHING` did.
                if d.get((tenant.as_str(), case.as_str(), name.as_str()))
                    .map_err(|e| be(&e))?
                    .is_none()
                {
                    d.insert(
                        (tenant.as_str(), case.as_str(), name.as_str()),
                        (
                            resolved,
                            digest.as_slice(),
                            warn.unwrap_or(0),
                            u8::from(warn.is_some()),
                            state,
                            has_ack,
                            ack_at,
                            by,
                            note,
                        ),
                    )
                    .map_err(|e| be(&e))?;
                    if is_outstanding(state) {
                        w.open_table(DEADLINES_DUE)
                            .map_err(|e| be(&e))?
                            .insert(
                                (
                                    tenant.as_str(),
                                    trigger_at(resolved, warn),
                                    case.as_str(),
                                    name.as_str(),
                                ),
                                resolved,
                            )
                            .map_err(|e| be(&e))?;
                    }
                    drop(d);
                    reindex_unaccounted(
                        &w,
                        &tenant,
                        &case,
                        &name,
                        resolved,
                        false,
                        unaccounted(state, has_ack),
                    )?;
                }
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn deadlines(&self, case: CaseId) -> Result<Vec<Deadline>, StoreError> {
        let tenant = self.tenant_name();
        let key = case.to_string();
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let d = r.open_table(DEADLINES).map_err(|e| be(&e))?;
            let mut out = Vec::new();
            for e in d
                .range(
                    (tenant.as_str(), key.as_str(), "")..=(tenant.as_str(), key.as_str(), MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                let (k, v) = e.map_err(|e| be(&e))?;
                out.push(build_deadline(k.value().1, k.value().2, v.value())?);
            }
            out.sort_by_key(|d| d.resolved_at);
            Ok(out)
        })
        .await
    }

    async fn set_deadline_state(
        &self,
        case: CaseId,
        name: &str,
        state: DeadlineState,
    ) -> Result<(), StoreError> {
        let tenant = self.tenant_name();
        let (key, name) = (case.to_string(), name.to_owned());
        let to = state.as_str();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            {
                let mut d = w.open_table(DEADLINES).map_err(|e| be(&e))?;
                let Some(row) = d
                    .get((tenant.as_str(), key.as_str(), name.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| {
                        let (res, dig, warn, has, st, has_ack, at, by, note) = v.value();
                        (
                            res,
                            dig.to_vec(),
                            warn,
                            has,
                            st.to_owned(),
                            has_ack,
                            at,
                            by.to_owned(),
                            note.to_owned(),
                        )
                    })
                else {
                    return Err(StoreError::NotFound(format!("{key}/{name}")));
                };
                let (resolved, digest, warn, has_warn, was, has_ack, ack_at, by, note) = row;

                // How an obligation ended is not editable. `cx.meet_deadline`
                // reaches this from a skill, so without the check a run that
                // answered late would take the miss off the operator's listing
                // and out of the row at once.
                let from = deadline_state_from(&was)?;
                if !from.may_become(state) {
                    return Err(StoreError::DeadlineFinal {
                        case: key,
                        obligation: name,
                        from: was,
                        to: to.to_owned(),
                    });
                }
                d.insert(
                    (tenant.as_str(), key.as_str(), name.as_str()),
                    (
                        resolved,
                        digest.as_slice(),
                        warn,
                        has_warn,
                        to,
                        has_ack,
                        ack_at,
                        by.as_str(),
                        note.as_str(),
                    ),
                )
                .map_err(|e| be(&e))?;

                // The sweep index tracks outstanding obligations only, and it is
                // updated in the same transaction as the state it reflects.
                let warn_opt = (has_warn == 1).then_some(warn);
                let trigger = trigger_at(resolved, warn_opt);
                let mut due = w.open_table(DEADLINES_DUE).map_err(|e| be(&e))?;
                match (is_outstanding(&was), is_outstanding(to)) {
                    (true, false) => {
                        due.remove((tenant.as_str(), trigger, key.as_str(), name.as_str()))
                            .map_err(|e| be(&e))?;
                    }
                    (false, true) => {
                        due.insert(
                            (tenant.as_str(), trigger, key.as_str(), name.as_str()),
                            resolved,
                        )
                        .map_err(|e| be(&e))?;
                    }
                    _ => {}
                }
                drop(due);
                drop(d);
                reindex_unaccounted(
                    &w,
                    &tenant,
                    &key,
                    &name,
                    resolved,
                    unaccounted(&was, has_ack),
                    unaccounted(to, has_ack),
                )?;
            }
            w.commit().map_err(|e| be(&e))?;
            Ok(())
        })
        .await
    }

    async fn census(&self, now: Timestamp) -> Result<CaseCensus, StoreError> {
        let tenant = self.tenant_name();
        let now_i = ts(now);
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let open_t = r.open_table(CASES_OPEN).map_err(|e| be(&e))?;
            // Count and oldest come from one index, so they cannot disagree
            // about which cases were open.
            // Ranged, not `len()` and `first()`: those answer for the whole
            // table, so a census would report every tenant's open cases as this
            // one's and date them from another tenant's oldest.
            let mut open = 0u64;
            let mut oldest = None;
            for e in open_t
                .range((tenant.as_str(), i64::MIN, "")..=(tenant.as_str(), i64::MAX, MAX_STR))
                .map_err(|e| be(&e))?
            {
                let (k, _) = e.map_err(|e| be(&e))?;
                if oldest.is_none() {
                    oldest = Some(k.value().1);
                }
                open += 1;
            }

            let due_t = r.open_table(DEADLINES_DUE).map_err(|e| be(&e))?;
            let mut due = 0u64;
            for e in due_t
                .range(
                    (tenant.as_str(), i64::MIN, "", "")
                        ..=(tenant.as_str(), now_i, MAX_STR, MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                let (_, resolved) = e.map_err(|e| be(&e))?;
                // The census counts what is *due*, not what has merely warned.
                if resolved.value() <= now_i {
                    due += 1;
                }
            }

            let idx = r.open_table(DEADLINES_UNACCOUNTED).map_err(|e| be(&e))?;
            let mut breached = 0u64;
            for e in idx
                .range(
                    (tenant.as_str(), i64::MIN, "", "")
                        ..=(tenant.as_str(), i64::MAX, MAX_STR, MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                e.map_err(|e| be(&e))?;
                breached += 1;
            }

            Ok(CaseCensus {
                open,
                oldest_age_secs: oldest.map(|o| {
                    crate::runtime::metrics::age_secs(
                        Timestamp::from_unix_timestamp(o).unwrap_or(now),
                        now,
                    )
                }),
                due,
                breached,
            })
        })
        .await
    }

    async fn due(&self, now: Timestamp, limit: usize) -> Result<Vec<Deadline>, StoreError> {
        let tenant = self.tenant_name();
        let now_i = ts(now);
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let due_t = r.open_table(DEADLINES_DUE).map_err(|e| be(&e))?;
            let d = r.open_table(DEADLINES).map_err(|e| be(&e))?;
            let mut out = Vec::new();
            // Ascending by trigger instant, so the longest-waiting obligation is
            // taken first when the limit bites.
            for e in due_t
                .range(
                    (tenant.as_str(), i64::MIN, "", "")
                        ..=(tenant.as_str(), now_i, MAX_STR, MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                if out.len() >= limit {
                    break;
                }
                let (k, _) = e.map_err(|e| be(&e))?;
                let (_, _, case, name) = k.value();
                if let Some(row) = d.get((tenant.as_str(), case, name)).map_err(|e| be(&e))? {
                    out.push(build_deadline(case, name, row.value())?);
                }
            }
            out.sort_by_key(|d| d.resolved_at);
            Ok(out)
        })
        .await
    }

    async fn breached(&self, limit: usize) -> Result<Vec<Deadline>, StoreError> {
        let tenant = self.tenant_name();
        self.with_db(move |db| {
            let r = db.begin_read().map_err(|e| be(&e))?;
            let idx = r.open_table(DEADLINES_UNACCOUNTED).map_err(|e| be(&e))?;
            let d = r.open_table(DEADLINES).map_err(|e| be(&e))?;
            let mut out = Vec::new();
            // Ascending by the missed instant, so a truncated answer is the
            // longest-overdue obligations rather than whichever the key order
            // reached first — and the truncation is honest, because an
            // acknowledged breach is not in this index to occupy the page.
            for e in idx
                .range(
                    (tenant.as_str(), i64::MIN, "", "")
                        ..=(tenant.as_str(), i64::MAX, MAX_STR, MAX_STR),
                )
                .map_err(|e| be(&e))?
            {
                if out.len() >= limit {
                    break;
                }
                let (k, _) = e.map_err(|e| be(&e))?;
                let (_, _, case, name) = k.value();
                let Some(row) = d.get((tenant.as_str(), case, name)).map_err(|e| be(&e))? else {
                    continue;
                };
                out.push(build_deadline(case, name, row.value())?);
            }
            Ok(out)
        })
        .await
    }

    async fn acknowledge_breach(
        &self,
        case: CaseId,
        name: &str,
        note: &BreachNote,
    ) -> Result<bool, StoreError> {
        let tenant = self.tenant_name();
        let (key, name) = (case.to_string(), name.to_owned());
        let note = note.clone();
        self.with_db(move |db| {
            let w = begin_write(db)?;
            let recorded = {
                let mut d = w.open_table(DEADLINES).map_err(|e| be(&e))?;
                let Some(row) = d
                    .get((tenant.as_str(), key.as_str(), name.as_str()))
                    .map_err(|e| be(&e))?
                    .map(|v| {
                        let (res, dig, warn, has, st, has_ack, at, by, n) = v.value();
                        (
                            res,
                            dig.to_vec(),
                            warn,
                            has,
                            st.to_owned(),
                            has_ack,
                            at,
                            by.to_owned(),
                            n.to_owned(),
                        )
                    })
                else {
                    return Err(StoreError::NotFound(format!("{key}/{name}")));
                };
                let (resolved, digest, warn, has_warn, state, has_ack, ack_at, by, prior) = row;
                if state != DeadlineState::Breached.as_str() {
                    return Err(StoreError::NotBreached {
                        case: key,
                        obligation: name,
                        state,
                    });
                }
                // The first account stands. A retry must not rewrite who looked
                // or when, for the reason an erasure's reason is not rewritable:
                // the record of who answered is the answer.
                if has_ack == 1 {
                    let _ = (ack_at, by, prior);
                    return Ok(false);
                }
                let (now_ack, ack_at, by, n) = ack_columns(Some(&note));
                d.insert(
                    (tenant.as_str(), key.as_str(), name.as_str()),
                    (
                        resolved,
                        digest.as_slice(),
                        warn,
                        has_warn,
                        state.as_str(),
                        now_ack,
                        ack_at,
                        by,
                        n,
                    ),
                )
                .map_err(|e| be(&e))?;
                drop(d);
                // Both ends through the same predicate. Spelling them as `true,
                // false` here would be the membership rule written a second
                // time, and the copy that drifts is whichever the listing does
                // not read.
                reindex_unaccounted(
                    &w,
                    &tenant,
                    &key,
                    &name,
                    resolved,
                    unaccounted(&state, has_ack),
                    unaccounted(&state, now_ack),
                )?;
                true
            };
            w.commit().map_err(|e| be(&e))?;
            Ok(recorded)
        })
        .await
    }

    async fn by_status(&self, status: CaseStatus, limit: usize) -> Result<Vec<Case>, StoreError> {
        let tenant = self.tenant_name();
        let s = status.as_str().to_owned();
        let ids = self
            .with_db(move |db| {
                let r = db.begin_read().map_err(|e| be(&e))?;
                let t = r.open_table(CASES_BY_STATUS).map_err(|e| be(&e))?;
                let mut out = Vec::new();
                for e in t
                    .range(
                        (tenant.as_str(), s.as_str(), i64::MIN, "")
                            ..=(tenant.as_str(), s.as_str(), i64::MAX, MAX_STR),
                    )
                    .map_err(|e| be(&e))?
                {
                    if out.len() >= limit {
                        break;
                    }
                    let (k, _) = e.map_err(|e| be(&e))?;
                    out.push(k.value().3.to_owned());
                }
                Ok(out)
            })
            .await?;

        let mut cases = Vec::with_capacity(ids.len());
        for id in ids {
            if let Some(c) = self.case(parse_case_id(&id)?).await? {
                cases.push(c);
            }
        }
        Ok(cases)
    }
}

/// Move a case between the status and open indexes.
///
/// Both are derived from the row being written, and both are updated in that
/// row's transaction — an index that disagreed with its row would make the
/// worklist show work that is not there.
fn reindex_status(
    w: &redb::WriteTransaction,
    tenant: &str,
    case: &str,
    was: &str,
    now: &str,
    opened_at: i64,
) -> Result<(), StoreError> {
    if was == now {
        return Ok(());
    }
    let mut by_status = w.open_table(CASES_BY_STATUS).map_err(|e| be(&e))?;
    by_status
        .remove((tenant, was, -opened_at, case))
        .map_err(|e| be(&e))?;
    by_status
        .insert((tenant, now, -opened_at, case), ())
        .map_err(|e| be(&e))?;

    let mut open = w.open_table(CASES_OPEN).map_err(|e| be(&e))?;
    let closed = CaseStatus::Closed.as_str();
    match (was == closed, now == closed) {
        (false, true) => {
            open.remove((tenant, opened_at, case)).map_err(|e| be(&e))?;
        }
        (true, false) => {
            open.insert((tenant, opened_at, case), ())
                .map_err(|e| be(&e))?;
        }
        _ => {}
    }
    Ok(())
}

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

    /// Every string this store writes is one it reads back as the same value.
    #[test]
    fn every_written_string_decodes_to_the_value_that_wrote_it() {
        for status in CaseStatus::ALL {
            assert_eq!(status_from(status.as_str()).expect("round trip"), status);
        }
        for state in DeadlineState::ALL {
            assert_eq!(
                deadline_state_from(state.as_str()).expect("round trip"),
                state
            );
        }
    }

    /// **A row this store cannot read is not a row with a default value.**
    #[test]
    fn an_unreadable_column_is_refused_rather_than_defaulted() {
        for (what, err) in [
            ("case status", status_from("Closed").err()),
            ("case status", status_from("").err()),
            ("deadline state", deadline_state_from("breach").err()),
        ] {
            assert!(
                matches!(err, Some(StoreError::Corrupt { .. })),
                "an unrecognised {what} decoded to a value instead of refusing"
            );
        }
    }

    /// An obligation whose state will not parse still blocks closure.
    ///
    /// `is_outstanding` reads the stored spelling, so it is the one predicate
    /// here that meets a damaged row before any decoder does. Fail-closed: a
    /// row that dropped out of the index because nobody could read it is an
    /// obligation this store forgot, and `close` would then admit a matter
    /// with an unmet duty — the one thing the whole case layer is built to
    /// refuse.
    #[test]
    fn an_unreadable_obligation_is_still_outstanding() {
        assert!(is_outstanding(DeadlineState::Pending.as_str()));
        assert!(is_outstanding(DeadlineState::Warned.as_str()));
        assert!(!is_outstanding(DeadlineState::Met.as_str()));
        assert!(!is_outstanding(DeadlineState::Breached.as_str()));
        assert!(!is_outstanding(DeadlineState::Cancelled.as_str()));
        assert!(
            is_outstanding("half a word"),
            "a state nobody can read must not silently leave the obligation index"
        );
    }
}