khive-db 0.20.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
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
//! Tests for `events_prune`. Every store here is a scratch file built by the test.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::time::Duration;

use rusqlite::{params, Connection};
use serde_json::{json, Value};
use uuid::Uuid;

use crate::events_prune::{
    self, ApplyOptions, KeyCount, PruneError, PruneTarget, EXPENDABLE_VERBS, HORIZON_SECONDS,
};

const EVENTS_DDL: &str = include_str!("../sql/events-ddl.sql");
const RUN_STARTED_US: i64 = 1_800_000_000_000_000;
const DAY_US: i64 = 86_400_000_000;
const CUTOFF_US: i64 = RUN_STARTED_US - HORIZON_SECONDS * 1_000_000;
const OLD_US: i64 = CUTOFF_US - DAY_US;

struct Fixture {
    _dir: tempfile::TempDir,
    root: PathBuf,
    events: PathBuf,
    main: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        let dir = tempfile::tempdir().expect("scratch directory");
        let root = dir.path().to_path_buf();
        let events = root.join("store.db.events.db");
        let main = root.join("store.db");
        let conn = Connection::open(&events).expect("events store");
        let mode: String = conn
            .query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))
            .expect("wal");
        assert_eq!(mode, "wal");
        conn.execute_batch(EVENTS_DDL).expect("events schema");
        let main_conn = Connection::open(&main).expect("main store");
        main_conn
            .execute_batch(
                "CREATE TABLE graph_edges (namespace TEXT NOT NULL, id TEXT PRIMARY KEY, source_id TEXT NOT NULL, \
                 target_id TEXT NOT NULL, relation TEXT NOT NULL, weight REAL NOT NULL DEFAULT 1.0, \
                 created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, deleted_at INTEGER, metadata TEXT, \
                 target_backend TEXT)",
            )
            .expect("edges table");
        Self {
            _dir: dir,
            root,
            events,
            main,
        }
    }

    fn target(&self) -> PruneTarget {
        PruneTarget {
            events_db: self.events.clone(),
            edge_dbs: vec![self.main.clone()],
        }
    }

    fn conn(&self) -> Connection {
        Connection::open(&self.events).expect("open events store")
    }

    /// Fold the WAL into the main file, so the file's bytes cover every committed row.
    fn checkpoint(&self) {
        let busy: i64 = self
            .conn()
            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| row.get(0))
            .expect("checkpoint");
        assert_eq!(busy, 0, "the checkpoint was blocked");
    }

    fn insert(
        &self,
        id: &str,
        kind: &str,
        verb: &str,
        created_at: i64,
        payload: &str,
        aggregate: bool,
    ) {
        self.conn()
            .execute(
                "INSERT INTO events (id, namespace, verb, substrate, actor, kind, outcome, payload, created_at, \
                 aggregate_kind, aggregate_id) VALUES (?1, 'local', ?2, 'event', 'lambda:test', ?3, 'success', ?4, ?5, ?6, ?7)",
                params![
                    id,
                    verb,
                    kind,
                    payload,
                    created_at,
                    aggregate.then_some("session"),
                    aggregate.then_some("s-1")
                ],
            )
            .expect("insert event");
    }

    /// A generic dispatch audit row; returns its id.
    fn generic(&self, verb: &str, created_at: i64) -> String {
        let id = Uuid::new_v4().hyphenated().to_string();
        self.insert(
            &id,
            "audit",
            verb,
            created_at,
            &envelope(verb, "allow").to_string(),
            false,
        );
        id
    }

    fn edge(&self, source: &str, target: &str, deleted: bool) {
        Connection::open(&self.main)
            .expect("main store")
            .execute(
                "INSERT INTO graph_edges (namespace, id, source_id, target_id, relation, created_at, updated_at, deleted_at) \
                 VALUES ('local', ?1, ?2, ?3, 'annotates', 1, 1, ?4)",
                params![Uuid::new_v4().to_string(), source, target, deleted.then_some(2_i64)],
            )
            .expect("insert edge");
    }

    fn ids(&self) -> BTreeSet<String> {
        let conn = self.conn();
        let mut stmt = conn.prepare("SELECT id FROM events").expect("prepare");
        let ids = stmt
            .query_map([], |row| row.get::<_, String>(0))
            .expect("query")
            .collect::<Result<_, _>>()
            .expect("rows");
        ids
    }

    /// Every row except the given ids, as text, ordered by id.
    fn rows_except(&self, skip: &BTreeSet<String>) -> Vec<String> {
        let conn = self.conn();
        let mut stmt = conn
            .prepare("SELECT id, namespace, verb, kind, outcome, payload, created_at, aggregate_kind FROM events ORDER BY id")
            .expect("prepare");
        let rows: Vec<(String, String)> = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    format!(
                        "{}|{}|{}|{}|{}|{}|{:?}",
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, String>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, String>(5)?,
                        row.get::<_, i64>(6)?,
                        row.get::<_, Option<String>>(7)?
                    ),
                ))
            })
            .expect("query")
            .collect::<Result<_, _>>()
            .expect("rows");
        rows.into_iter()
            .filter(|(id, _)| !skip.contains(id))
            .map(|(id, row)| format!("{id}|{row}"))
            .collect()
    }

    fn backup(&self, plan: &events_prune::Plan, name: &str) -> PathBuf {
        let dest = self.root.join(name);
        events_prune::backup(&self.target(), plan, &dest).expect("backup");
        events_prune::receipt_path(&dest)
    }

    fn options(&self, digest: &str, receipt: PathBuf, state: &str) -> ApplyOptions {
        ApplyOptions {
            digest: digest.to_string(),
            cutoff_us: CUTOFF_US,
            backup_receipt: receipt,
            state_dir: self.root.join(state),
            batch_rows: 2,
            pause: Duration::ZERO,
            busy_timeout: Duration::from_millis(200),
            max_batches: None,
        }
    }
}

fn envelope(verb: &str, decision: &str) -> Value {
    json!({
        "timestamp": "2026-01-01T00:00:00Z",
        "actor": {"kind": "lambda", "id": "test"},
        "namespace": "local",
        "verb": verb,
        "decision": decision,
        "obligations": [],
        "gate_impl": "allow_all"
    })
}

fn plan(fixture: &Fixture) -> events_prune::Plan {
    events_prune::plan_at(&fixture.target(), RUN_STARTED_US, CUTOFF_US).expect("plan")
}

fn schema_sql(path: &Path) -> Vec<String> {
    let conn = Connection::open(path).expect("open");
    let mut stmt = conn
        .prepare("SELECT type || ' ' || name || ' ' || IFNULL(sql, '') FROM sqlite_master ORDER BY type, name")
        .expect("prepare");
    let rows = stmt
        .query_map([], |row| row.get::<_, String>(0))
        .expect("query")
        .collect::<Result<_, _>>()
        .expect("rows");
    rows
}

#[test]
fn each_of_the_six_verbs_is_selected() {
    let fixture = Fixture::new();
    let ids: BTreeSet<String> = EXPENDABLE_VERBS
        .iter()
        .map(|verb| fixture.generic(verb, OLD_US))
        .collect();
    let plan = plan(&fixture);
    assert_eq!(plan.candidates, 6);
    for verb in EXPENDABLE_VERBS {
        assert_eq!(plan.candidates_by_verb_and_age[verb]["7-14d"], 1, "{verb}");
    }
    let selected: BTreeSet<String> = plan
        .selected
        .iter()
        .map(|c| c.id.hyphenated().to_string())
        .collect();
    assert_eq!(selected, ids);
    assert!(
        plan.retained_by_reason.is_empty(),
        "{:?}",
        plan.retained_by_reason
    );
}

#[test]
fn every_excluded_shape_is_retained_with_its_reason() {
    let fixture = Fixture::new();
    let keep = fixture.generic("comm.inbox", OLD_US);
    // Outside the class altogether: a seventh verb, and an allowlisted verb under another kind.
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "knowledge.get",
        OLD_US,
        &envelope("knowledge.get", "allow").to_string(),
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "phase_started",
        "comm.inbox",
        OLD_US,
        &envelope("comm.inbox", "allow").to_string(),
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "channel.poll_lifecycle",
        OLD_US,
        &envelope("channel.poll_lifecycle", "allow").to_string(),
        false,
    );
    // At exactly the cutoff, and one microsecond before it.
    fixture.generic("whoami", CUTOFF_US);
    let just_old = fixture.generic("whoami", CUTOFF_US - 1);
    // Non-generic envelopes.
    let mut no_gate = envelope("comm.probe", "allow");
    no_gate.as_object_mut().unwrap().remove("gate_impl");
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.probe",
        OLD_US,
        &no_gate.to_string(),
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.probe",
        OLD_US,
        &envelope("comm.probe", "maybe").to_string(),
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.probe",
        OLD_US,
        &envelope("comm.inbox", "allow").to_string(),
        false,
    );
    // Aggregate identity, a payload that is not an object, a non-canonical id. The events schema indexes
    // json_extract(payload, ...), so SQLite refuses unparseable text at insert; valid non-object JSON is
    // the malformed shape a store with this schema can hold.
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.heartbeat",
        OLD_US,
        &envelope("comm.heartbeat", "allow").to_string(),
        true,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.heartbeat",
        OLD_US,
        r#"["not an object"]"#,
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string().to_uppercase(),
        "audit",
        "comm.heartbeat",
        OLD_US,
        &envelope("comm.heartbeat", "allow").to_string(),
        false,
    );
    // Retention stamps: the producer's exact one is selected, any other retains.
    let mut stamped = envelope("comm.cursor_get", "deny");
    stamped["retention"] =
        json!({"class": "expendable", "policy": "poll-dispatch-v1", "horizon_seconds": 604800});
    let stamped_id = Uuid::new_v4().to_string();
    fixture.insert(
        &stamped_id,
        "audit",
        "comm.cursor_get",
        OLD_US,
        &stamped.to_string(),
        false,
    );
    let mut other_stamp = envelope("comm.cursor_get", "allow");
    other_stamp["retention"] =
        json!({"class": "expendable", "policy": "poll-dispatch-v2", "horizon_seconds": 604800});
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "comm.cursor_get",
        OLD_US,
        &other_stamp.to_string(),
        false,
    );
    // A sampled row (ADR-103 Amendment 7) is still a generic envelope.
    let mut sampled = envelope("comm.cleanup_expired_quarantine", "gate_unavailable");
    sampled["resource"] = json!({"sampling": {"rate": 0.01, "forced": false}});
    let sampled_id = Uuid::new_v4().to_string();
    fixture.insert(
        &sampled_id,
        "audit",
        "comm.cleanup_expired_quarantine",
        OLD_US,
        &sampled.to_string(),
        false,
    );
    // Observations, and edges: live, soft-deleted, and naming the id in upper case.
    let observed = fixture.generic("comm.inbox", OLD_US);
    fixture
        .conn()
        .execute(
            "INSERT INTO event_observations (event_id, entity_id, referent_kind, role, position) VALUES (?1, 'e', 'entity', 'target', 0)",
            [&observed],
        )
        .expect("observation");
    let live_edge = fixture.generic("comm.inbox", OLD_US);
    fixture.edge(&live_edge, &Uuid::new_v4().to_string(), false);
    let deleted_edge = fixture.generic("comm.inbox", OLD_US);
    fixture.edge(&Uuid::new_v4().to_string(), &deleted_edge, true);
    let upper_edge = fixture.generic("comm.inbox", OLD_US);
    fixture.edge(
        &upper_edge.to_uppercase(),
        &Uuid::new_v4().to_string(),
        false,
    );

    let plan = plan(&fixture);
    let selected: BTreeSet<String> = plan
        .selected
        .iter()
        .map(|c| c.id.hyphenated().to_string())
        .collect();
    let expected: BTreeSet<String> = [keep, just_old, stamped_id, sampled_id]
        .into_iter()
        .collect();
    assert_eq!(selected, expected);
    let retained: Vec<(&str, u64)> = plan
        .retained_by_reason
        .iter()
        .map(|(k, v)| (k.as_str(), *v))
        .collect();
    assert_eq!(
        retained,
        vec![
            ("aggregate", 1),
            ("edge_referenced", 3),
            ("malformed", 2),
            ("non_generic_envelope", 3),
            ("observations_present", 1),
            ("retention_stamp_mismatch", 1),
            ("younger", 1),
        ]
    );
    assert_eq!(plan.protected_backlog, 11);
    let keys: Vec<(&str, &str)> = plan
        .non_candidate_keys
        .iter()
        .map(|k| (k.kind.as_str(), k.verb.as_str()))
        .collect();
    assert_eq!(
        keys,
        vec![
            ("audit", "channel.poll_lifecycle"),
            ("audit", "knowledge.get"),
            ("phase_started", "comm.inbox")
        ]
    );
}

#[test]
fn the_digest_ignores_order_and_duplicates_and_matches_canonical_json() {
    let ids: Vec<Uuid> = (0..20).map(|_| Uuid::new_v4()).collect();
    let mut shuffled = ids.clone();
    shuffled.reverse();
    shuffled.extend(ids.iter().take(5).copied());
    assert_eq!(
        events_prune::candidate_digest(ids.clone()),
        events_prune::candidate_digest(shuffled)
    );
    let mut strings: Vec<String> = ids.iter().map(|id| id.hyphenated().to_string()).collect();
    strings.sort();
    let canonical = khive_types::canonical_json_bytes(&json!(strings)).expect("canonical json");
    assert_eq!(
        events_prune::candidate_digest(ids),
        blake3::hash(&canonical).to_hex().to_string()
    );
    assert_eq!(
        events_prune::candidate_digest(Vec::new()),
        blake3::hash(b"[]").to_hex().to_string()
    );
}

#[test]
fn a_dry_run_changes_no_byte_of_either_store() {
    let fixture = Fixture::new();
    fixture.generic("comm.inbox", OLD_US);
    fixture.checkpoint();
    let before = (
        std::fs::read(&fixture.events).unwrap(),
        std::fs::read(&fixture.main).unwrap(),
    );
    let plan = plan(&fixture);
    assert_eq!(plan.candidates, 1);
    let after = (
        std::fs::read(&fixture.events).unwrap(),
        std::fs::read(&fixture.main).unwrap(),
    );
    assert!(before == after, "a dry run changed a store");
}

#[test]
fn an_unknown_events_schema_is_refused_and_left_unchanged() {
    let fixture = Fixture::new();
    fixture
        .conn()
        .execute_batch("ALTER TABLE events ADD COLUMN future TEXT")
        .expect("alter");
    fixture.checkpoint();
    let before = std::fs::read(&fixture.events).unwrap();
    let error = events_prune::plan_at(&fixture.target(), RUN_STARTED_US, CUTOFF_US).unwrap_err();
    assert!(matches!(error, PruneError::Schema(_)), "{error}");
    assert_eq!(error.exit_code(), 3);
    assert_eq!(std::fs::read(&fixture.events).unwrap(), before);
}

#[test]
fn a_cutoff_later_than_the_horizon_is_refused() {
    let fixture = Fixture::new();
    let error =
        events_prune::plan_at(&fixture.target(), RUN_STARTED_US, CUTOFF_US + 1).unwrap_err();
    assert!(matches!(error, PruneError::Invalid(_)), "{error}");
}

#[test]
fn apply_removes_exactly_the_candidates_and_leaves_every_other_row_identical() {
    let fixture = Fixture::new();
    let candidates: BTreeSet<String> = (0..5)
        .map(|i| fixture.generic(EXPENDABLE_VERBS[i % 6], OLD_US - i as i64))
        .collect();
    fixture.generic("comm.inbox", CUTOFF_US);
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "knowledge.get",
        OLD_US,
        &envelope("knowledge.get", "allow").to_string(),
        false,
    );
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "feedback_explicit",
        "brain.feedback",
        OLD_US,
        "{}",
        false,
    );
    let referenced = fixture.generic("comm.inbox", OLD_US);
    fixture.edge(&referenced, &Uuid::new_v4().to_string(), false);
    let others_before = fixture.rows_except(&candidates);
    let schema_before = (schema_sql(&fixture.events), schema_sql(&fixture.main));

    let plan = plan(&fixture);
    assert_eq!(plan.candidates, 5);
    let receipt = fixture.backup(&plan, "backup.db");
    let report = events_prune::apply_at(
        &fixture.target(),
        &fixture.options(&plan.digest, receipt, "state"),
        RUN_STARTED_US + 1,
    )
    .expect("apply");
    assert_eq!(report.removed, 5);
    assert_eq!(report.batches, 3);
    assert_eq!(fixture.rows_except(&BTreeSet::new()), others_before);
    assert!(fixture.ids().is_disjoint(&candidates));
    assert_eq!(report.controls_before, report.controls_after);
    assert_eq!(report.candidate_key_rows_before_cutoff, [6, 1]);
    assert_eq!(
        (schema_sql(&fixture.events), schema_sql(&fixture.main)),
        schema_before
    );
    let ledger = std::fs::read_to_string(&report.expended_ids_file).expect("ledger");
    assert_eq!(
        ledger
            .lines()
            .filter(|l| l.contains("\"type\":\"intent\""))
            .count(),
        3
    );
    assert_eq!(
        ledger
            .lines()
            .filter(|l| l.contains("\"type\":\"commit\""))
            .count(),
        3
    );
    for id in &candidates {
        assert!(ledger.contains(id.as_str()), "{id} missing from the ledger");
    }
    // The backup still holds every removed row.
    let copy = Connection::open(fixture.root.join("backup.db")).expect("backup copy");
    let in_copy: i64 = copy
        .query_row("SELECT COUNT(*) FROM events", [], |row| row.get(0))
        .unwrap();
    assert_eq!(in_copy, 9);
}

#[test]
fn apply_without_a_backup_refuses_before_any_write() {
    let fixture = Fixture::new();
    fixture.generic("comm.inbox", OLD_US);
    let plan = plan(&fixture);
    let before = fixture.ids();
    let error = events_prune::apply_at(
        &fixture.target(),
        &fixture.options(
            &plan.digest,
            fixture.root.join("absent.receipt.json"),
            "state",
        ),
        RUN_STARTED_US + 1,
    )
    .unwrap_err();
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
    assert_eq!(error.exit_code(), 5);
    assert_eq!(fixture.ids(), before);
    // A receipt for another digest is no backup for this one.
    let receipt = fixture.backup(&plan, "backup.db");
    let error = events_prune::apply_at(
        &fixture.target(),
        &fixture.options(&"0".repeat(64), receipt, "state2"),
        RUN_STARTED_US + 1,
    )
    .unwrap_err();
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
    assert_eq!(fixture.ids(), before);
}

/// The same file named relative to the process's working directory, so resolving it depends on where the
/// process runs, as a path given on the command line would.
fn relative_to_cwd(path: &Path) -> PathBuf {
    let cwd = std::env::current_dir().expect("working directory");
    let absolute = std::fs::canonicalize(path).expect("canonical path");
    let mut relative = PathBuf::new();
    for _ in cwd.components().skip(1) {
        relative.push("..");
    }
    relative.push(absolute.strip_prefix("/").expect("absolute path"));
    assert!(relative.is_relative());
    relative
}

#[test]
fn a_backup_taken_through_a_relative_path_records_the_absolute_source() {
    let fixture = Fixture::new();
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "audit",
        "whoami",
        OLD_US,
        &envelope("whoami", "allow").to_string(),
        false,
    );
    let plan = plan(&fixture);
    let target = PruneTarget {
        events_db: relative_to_cwd(&fixture.events),
        edge_dbs: vec![fixture.main.clone()],
    };
    let dest = fixture.root.join("relative-backup.db");
    let receipt = events_prune::backup(&target, &plan, &dest).expect("backup");
    assert!(receipt.source.is_absolute(), "{}", receipt.source.display());
    assert_eq!(
        receipt.source,
        std::fs::canonicalize(&fixture.events).unwrap()
    );
}

#[test]
fn a_receipt_with_a_relative_source_refuses_before_any_apply_mutation() {
    let fixture = Fixture::new();
    for verb in ["comm.inbox", "whoami"] {
        fixture.insert(
            &Uuid::new_v4().to_string(),
            "audit",
            verb,
            OLD_US,
            &envelope(verb, "allow").to_string(),
            false,
        );
    }
    let plan = plan(&fixture);
    let receipt_file = fixture.backup(&plan, "backup.db");
    let mut stored: Value = serde_json::from_slice(&std::fs::read(&receipt_file).unwrap()).unwrap();
    // A receipt written before sources were recorded absolute: the path still resolves to this very store
    // from the test's working directory, so only the relative form itself can refuse it.
    stored["source"] = json!(relative_to_cwd(&fixture.events));
    std::fs::write(&receipt_file, serde_json::to_vec(&stored).unwrap()).unwrap();
    fixture.checkpoint();
    let before = (
        std::fs::read(&fixture.events).unwrap(),
        fixture.rows_except(&BTreeSet::new()),
    );
    let options = fixture.options(&plan.digest, receipt_file, "relative-state");
    let error = events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 1)
        .expect_err("a relative receipt source must refuse");
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
    assert!(error.to_string().contains("relative path"), "{error}");
    assert!(
        !options.state_dir.exists(),
        "refusal must not create apply state"
    );
    assert_eq!(std::fs::read(&fixture.events).unwrap(), before.0);
    assert_eq!(fixture.rows_except(&BTreeSet::new()), before.1);
}

#[test]
fn a_backup_of_another_store_refuses_before_any_apply_mutation() {
    let source = Fixture::new();
    let other = Fixture::new();
    let mut candidates = BTreeSet::new();
    for verb in ["comm.inbox", "whoami", "knowledge.get"] {
        let id = Uuid::new_v4().to_string();
        for fixture in [&source, &other] {
            fixture.insert(
                &id,
                "audit",
                verb,
                OLD_US,
                &envelope(verb, "allow").to_string(),
                false,
            );
        }
        if verb != "knowledge.get" {
            candidates.insert(id);
        }
    }
    let source_plan = plan(&source);
    let other_plan = plan(&other);
    assert_eq!(source_plan.candidates, 2);
    assert_eq!(source_plan.selected, other_plan.selected);
    assert_eq!(source_plan.digest, other_plan.digest);
    assert_eq!(source_plan.cutoff_us, other_plan.cutoff_us);
    let receipt = source.backup(&source_plan, "backup.db");
    let options = other.options(&other_plan.digest, receipt.clone(), "wrong-store-state");
    let snapshots: Vec<_> = [&source, &other]
        .into_iter()
        .map(|fixture| {
            fixture.checkpoint();
            (
                std::fs::read(&fixture.events).unwrap(),
                std::fs::read(&fixture.main).unwrap(),
                fixture.rows_except(&BTreeSet::new()),
            )
        })
        .collect();
    let error = events_prune::apply_at(&other.target(), &options, RUN_STARTED_US + 1)
        .expect_err("matching candidates cannot authorize a backup of another store");
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
    assert_eq!(error.exit_code(), 5);
    let message = error.to_string();
    for path in [&source.events, &other.events] {
        assert!(message.contains(path.to_str().unwrap()), "{message}");
    }
    assert!(
        !options.state_dir.exists(),
        "refusal must not create apply state"
    );
    for (fixture, (events, main, rows)) in [&source, &other].into_iter().zip(snapshots) {
        assert_eq!(std::fs::read(&fixture.events).unwrap(), events);
        assert_eq!(std::fs::read(&fixture.main).unwrap(), main);
        assert_eq!(fixture.rows_except(&BTreeSet::new()), rows);
    }

    let retained = source.rows_except(&candidates);
    let report = events_prune::apply_at(
        &source.target(),
        &source.options(&source_plan.digest, receipt, "source-state"),
        RUN_STARTED_US + 1,
    )
    .expect("the same verified receipt must authorize its own source");
    assert_eq!(report.removed, 2);
    assert_eq!(source.rows_except(&BTreeSet::new()), retained);
    assert_eq!(
        other.ids().len(),
        3,
        "applying the source cannot prune the other store"
    );
}

#[test]
fn receipt_source_and_apply_target_accept_canonical_path_aliases() {
    for alias_is_source in [false, true] {
        let fixture = Fixture::new();
        fixture.generic("comm.inbox", OLD_US);
        let plan = plan(&fixture);
        let child = fixture.root.join("path-alias");
        std::fs::create_dir(&child).unwrap();
        let alias = child.join("..").join(fixture.events.file_name().unwrap());
        assert_ne!(alias, fixture.events, "the spellings must actually differ");
        assert_eq!(
            alias.canonicalize().unwrap(),
            fixture.events.canonicalize().unwrap()
        );
        let mut backup_target = fixture.target();
        let mut apply_target = fixture.target();
        if alias_is_source {
            backup_target.events_db = alias;
        } else {
            apply_target.events_db = alias;
        }
        let backup = fixture.root.join("backup.db");
        let receipt = events_prune::backup(&backup_target, &plan, &backup).unwrap();
        assert_eq!(
            receipt.source,
            backup_target.events_db.canonicalize().unwrap()
        );
        let report = events_prune::apply_at(
            &apply_target,
            &fixture.options(&plan.digest, events_prune::receipt_path(&backup), "state"),
            RUN_STARTED_US + 1,
        )
        .expect("either supplied path may canonically name the backed-up source");
        assert_eq!(report.removed, 1);
        assert!(fixture.ids().is_empty());
    }
}

#[test]
fn an_unresolvable_receipt_source_refuses_before_any_apply_mutation() {
    let fixture = Fixture::new();
    fixture.generic("comm.inbox", OLD_US);
    let plan = plan(&fixture);
    let receipt_path = fixture.backup(&plan, "backup.db");
    let mut receipt: events_prune::BackupReceipt =
        serde_json::from_slice(&std::fs::read(&receipt_path).unwrap()).unwrap();
    receipt.source = fixture.root.join("missing-events.db");
    std::fs::write(&receipt_path, serde_json::to_vec(&receipt).unwrap()).unwrap();
    let options = fixture.options(&plan.digest, receipt_path, "state");
    fixture.checkpoint();
    let before = std::fs::read(&fixture.events).unwrap();
    let rows = fixture.rows_except(&BTreeSet::new());
    let error = events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 1)
        .expect_err("a receipt source must resolve before apply");
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
    assert_eq!(error.exit_code(), 5);
    let message = error.to_string();
    for path in [&receipt.source, &fixture.events] {
        assert!(message.contains(path.to_str().unwrap()), "{message}");
    }
    assert_eq!(std::fs::read(&fixture.events).unwrap(), before);
    assert_eq!(fixture.rows_except(&BTreeSet::new()), rows);
    assert!(!options.state_dir.exists());
    assert!(!receipt.source.exists());
}

#[test]
fn a_changed_candidate_set_refuses_with_a_digest_mismatch_before_any_write() {
    let fixture = Fixture::new();
    let first = fixture.generic("comm.inbox", OLD_US);
    fixture.generic("whoami", OLD_US);
    let plan = plan(&fixture);
    let receipt = fixture.backup(&plan, "backup.db");
    fixture.edge(&first, &Uuid::new_v4().to_string(), false);
    let before = fixture.ids();
    let error = events_prune::apply_at(
        &fixture.target(),
        &fixture.options(&plan.digest, receipt, "state"),
        RUN_STARTED_US + 1,
    )
    .unwrap_err();
    assert!(
        matches!(error, PruneError::DigestMismatch { .. }),
        "{error}"
    );
    assert_eq!(error.exit_code(), 4);
    assert_eq!(fixture.ids(), before);
}

#[test]
fn an_interrupted_apply_resumes_to_the_same_removed_set() {
    let build = || {
        let fixture = Fixture::new();
        for i in 0..7 {
            let id = format!("00000000-0000-4000-8000-00000000000{i}");
            fixture.insert(
                &id,
                "audit",
                "comm.probe",
                OLD_US - i,
                &envelope("comm.probe", "allow").to_string(),
                false,
            );
        }
        let survivor = "00000000-0000-4000-8000-0000000000ff";
        fixture.insert(
            survivor,
            "audit",
            "comm.probe",
            CUTOFF_US,
            &envelope("comm.probe", "allow").to_string(),
            false,
        );
        fixture
    };
    let whole = build();
    let plan_whole = plan(&whole);
    let receipt = whole.backup(&plan_whole, "backup.db");
    events_prune::apply_at(
        &whole.target(),
        &whole.options(&plan_whole.digest, receipt, "state"),
        RUN_STARTED_US + 1,
    )
    .expect("uninterrupted apply");

    let parts = build();
    let plan_parts = plan(&parts);
    assert_eq!(plan_parts.digest, plan_whole.digest);
    let receipt = parts.backup(&plan_parts, "backup.db");
    let mut options = parts.options(&plan_parts.digest, receipt, "state");
    options.max_batches = Some(1);
    let error = events_prune::apply_at(&parts.target(), &options, RUN_STARTED_US + 1).unwrap_err();
    assert!(matches!(error, PruneError::Interrupted(_)), "{error}");
    assert_eq!(error.exit_code(), 7);
    assert_eq!(parts.ids().len(), 6);

    // A run killed after its delete committed and before its commit line: the intent line is all that remains.
    let next: Vec<String> = (2..4)
        .map(|i| format!("00000000-0000-4000-8000-00000000000{}", 6 - i))
        .collect();
    let ledger = options.state_dir.join("expended-ids.ndjson");
    let intent = json!({
        "type": "intent",
        "digest": plan_parts.digest,
        "batch": 2,
        "ids": next.iter().map(|id| json!({"id": id, "verb": "comm.probe", "namespace": "local", "created_at": 0})).collect::<Vec<_>>()
    });
    let mut text = std::fs::read_to_string(&ledger).unwrap();
    text.push_str(&format!("{intent}\n"));
    std::fs::write(&ledger, text).unwrap();
    for id in &next {
        parts
            .conn()
            .execute("DELETE FROM events WHERE id = ?1", [id])
            .unwrap();
    }

    options.max_batches = None;
    let report = events_prune::apply_at(&parts.target(), &options, RUN_STARTED_US + 2)
        .expect("resumed apply");
    assert_eq!(report.reconciled, 2);
    assert_eq!(report.removed_total, 7);
    assert_eq!(parts.ids(), whole.ids());
}

#[test]
fn a_row_an_edge_names_after_selection_survives_its_batch() {
    let fixture = Fixture::new();
    let a = fixture.generic("comm.inbox", OLD_US);
    let b = fixture.generic("comm.inbox", OLD_US);
    let ids: Vec<events_prune::LedgerId> = [&a, &b]
        .iter()
        .map(|id| events_prune::LedgerId {
            id: (*id).clone(),
            verb: "comm.inbox".into(),
            namespace: "local".into(),
            created_at: OLD_US,
        })
        .collect();
    let edges: std::collections::HashSet<Uuid> =
        [Uuid::parse_str(&b).unwrap()].into_iter().collect();
    let conn = fixture.conn();
    conn.execute_batch("BEGIN IMMEDIATE").unwrap();
    let (removed, skipped) =
        events_prune::delete_batch(&conn, &ids, CUTOFF_US, &edges).expect("batch");
    conn.execute_batch("COMMIT").unwrap();
    assert_eq!(removed, vec![a]);
    assert_eq!(skipped, vec![(b.clone(), "edge_referenced".to_string())]);
    assert!(fixture.ids().contains(&b));
}

fn append_ledger(state_dir: &Path, lines: &[Value]) {
    let path = state_dir.join("expended-ids.ndjson");
    let mut text = std::fs::read_to_string(&path).expect("ledger");
    for line in lines {
        text.push_str(&format!("{line}\n"));
    }
    std::fs::write(&path, text).expect("write ledger");
}

fn ledger_ids(ids: &[&String]) -> Vec<Value> {
    ids.iter()
        .map(|id| json!({"id": id, "verb": "comm.probe", "namespace": "local", "created_at": 0}))
        .collect()
}

/// Four candidates, one committed batch of two, then an interruption. Returns the fixture, the options and the two
/// candidates still present.
fn interrupted_after_one_batch() -> (Fixture, ApplyOptions, events_prune::Plan, Vec<String>) {
    let fixture = Fixture::new();
    let ids: Vec<String> = (0..4)
        .map(|i| fixture.generic("comm.probe", OLD_US - i))
        .collect();
    let plan = plan(&fixture);
    assert_eq!(plan.candidates, 4);
    let receipt = fixture.backup(&plan, "backup.db");
    let mut options = fixture.options(&plan.digest, receipt, "state");
    options.max_batches = Some(1);
    let error =
        events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 1).unwrap_err();
    assert!(matches!(error, PruneError::Interrupted(_)), "{error}");
    let present = fixture.ids();
    let left: Vec<String> = ids.into_iter().filter(|id| present.contains(id)).collect();
    assert_eq!(left.len(), 2);
    options.max_batches = None;
    (fixture, options, plan, left)
}

#[test]
fn a_resume_after_a_skipped_row_keeps_the_authorized_digest() {
    let (fixture, options, plan, left) = interrupted_after_one_batch();
    let (gone, kept) = (&left[0], &left[1]);
    // A second invocation's batch removed one row and skipped the other, which an edge named after selection.
    fixture.edge(kept, &Uuid::new_v4().to_string(), false);
    fixture
        .conn()
        .execute("DELETE FROM events WHERE id = ?1", [gone])
        .unwrap();
    append_ledger(
        &options.state_dir,
        &[
            json!({"type": "intent", "digest": plan.digest, "batch": 2, "ids": ledger_ids(&[gone, kept])}),
            json!({"type": "commit", "digest": plan.digest, "batch": 2, "removed": [gone],
                   "skipped": [[kept, "edge_referenced"]], "at_us": 0}),
        ],
    );

    let report = events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 2)
        .expect("a resume after a skip continues");
    assert_eq!(report.removed, 0);
    assert_eq!(
        report.removed_total, 3,
        "the skipped row is not counted as removed"
    );
    assert_eq!(fixture.ids(), [kept.clone()].into_iter().collect());
}

#[test]
fn a_resume_after_a_killed_batch_whose_row_gained_an_edge_keeps_the_authorized_digest() {
    let (fixture, options, plan, left) = interrupted_after_one_batch();
    let (still, named) = (&left[0], &left[1]);
    // A batch was killed before its delete committed, and an edge named one of its rows before the next start.
    append_ledger(
        &options.state_dir,
        &[
            json!({"type": "intent", "digest": plan.digest, "batch": 2, "ids": ledger_ids(&[still, named])}),
        ],
    );
    fixture.edge(named, &Uuid::new_v4().to_string(), false);

    let report = events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 2)
        .expect("a resume after a killed batch continues");
    assert_eq!(report.reconciled, 0, "both rows were still present");
    assert_eq!(report.removed, 1);
    assert_eq!(report.removed_total, 3);
    assert_eq!(fixture.ids(), [named.clone()].into_iter().collect());
}

#[test]
fn a_resume_refuses_when_a_new_row_joins_the_selection() {
    let (fixture, options, _plan, _left) = interrupted_after_one_batch();
    fixture.generic("comm.probe", OLD_US);
    let before = fixture.ids();
    let error =
        events_prune::apply_at(&fixture.target(), &options, RUN_STARTED_US + 2).unwrap_err();
    assert!(
        matches!(error, PruneError::DigestMismatch { .. }),
        "{error}"
    );
    assert_eq!(error.exit_code(), 4);
    assert_eq!(fixture.ids(), before);
}

#[test]
fn a_falling_control_count_stops_the_run() {
    let key = |rows_before_cutoff, rows| KeyCount {
        kind: "feedback_explicit".into(),
        verb: "brain.feedback".into(),
        rows_before_cutoff,
        rows,
    };
    assert!(events_prune::check_controls(&[key(3, 5)], &[key(3, 6)], [10, 8], 2).is_ok());
    let error = events_prune::check_controls(&[key(3, 5)], &[key(2, 5)], [10, 8], 2).unwrap_err();
    assert_eq!(error.exit_code(), 6);
    assert!(events_prune::check_controls(&[key(3, 5)], &[], [10, 8], 2).is_err());
    assert!(events_prune::check_controls(&[key(3, 5)], &[key(3, 5)], [10, 9], 2).is_err());
}

#[test]
fn a_backup_is_verified_and_never_overwrites() {
    let fixture = Fixture::new();
    fixture.generic("comm.inbox", OLD_US);
    fixture.insert(
        &Uuid::new_v4().to_string(),
        "feedback_explicit",
        "brain.feedback",
        OLD_US,
        "{}",
        false,
    );
    let plan = plan(&fixture);
    let dest = fixture.root.join("backup.db");
    let receipt = events_prune::backup(&fixture.target(), &plan, &dest).expect("backup");
    assert_eq!(receipt.integrity, vec!["ok".to_string()]);
    assert_eq!(receipt.digest, plan.digest);
    assert_eq!(receipt.rows_by_kind.values().sum::<u64>(), 2);
    assert_eq!(receipt.bytes, std::fs::metadata(&dest).unwrap().len());
    assert!(
        !fixture.root.join("backup.db-wal").exists(),
        "the copy is one self-contained file"
    );
    let error = events_prune::backup(&fixture.target(), &plan, &dest).unwrap_err();
    assert!(matches!(error, PruneError::Invalid(_)), "{error}");
    // A copy that no longer matches its receipt is no backup.
    std::fs::write(&dest, b"changed").unwrap();
    let error = events_prune::apply_at(
        &fixture.target(),
        &fixture.options(&plan.digest, events_prune::receipt_path(&dest), "state"),
        RUN_STARTED_US + 1,
    )
    .unwrap_err();
    assert!(matches!(error, PruneError::NoBackup(_)), "{error}");
}