macrame-db 0.15.0

A Bitemporal Graph Ledger on libSQL · Embedded knowledge database
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
use thiserror::Error;

/// The two intervals of a [`DbError::OverlappingInterval`], boxed out of the
/// error enum (D-075).
///
/// Both are reported because neither alone identifies the conflict: the caller
/// knows what they asserted and not what it collided with, and a message naming
/// only the other interval reads as though the assertion were the innocent one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Overlap {
    pub source_id: String,
    pub target_id: String,
    pub edge_type: String,
    /// The interval the caller asserted.
    pub valid_from: String,
    pub valid_to: String,
    /// The interval it collides with — see [`Overlap::within_batch`] for where
    /// that one is, because it is not always in the database.
    pub existing_from: String,
    pub existing_to: String,
    /// Whether the collision is with another edge in the *same call* (0.13.7,
    /// D-180).
    ///
    /// Two guards raise this one error. `reject_overlapping_interval` compares
    /// the assertion against committed rows; `reject_overlaps_within` compares
    /// a batch against itself, before the transaction opens, and nothing it
    /// names is in the database — the batch is refused whole, so nothing it
    /// names ever will be. A caller told an edge "already holds" an interval
    /// goes looking for a row that is not there.
    pub within_batch: bool,
}

impl Overlap {
    /// The message's closing clause: where the second interval came from.
    ///
    /// A method rather than two `#[error]` strings, because one variant gets
    /// one format string, and rather than a `String` because this is on a
    /// `Display` path.
    pub fn provenance(&self) -> &'static str {
        if self.within_batch {
            "this same batch also asserts"
        } else {
            "is already recorded"
        }
    }
}

/// Which instants a traversal stated, for the one error that has to name them
/// (0.13.10, W7.7, D-183).
///
/// Three cases and never zero. [`DbError::AttributeModeUnstated`] exists
/// *because* an instant was set, so a fourth case carrying neither would be a
/// state no construction site can reach — [D-177]'s objection to a `Result`
/// that cannot fail, in a different shape. [`Self::new`] returns an `Option`
/// and the `None` is the ordinary live traversal, resolved before any error
/// exists.
///
/// [D-177]: ../docs/architecture/s13-decision-register.md#d-177
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StatedInstants {
    /// `as_of_valid` alone — *what was true then*.
    Valid(String),
    /// `as_of_recorded` alone — *what we believed then*.
    Recorded(String),
    /// Both, which is the bitemporal cell: *what did we believe at `recorded`
    /// about what was true at `valid`*.
    Both {
        /// The valid-time instant.
        valid: String,
        /// The transaction-time instant.
        recorded: String,
    },
}

impl StatedInstants {
    /// `None` when neither axis was set, which is not an error and not this
    /// type's business to describe.
    pub fn new(valid: Option<&str>, recorded: Option<&str>) -> Option<Self> {
        match (valid, recorded) {
            (Some(v), Some(r)) => Some(Self::Both {
                valid: v.to_string(),
                recorded: r.to_string(),
            }),
            (Some(v), None) => Some(Self::Valid(v.to_string())),
            (None, Some(r)) => Some(Self::Recorded(r.to_string())),
            (None, None) => None,
        }
    }

    /// The valid-time instant, if this traversal stated one.
    pub fn valid(&self) -> Option<&str> {
        match self {
            Self::Valid(v) | Self::Both { valid: v, .. } => Some(v),
            Self::Recorded(_) => None,
        }
    }

    /// The transaction-time instant, if this traversal stated one.
    pub fn recorded(&self) -> Option<&str> {
        match self {
            Self::Recorded(r) | Self::Both { recorded: r, .. } => Some(r),
            Self::Valid(_) => None,
        }
    }
}

/// Rendered as the **calls that produce them**, which is the whole point.
///
/// A message reading `as_of(2020-06-01)` names a method that has not existed
/// since 0.12.17 ([D-174](../docs/architecture/s13-decision-register.md#d-174)),
/// so a caller who goes looking for it finds nothing — and, worse, is not told
/// which of the two axes the instant they set landed on. `as_of_valid(…)` and
/// `as_of_recorded(…)` are what a caller typed and what a caller can change.
impl std::fmt::Display for StatedInstants {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Valid(v) => write!(f, "as_of_valid({v})"),
            Self::Recorded(r) => write!(f, "as_of_recorded({r})"),
            Self::Both { valid, recorded } => {
                write!(f, "as_of_valid({valid}) with as_of_recorded({recorded})")
            }
        }
    }
}

/// Central error type for the Macrame bitemporal ledger database.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum DbError {
    #[error("engine: {0}")]
    Engine(#[from] libsql::Error),

    #[error("migration to v{to} failed: {reason}")]
    Migration { to: u32, reason: String },

    #[error("invalid edge type {0} (must match [A-Z0-9]+)")]
    InvalidEdgeType(String),

    // NOTE: the spec (§7) names these fields `source` / `target`. `source` is a
    // reserved field name for thiserror (it is inferred as the error source and
    // requires `std::error::Error`), so the schema column names are used instead.
    #[error(
        "{source_id} -> {target_id} ({edge_type}) already has an open interval; retire it first"
    )]
    SingleOpenViolation {
        source_id: String,
        target_id: String,
        edge_type: String,
    },

    #[error("node {0} not found")]
    NotFound(String),

    #[error("embedding dim {got}, expected {expected} for model {model}")]
    DimMismatch {
        got: usize,
        expected: usize,
        model: String,
    },

    /// A model name is spliced into DDL and queries as a table identifier, and
    /// identifiers cannot be bound as parameters. Validating the name is what
    /// makes that splice safe, so an invalid one is refused rather than escaped.
    #[error("invalid embedding model name {0:?}: expected [a-z][a-z0-9_]* up to 48 characters")]
    InvalidModelName(String),

    #[error("embedding model {model} is not registered (no {table} table)")]
    ModelNotRegistered { model: String, table: String },

    /// `branches` is append-only under two unconditional triggers, so a name is
    /// written once and can never be corrected. The rule is deliberately not
    /// [`Self::InvalidModelName`]'s — a `branch_id` is always a bound value and
    /// never a spliced identifier, so what is refused here is the pair of names
    /// that read as one another rather than the ones that would break SQL.
    #[error(
        "invalid branch id {0:?}: expected 1-128 characters, \
         no control characters, no leading or trailing whitespace"
    )]
    InvalidBranchId(String),

    /// Named rather than left to the foreign key, because the caller asked
    /// about a branch and a constraint violation would answer about a column.
    #[error("branch {0} is not registered")]
    UnknownBranch(String),

    /// Refused rather than ignored, which is the interesting half: an
    /// `INSERT OR IGNORE` would return a handle to a lineage with a *different*
    /// parent and fork point than the caller asked for, which is D-069's
    /// right-looking answer to a question nobody asked.
    #[error("branch {0} already exists")]
    BranchExists(String),

    /// [`crate::Database::archive_branch`] refused (0.14.13, §15.4, D-230).
    ///
    /// Four conditions share one variant because they share one answer: the
    /// lineage stays, and the caller has to change something about the ledger
    /// before asking again. The `reason` says which — the trunk, a lineage with
    /// descendants, or a lineage whose concepts another lineage's hot edges
    /// still name.
    ///
    /// The fourth condition, a name that is not registered, is deliberately
    /// **not** here: it is [`Self::UnknownBranch`], the same answer every other
    /// branch-taking surface gives, because a typo should read the same way
    /// wherever it is made.
    #[error("branch {branch} cannot be archived: {reason}")]
    BranchNotArchivable { branch: String, reason: String },

    /// The cross-row half of the fork-point invariant, which no `CHECK` can see
    /// (§15.2): fork points must not decrease down a root path.
    ///
    /// A branch cut *before* its parent was is a branch that inherits nothing
    /// whatever from the parent it names — every row that parent wrote falls
    /// past the child's cutoff — so its `parent_id` and its visible history say
    /// different things, silently.
    ///
    /// Compared against the parent's `forked_at` and not its `created_at`,
    /// which the schema comment originally called for: `created_at` on the
    /// trunk is stamped from `SystemTime::now()` during migration, before the
    /// database's clock exists, so it is not on the same timeline as anything
    /// else. See [`Database::fork`](crate::Database::fork).
    #[error(
        "branch {branch} would fork from {parent} at {forked_at}, \
         before {parent} itself was cut at {parent_forked_at}"
    )]
    ForkPrecedesParent {
        branch: String,
        parent: String,
        forked_at: String,
        parent_forked_at: String,
    },

    /// A branch tried to restate a concept another lineage already holds
    /// (§15.2, v12, D-225).
    ///
    /// # A guard that existed for three releases with nothing able to fire it
    ///
    /// `trg_concepts_cross_lineage` has been in the schema since v12 and
    /// [`AbortKind::CrossLineage`] has recognised it since, but [`classify`]
    /// had no arm for that kind, so it fell through to
    /// [`DbError::Engine`] — the opaque variant every other guard exists to
    /// avoid. Nothing was wrong with that until 0.14.8, because until 0.14.8
    /// no write in this crate could name a lineage and no caller could reach
    /// the trigger. It is the same shape D-224 found in a comment and D-223
    /// found in a filter: **machinery written for an unbuilt caller is
    /// exercised by nothing**, so a gap in it is invisible in a green suite.
    ///
    /// `held_by` is read back on the error path rather than parsed out of the
    /// abort message, for [`RecordedAtRegression`](Self::RecordedAtRegression)'s
    /// reason: the trigger cannot put it in the text, and the database knows it.
    #[error(
        "concept {id} belongs to lineage {held_by} and {attempted} may not \
         restate it; a branch inherits concepts"
    )]
    CrossLineage {
        id: String,
        held_by: String,
        attempted: String,
    },

    /// A write reached a [`BranchView`](crate::branch::BranchView) carrying a
    /// different lineage's name (§15.4, 0.14.9, D-226).
    ///
    /// # Why this is refused rather than overwritten
    ///
    /// The view exists to spare a caller from threading a `BranchId` through
    /// every call, so the obvious reading is that it should simply *stamp* its
    /// own lineage on whatever it is handed. That is right for an assertion
    /// that names none — which is the shape a caller building through the view
    /// produces, and the one this does not refuse. It is wrong for an assertion
    /// that names a **different** lineage, because that assertion is evidence
    /// the caller believed something about where the write was going, and
    /// silently relabelling it discards the belief instead of contradicting it.
    ///
    /// The failure this catches is holding two views and passing one's
    /// assertion to the other, which nothing in the type system prevents:
    /// `BranchView` is `Clone` and both views have the same methods, so the
    /// mistake reads correctly at the call site and produces rows on the wrong
    /// lineage. On a ledger where a lineage is what a belief *means*, that is
    /// not a misfiled row — it is an assertion attributed to the wrong belief.
    #[error("view of branch {view} was handed a write naming {named}")]
    BranchMismatch {
        /// The lineage the view carries.
        view: String,
        /// The lineage the assertion named.
        named: String,
    },

    #[error("subgraph exceeds budget ({n} > {budget})")]
    SubgraphTooLarge { n: usize, budget: usize },

    /// Dijkstra and A* settle a node permanently the first time they pop it,
    /// which is only sound when no later edge can reduce the distance — that is,
    /// when weights are non-negative. `links.weight` is a bare `REAL NOT NULL`
    /// with no CHECK, so the guarantee has to be established at load time. The
    /// alternative is a shortest-path result that is quietly just a path.
    #[error("edge {source_id} -> {target_id} has weight {weight}, which shortest-path analytics cannot use")]
    NegativeEdgeWeight {
        source_id: String,
        target_id: String,
        weight: f64,
    },

    #[error("replay corrupt at seq {seq}: {reason}")]
    ReplayCorrupt { seq: i64, reason: String },

    /// A snapshot this build cannot read. Distinct from [`Self::ReplayCorrupt`]
    /// on purpose: corruption is a fault to report, an incompatible snapshot is
    /// the ordinary consequence of an upgrade, and the correct response is to
    /// discard the file and fold from the log instead (D-043).
    #[error("snapshot {path} is not readable by this build: {reason}")]
    SnapshotIncompatible { path: String, reason: String },

    /// A snapshot that is damaged rather than foreign (0.13.12, W8.2, D-185).
    ///
    /// The third case in the same family, and it needed its own name for the
    /// reason [D-069] gives: an error that names the wrong subject sends a
    /// caller to fix the wrong thing.
    ///
    /// * [`Self::SnapshotIncompatible`] — *a different build wrote this*.
    ///   Ordinary after an upgrade.
    /// * [`Self::ReplayCorrupt`] — **the ledger is damaged.** The log is the
    ///   only authority in this system and this is the worst thing it can say.
    /// * This — *the cache is damaged.* The ledger is untouched. Deleting the
    ///   file restores correctness and costs a slower reconstruction, because
    ///   [Doctrine VI] makes a snapshot derivative and disposable.
    ///
    /// Every failure of `load_snapshot` used to be `ReplayCorrupt { seq: 0 }`,
    /// which claimed the ledger was damaged and carried a sequence number that
    /// cannot exist — `AUTOINCREMENT` starts at 1. That is the same placeholder
    /// [D-069] removed from `InvalidTimestamp`, left in place here because
    /// nothing had cause to look at it.
    ///
    /// It carries the path and not a `seq`, because a snapshot is identified by
    /// its file. The reason names the check that failed, and the checks are
    /// ordered so that the earliest possible one fires: declared length, then
    /// checksum, then the decompressed size against what the header declared.
    ///
    /// [D-069]: ../docs/architecture/s13-decision-register.md#d-069
    /// [Doctrine VI]: ../docs/architecture/s0-s3-foundations.md#doctrine-vi
    #[error("snapshot {path} is damaged: {reason}")]
    SnapshotCorrupt { path: String, reason: String },

    /// A snapshot that could not be **written** (0.14.23, W12.23, C-2, [D-240]).
    ///
    /// The fourth case in the family above and the last one missing, which is
    /// why it is worth saying what the other three had in common: each names
    /// the subject a caller has to go and fix. Every failure inside
    /// `save_snapshot` — the directory, the serialization, the compression, the
    /// temp file, the write, the flush, the rename, and the directory flush
    /// after it — used to be [`Self::ReplayCorrupt`], which says **the ledger
    /// is damaged**, the worst thing this system can say. A full disk said it.
    ///
    /// * [`Self::SnapshotIncompatible`] — *a different build wrote this*.
    /// * [`Self::SnapshotCorrupt`] — *the cache is damaged*, delete the file.
    /// * [`Self::ReplayCorrupt`] — **the ledger is damaged**.
    /// * This — *the cache could not be written*. **Nothing is damaged and
    ///   nothing is lost**: [Doctrine VI] makes a snapshot derivative, so the
    ///   next start folds from the previous anchor and the whole cost is a
    ///   slower start. The subject is the filesystem.
    ///
    /// The read half of this correction shipped at 0.13.12: `load_snapshot`
    /// stopped answering `ReplayCorrupt { seq: 0 }` for a damaged file, for
    /// exactly this reason ([D-185](../docs/architecture/s13-decision-register.md#d-185)).
    /// The write half kept it for ten releases.
    ///
    /// **One variant covers the directory flush as well**, and that is
    /// [D-186](../docs/architecture/s13-decision-register.md#d-186)'s decision
    /// rather than a simplification here: a failed `sync_directory` leaves the
    /// snapshot at its final name and readable, unable only to promise the name
    /// survives a power loss, and D-186 already placed it in "the same class the
    /// file's own `sync_all` failure already returns". `reason` names which step
    /// failed.
    ///
    /// [D-240]: ../docs/architecture/s13-decision-register.md#d-240
    /// [Doctrine VI]: ../docs/architecture/s0-s3-foundations.md#doctrine-vi
    #[error("snapshot {path} could not be saved: {reason}")]
    SnapshotWriteFailed { path: String, reason: String },

    #[error("payload v{got} unsupported (max {max})")]
    PayloadVersion { got: u8, max: u8 },

    #[error("physical delete blocked outside archive session ({table})")]
    ArchiveViolation { table: String },

    /// The archive-session marker exists as **committed** state (0.10.0, W2).
    ///
    /// [`ArchiveViolation`] is this guard working. This variant is the guard
    /// having been silently switched off: while
    /// `macrame_archive_session` is present, `trg_concepts_guard_delete`,
    /// `trg_links_guard_delete` and `trg_txlog_guard_delete` all evaluate their
    /// `WHEN` to false and permit the deletes they exist to refuse, and
    /// `trg_concepts_log_insert` writes no `transaction_log` row for a concept
    /// insert. [Doctrine IV] and [Doctrine V] are both suspended, with no error
    /// and no counter — which is why the condition needs a name of its own.
    ///
    /// **It cannot be produced by an archive session, crashed or otherwise.**
    /// `archive()` and `archive_windowed()` create and drop the marker inside
    /// the same transaction that does the work, so a commit drops it and a
    /// rollback discards it; and the check that raises this error —
    /// `verify` in `src/schema/migrations.rs`, which is private, hence the file
    /// reference rather than a link — reads committed state, so it cannot see an
    /// in-flight session. Reaching this
    /// error therefore means something wrote the table outside the write actor
    /// — the raw-writer case §4.7 concedes exists.
    ///
    /// Not a [`Migration`] error: the schema is intact. What is wrong is the
    /// database's *contents*, and saying "your schema is wrong" would send the
    /// reader to the migration ladder for a fault a `DROP TABLE` fixes.
    ///
    /// [Doctrine IV]: ../../docs/architecture/s0-s3-foundations.md#doctrine-iv
    /// [Doctrine V]: ../../docs/architecture/s0-s3-foundations.md#doctrine-v
    /// [`ArchiveViolation`]: DbError::ArchiveViolation
    /// [`Migration`]: DbError::Migration
    #[error(
        "the archive-session marker table {marker:?} is present as committed \
         state. While it exists, the delete guards on concepts, links and \
         transaction_log are disarmed and concept inserts write no \
         transaction_log row. An archive session creates and drops this table \
         inside one transaction, so it should never be visible here — \
         something wrote it outside the write actor. Drop it (DROP TABLE \
         {marker}) and audit for deletions and missing log rows since it \
         appeared"
    )]
    ArchiveSessionLeaked { marker: String },

    /// A traversal asked about the past without saying which text it wanted
    /// (T3.2, D-085).
    ///
    /// An instant on either axis fixes the *topology*. Node attributes are a
    /// second, independent question, and the default answer —
    /// `AttributeMode::Current` — is live text. That combination returns the
    /// past's graph wearing the present's titles, which is a legitimate thing to
    /// want and a terrible thing to get by accident.
    ///
    /// It used to be a `tracing::warn!`, which is invisible in any application
    /// that has not configured a subscriber. This is the same statement as a
    /// value the caller cannot miss.
    ///
    /// Fix by stating the mode: `.attribute_mode(AttributeMode::AtTime)` for the
    /// past's text, or `.attribute_mode(AttributeMode::Current)` to affirm that
    /// live text is what was meant.
    ///
    /// # It carries [`StatedInstants`] rather than one string (0.13.10, W7.7, D-183)
    ///
    /// The field was `as_of: String` and the message rendered it as
    /// `as_of(…)` — a method removed in 0.12.17 when
    /// [D-174](../docs/architecture/s13-decision-register.md#d-174) split the
    /// axes. Both instants collapsed into it through an `.or()`, so a caller who
    /// set `as_of_recorded` was told about `as_of`, a caller who set both was
    /// told about one of them, and neither was told which clock they had asked
    /// about. Naming the axis is the whole remedy this error offers.
    #[error(
        "traversal {instants} did not state an attribute mode: that topology \
         would be returned with attributes as they are *now*. Call \
         .attribute_mode(AttributeMode::AtTime) for attributes as believed at \
         the stated instant, or .attribute_mode(AttributeMode::Current) to \
         confirm live attributes are intended"
    )]
    AttributeModeUnstated { instants: StatedInstants },
    /// [`crate::Database::diagnostic_conn`] could not open the file read-only
    /// (T5.1, D-091).
    ///
    /// Its own variant rather than `NotFound`, which renders "node {0} not
    /// found" — naming the wrong subject is the defect [D-069] was written to
    /// correct, and a file is not a node.
    ///
    /// The case worth the sentence is a missing file:
    /// `SQLITE_OPEN_READ_ONLY` drops `SQLITE_OPEN_CREATE` with it, so a path
    /// that does not exist is `SQLITE_CANTOPEN` rather than a fresh empty
    /// database. That is the right behaviour and an opaque error to receive.
    ///
    /// [D-069]: ../../docs/architecture/s13-decision-register.md#d-069
    #[error("cannot open {path} read-only for diagnostics: {reason}")]
    DiagnosticConn { path: String, reason: String },
    /// [`crate::Database::archive_windowed`] was given a window it cannot use
    /// (T1.1, D-080).
    ///
    /// Carries a `reason` rather than the numbers as fields because the two
    /// cases it covers are not the same shape — a zero-length window never
    /// advances at all, while a merely narrow one produces a session count that
    /// has to be quoted against the limit to mean anything. A caller reading
    /// this needs the sentence, not the struct.
    ///
    /// It is an error rather than a silent clamp on purpose. Rounding a
    /// one-second window up to something workable would archive over boundaries
    /// the caller did not choose, and the caller cannot see that it happened.
    #[error("archive window {window:?} is unusable: {reason}")]
    ArchiveWindow {
        window: std::time::Duration,
        reason: String,
    },

    /// A search asked for decay without saying what age is measured from
    /// (0.13.20, W9.5, D-193).
    ///
    /// Decay ranks a hit by how old the thing it matched is, and *old* is only
    /// meaningful relative to an instant. The crate does not read a wall clock
    /// on a read path — that is what makes the suite's `FakeClock` able to
    /// pin these answers at all — so the instant has to be stated, and the one
    /// to state is the one the search is already bounded by.
    ///
    /// Refusing rather than defaulting to *now*: a default here would silently
    /// make every decayed search a search about the present, which is exactly
    /// the class of quiet substitution F-35 and
    /// [D-175](../docs/architecture/s13-decision-register.md#d-175) were about.
    #[error(
        "a half-life was given without a valid-time instant to measure age          from: decay ranks a hit by how old what it matched is, and \"old\" is          relative to the instant the search reads at. State it —          `as_of_valid(t)` on the same search — or drop the half-life"
    )]
    HalfLifeWithoutInstant,

    /// A read named a transaction-time instant the hot log can no longer answer
    /// for (0.13.2, W7.1, D-174; extended 0.13.16, W9.1, D-189).
    ///
    /// A transaction-time read folds `transaction_log`, and
    /// [`crate::Database::archive`] removes superseded rows from it. Once
    /// anything has been archived, an instant below the cutoff is not *before
    /// history*, it is *history that is in the other file* — and these readers
    /// take a connection, not an archive path, so they cannot go and get it.
    ///
    /// **Two surfaces fold the log and both raise this.**
    /// [`crate::graph::TraversalBuilder::as_of_recorded`] folds it for topology;
    /// [`crate::temporal::hydrate_attributes`] folds it for the text under
    /// [`crate::graph::AttributeMode::AtTime`]. The second was added in 0.13.16
    /// (W9.1), where it had been returning a quietly shorter `Vec` — §3.2 of the
    /// review, and the same silence in the same wave as the first.
    ///
    /// **Conservative by one bit, deliberately.** The test is
    /// `hot_log_is_intact`: whether anything was *ever* removed. It cannot ask
    /// whether this particular instant is above the archive cutoff, because the
    /// cutoff is not recorded in the hot log — that is exactly what the hot-side
    /// marker D-132 refused would have carried. So an archived database
    /// refuses every `as_of_recorded`, including instants it could in principle
    /// have answered. The alternative is answering some of them from a partial
    /// fold, which returns *nearly* the right topology, and on a ledger that is
    /// the worst failure available.
    ///
    /// [`crate::temporal::reconstruct`] takes the archive path and answers the
    /// same question, which is why the message names it.
    #[error(
        "transaction-time instant {ts} cannot be answered from the hot log: rows \
         have been archived out of it and this read has no archive path. Use \
         macrame::temporal::reconstruct(conn, ts, archive_path, snapshots_dir), \
         which does"
    )]
    RecordedInstantUnreachable { ts: String },

    /// A timestamp that is not in canonical form (§4.1, D-029).
    ///
    /// **Distinct from [`Self::ReplayCorrupt`], which is what this used to be
    /// (Wave 4.5).** `timestamp::normalize` and `timestamp::parse` reported bad
    /// *caller input* as `ReplayCorrupt { seq: 0 }` — a claim that the ledger is
    /// damaged, carrying a sequence number that cannot exist because
    /// `AUTOINCREMENT` starts at 1. The same mistake as defect J: an error that
    /// names the wrong subject sends a caller to fix the wrong thing.
    ///
    /// The value is reported rather than the provenance, because one function
    /// serves both directions — a caller passing `2026-01-01T00:00:00Z` and a
    /// stored `recorded_at` that will not parse produce the same complaint about
    /// the same string. `SystemClock::new` is where the second case is
    /// interpreted, and it already logs and floors to the wall clock (D-027).
    #[error("timestamp {value:?} is not canonical: {reason}")]
    InvalidTimestamp { value: String, reason: String },

    /// An identifier the crate's own encodings cannot represent (D-061).
    ///
    /// Distinct from [`Self::NotFound`], and the distinction is defect J: this
    /// id was refused, not looked up. `validate_id` used to return `NotFound`
    /// here, which tells a caller the thing is missing and invites them to
    /// create it — with the same id, which will be refused again.
    #[error("invalid identifier {id:?}: {reason}")]
    InvalidId { id: String, reason: String },

    /// Two valid-time intervals for one relationship claim the same instant.
    ///
    /// Distinct from [`Self::SingleOpenViolation`], which is the storage layer's
    /// guard and covers only the *open* sentinel. This is the general case, and
    /// it is refused at the API rather than by a trigger (D-060): raw SQL against
    /// the same file can still write an overlap, and §4.2 says so.
    ///
    /// The consequence of allowing one is not an error later but a wrong answer:
    /// `query_as_of_edges` at an instant inside both returns the relationship
    /// twice, and every weighted algorithm downstream double-counts that edge.
    ///
    /// **Boxed, and it is the only variant that is (D-075).** Seven `String`s is
    /// 168 bytes, which made `DbError` — and therefore every `Result` in the
    /// crate, on the `Ok` path too — larger than `clippy::result_large_err`'s
    /// threshold the moment D-060 added it. The other variants are well under.
    /// Boxing the rarest one keeps the whole error small rather than trimming
    /// what a caller is told; `matches!(err, OverlappingInterval { .. })` is
    /// unaffected, which is how every call site uses it.
    #[error(
        "edge {} -> {} ({}): the asserted [{}, {}) overlaps [{}, {}), which {}",
        .overlap.source_id, .overlap.target_id, .overlap.edge_type,
        .overlap.valid_from, .overlap.valid_to,
        .overlap.existing_from, .overlap.existing_to,
        .overlap.provenance()
    )]
    OverlappingInterval { overlap: Box<Overlap> },

    #[error("links_current drift detected: {n} intervals diverge")]
    CurrentDrift { n: usize },

    #[error("rebuild verification failed: {n} intervals still diverge")]
    RebuildFailed { n: usize },
    /// A chunked shadow rebuild was abandoned rather than committed (T1.2, D-082).
    ///
    /// Distinct from [`Self::RebuildFailed`], and the distinction is the whole
    /// point: `RebuildFailed` means the repair ran and did not repair, which is
    /// a reason to distrust the ledger. This means the repair **did not run** —
    /// something invalidated the work in progress and it was discarded before it
    /// could be swapped in. `links_current` is untouched and whatever was true
    /// of it before is still true. The action is to retry.
    #[error("chunked rebuild abandoned: {reason}")]
    RebuildInterrupted { reason: String },

    // -- 0.4.5: writer-actor containment --
    #[error("write actor is not running (reopen the Database)")]
    WriterUnavailable,

    #[error("write actor dropped the response channel mid-request")]
    WriterDroppedResponder,

    /// The actor's task did not join cleanly at [`crate::Database::close`].
    ///
    /// Distinct from [`Self::WriterUnavailable`], which means the channel is
    /// gone while the handle is still in use. This is the shutdown path telling
    /// a caller that the write actor panicked — which `close()` used to swallow,
    /// so a database whose write path had died closed "successfully" (Wave 4.2).
    #[error("write actor did not shut down cleanly: {0}")]
    WriterStopped(String),

    // -- 0.5.0: concept integrity --
    #[error("recorded_at must advance on concept update (got {got}, had {had})")]
    RecordedAtRegression { got: String, had: String },

    /// The stored transaction-time floor is in the future (0.13.5, W7.4, §3.4).
    ///
    /// The clock is raised to `MAX(recorded_at)` at open so that stamps stay
    /// strictly increasing across restarts. That makes a single row from the
    /// future — a skewed host, a bad import, a fixture that escaped — this
    /// process's floor, and every stamp it issues lands at or after it. Those
    /// rows are then written, so the next open reads the same floor back: the
    /// damage is permanent, and it spreads.
    ///
    /// Refused at open rather than absorbed, which is where the crate can still
    /// tell the difference between a stamp it wrote and one it did not.
    /// `macrame::FutureStampPolicy` widens or waives the bound; waiving it
    /// opens the file to be *read*, and does not repair it.
    // The message names the *knob* rather than the Rust spelling of it,
    // because it crosses to Python verbatim and a caller there cannot write a
    // `Tuning` literal. `future_stamps` and `allow` are the two words that mean
    // the same thing on both surfaces.
    #[error(
        "the newest recorded_at in this database is {stamp}, past the limit \
         {limit}. The clock floor is taken from it, so opening would stamp \
         every later write at or after it — permanently, since the next open \
         reads those rows back. Set the future_stamps policy to allow to open \
         it and inspect it; that inherits the floor rather than repairing it"
    )]
    FutureRecordedAt { stamp: String, limit: String },

    /// A chunked bulk write stopped because its caller asked it to (0.13.8,
    /// W7.6, [D-181]).
    ///
    /// Not a failure of the ledger, and the only [`DbError`] a caller can
    /// *cause on purpose*. Nothing is rolled back: the chunks that committed
    /// before the token was seen are committed, which is the same per-chunk
    /// boundary [`crate::Database::bulk_import`] already documents. How many
    /// rows those were is on [`BulkInterrupted::written`], the error this
    /// arrives inside.
    ///
    /// It carries no count of its own precisely so that there is one place to
    /// read the count from, whether the stop was a cancellation or a
    /// constraint.
    ///
    /// [D-181]: ../../docs/architecture/s13-decision-register.md#d-181
    #[error("the bulk write was cancelled between chunks")]
    BulkCancelled,
}

/// What kind of failure a [`DbError`] is, as a value (0.14.25, §14.1 C-3,
/// [D-242]).
///
/// # Why this exists
///
/// [`DbError`] is `#[non_exhaustive]` ([D-207]), so a downstream `match` needs
/// a wildcard arm and can never be checked for completeness by the compiler.
/// That was a deliberate trade — a ledger that will certainly add error
/// variants after 1.0 cannot make each addition a major version — and its
/// price was paid by callers, who lost the one guarantee that told them they
/// had considered everything.
///
/// This buys part of it back, and the part it buys back is **inside this
/// crate**: [`DbError::kind`] is one exhaustive match with no wildcard, so a
/// variant added without a classification does not compile. The decision moves
/// to the person adding the variant, at the line that needs it, which is
/// exactly what [`crate::DbError`]'s binding lost in 0.13.34.
///
/// # The taxonomy is not new
///
/// These twelve names are the hierarchy the Python bindings have published
/// since they existed — seven groups a caller can catch as a set, and five
/// failures that belong to no group. Inventing a second, Rust-only taxonomy
/// here would be [D-227]'s finding again: *a surface that spells its own
/// version of a shared thing misses every repair made to the shared thing,
/// quietly*. `binding_parity_tests` pins the two spellings together.
///
/// # What it is not
///
/// It is not a replacement for matching on [`DbError`] itself. A caller who
/// needs the `path` a snapshot failed to write still matches the variant; this
/// answers the coarser question — *whose problem is this, and can I retry it* —
/// and, being `Copy + Eq + Hash`, answers it somewhere a [`DbError`] cannot go:
/// a metrics key, a log field, a counter.
///
/// It is `#[non_exhaustive]` for the same reason [`DbError`] is. An exhaustive
/// `ErrorKind` would give downstream its compile-time completeness back, and
/// would do it by making a genuinely new *category* of failure a major
/// version — which is the trap [D-207] rejected by name, one level up: the
/// category would then not get added, and the ledger would report the wrong
/// kind rather than a new one.
///
/// [D-207]: ../../docs/architecture/s13-decision-register.md#d-207
/// [D-227]: ../../docs/architecture/s13-decision-register.md#d-227
/// [D-242]: ../../docs/architecture/s13-decision-register.md#d-242
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The ledger's own invariants: overlap, drift, a leaked archive session,
    /// a rebuild that failed or was interrupted. Something is wrong with the
    /// data or with a repair of it, and no retry fixes it.
    Integrity,
    /// The caller's input was refused before anything was attempted.
    Validation,
    /// Embeddings and the model registry.
    Vector,
    /// Time, snapshots and the archive — the bitemporal machinery.
    Temporal,
    /// The write actor could not take, keep, or answer the request.
    Writer,
    /// A bound the caller set, or one the crate sets on the caller's behalf.
    Budget,
    /// Lineage: a branch that does not exist, cannot be forked, or may not be
    /// named from where the caller is standing.
    Branch,
    /// A chunked bulk write stopped between chunks. Distinct from every other
    /// kind because **part of it landed** — see [`BulkInterrupted`].
    Cancelled,
    /// The read-only diagnostic connection.
    Diagnostic,
    /// libSQL itself, passed through.
    Engine,
    /// Schema migration.
    Migration,
    /// The thing asked for is not there.
    NotFound,
}

impl ErrorKind {
    /// A stable name, for logs and metrics labels.
    ///
    /// Stable in the sense that matters for a label: these strings are part of
    /// the public surface from 1.0 and will not be re-spelled. New kinds may
    /// appear, which is what `#[non_exhaustive]` says.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Integrity => "integrity",
            Self::Validation => "validation",
            Self::Vector => "vector",
            Self::Temporal => "temporal",
            Self::Writer => "writer",
            Self::Budget => "budget",
            Self::Branch => "branch",
            Self::Cancelled => "cancelled",
            Self::Diagnostic => "diagnostic",
            Self::Engine => "engine",
            Self::Migration => "migration",
            Self::NotFound => "not_found",
        }
    }
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl DbError {
    /// This error's [`ErrorKind`].
    ///
    /// **The match below has no wildcard arm, and that is the whole point**
    /// ([D-242], §14.1 C-3). `DbError` is `#[non_exhaustive]`, so no `match`
    /// outside this crate can be checked for completeness — but inside it, the
    /// compiler still checks. A variant added without a line here fails to
    /// build, which is the guarantee [D-207] traded away for the binding and
    /// could not get back there.
    ///
    /// [D-207]: ../../docs/architecture/s13-decision-register.md#d-207
    /// [D-242]: ../../docs/architecture/s13-decision-register.md#d-242
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::Engine(_) => ErrorKind::Engine,
            Self::Migration { .. } => ErrorKind::Migration,
            Self::NotFound { .. } => ErrorKind::NotFound,
            Self::DiagnosticConn { .. } => ErrorKind::Diagnostic,
            Self::BulkCancelled => ErrorKind::Cancelled,

            Self::ArchiveSessionLeaked { .. }
            | Self::CurrentDrift { .. }
            | Self::FutureRecordedAt { .. }
            | Self::NegativeEdgeWeight { .. }
            | Self::OverlappingInterval { .. }
            | Self::RebuildFailed { .. }
            | Self::RebuildInterrupted { .. }
            | Self::RecordedAtRegression { .. }
            | Self::SingleOpenViolation { .. } => ErrorKind::Integrity,

            Self::AttributeModeUnstated { .. }
            | Self::HalfLifeWithoutInstant
            | Self::InvalidBranchId { .. }
            | Self::InvalidEdgeType { .. }
            | Self::InvalidId { .. }
            | Self::InvalidModelName { .. }
            | Self::InvalidTimestamp { .. } => ErrorKind::Validation,

            Self::DimMismatch { .. } | Self::ModelNotRegistered { .. } => ErrorKind::Vector,

            Self::ArchiveViolation { .. }
            | Self::ArchiveWindow { .. }
            | Self::PayloadVersion { .. }
            | Self::RecordedInstantUnreachable { .. }
            | Self::ReplayCorrupt { .. }
            | Self::SnapshotCorrupt { .. }
            | Self::SnapshotIncompatible { .. }
            | Self::SnapshotWriteFailed { .. } => ErrorKind::Temporal,

            Self::WriterDroppedResponder
            | Self::WriterStopped { .. }
            | Self::WriterUnavailable { .. } => ErrorKind::Writer,

            Self::SubgraphTooLarge { .. } => ErrorKind::Budget,

            Self::BranchExists { .. }
            | Self::BranchMismatch { .. }
            | Self::BranchNotArchivable { .. }
            | Self::CrossLineage { .. }
            | Self::ForkPrecedesParent { .. }
            | Self::UnknownBranch { .. } => ErrorKind::Branch,
        }
    }
}

pub type Result<T> = std::result::Result<T, DbError>;

/// A chunked bulk write that stopped partway, and how much of it landed
/// (0.13.8, W7.6, [D-181]).
///
/// The four chunked paths — [`crate::Database::bulk_import`],
/// [`write_concepts`], [`upsert_embeddings`] and
/// [`write_analytics_annotations`] — are atomic per chunk and not overall, so a
/// failure at row 19,000 of 20,000 leaves the first 18,000-odd rows committed.
/// Until 0.13.8 they returned a bare [`DbError`] and the caller was told only
/// that it failed: the count was computed, used to size the next chunk, and
/// dropped on the floor at the `?`. A caller who then retried the whole batch
/// re-wrote everything that had already landed, and one who skipped it lost the
/// tail.
///
/// This is why those four return `Result<usize, BulkInterrupted>` rather than
/// [`Result`]. `From<BulkInterrupted> for DbError` exists so `?` still works in
/// a function returning [`Result`] — that conversion is how a caller says the
/// count does not interest them, and it says so at the call site instead of
/// silently.
///
/// [`write_concepts`]: crate::Database::write_concepts
/// [`upsert_embeddings`]: crate::Database::upsert_embeddings
/// [`write_analytics_annotations`]: crate::Database::write_analytics_annotations
/// [D-181]: ../../docs/architecture/s13-decision-register.md#d-181
#[derive(Debug)]
pub struct BulkInterrupted {
    /// Rows the chunks that finished before the stop committed, and which are
    /// still committed. Zero is an ordinary value: the first chunk can fail.
    pub written: usize,
    /// Why it stopped. [`DbError::BulkCancelled`] if the caller asked;
    /// otherwise whatever the failing chunk raised, unchanged — this is not a
    /// new error, it is the same one with the count attached.
    pub cause: DbError,
}

impl std::fmt::Display for BulkInterrupted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} ({} row(s) committed before the stop, and still committed)",
            self.cause, self.written
        )
    }
}

impl std::error::Error for BulkInterrupted {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.cause)
    }
}

impl From<BulkInterrupted> for DbError {
    /// Discards `written`. That is the point: a caller writing `?` into a
    /// function returning [`Result`] has decided the partial count is not
    /// something they will act on, and this puts that decision at the place it
    /// is taken rather than inside the crate.
    fn from(e: BulkInterrupted) -> Self {
        e.cause
    }
}

impl BulkInterrupted {
    /// Whether the stop was the caller's own cancellation rather than a fault.
    pub fn was_cancelled(&self) -> bool {
        matches!(self.cause, DbError::BulkCancelled)
    }
}

/// What the four chunked bulk paths return (0.13.8, W7.6).
pub type BulkResult<T> = std::result::Result<T, BulkInterrupted>;

/// A guard abort recognised by its message (§4.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AbortKind {
    SingleOpenInterval,
    RecordedAtRegression,
    DeleteOutsideArchive,
    /// A concept id already held by a different lineage (v12, §15.2, D-214).
    CrossLineage,
    /// An `UPDATE` that would move a concept between lineages (v12, D-214).
    BranchImmutable,
    /// Any write to `branches` other than an insert (v12, §15.2).
    BranchesFrozen,
    /// Not one of our guards — an ordinary engine error.
    NotAGuard,
}

/// Recognise a schema guard's `RAISE(ABORT, …)` by its message.
///
/// **The only place in the crate that matches on engine error text.** SQLite
/// reports a `RAISE(ABORT)` as a generic constraint failure carrying the
/// message, so the message is the only thing distinguishing "you violated the
/// single-open-interval rule" from "the disk is full" — but matching on it
/// scattered across call sites means an upstream wording change degrades an
/// unknown number of typed errors into opaque ones, silently. Concentrated here,
/// a change breaks one function and the tests that cover it.
///
/// The needles are the [`crate::schema::ddl`] constants spliced into the
/// triggers themselves, so guard and classifier cannot drift.
pub fn abort_kind(err: &libsql::Error) -> AbortKind {
    use crate::schema::ddl::{
        ABORT_BRANCHES_FROZEN, ABORT_BRANCH_IMMUTABLE, ABORT_CROSS_LINEAGE, ABORT_DELETE_GUARD,
        ABORT_MONOTONIC_RA, ABORT_SINGLE_OPEN,
    };

    let text = err.to_string();
    if text.contains(ABORT_SINGLE_OPEN) {
        AbortKind::SingleOpenInterval
    } else if text.contains(ABORT_MONOTONIC_RA) {
        AbortKind::RecordedAtRegression
    } else if text.contains(ABORT_DELETE_GUARD) {
        AbortKind::DeleteOutsideArchive
    } else if text.contains(ABORT_CROSS_LINEAGE) {
        AbortKind::CrossLineage
    } else if text.contains(ABORT_BRANCH_IMMUTABLE) {
        AbortKind::BranchImmutable
    } else if text.contains(ABORT_BRANCHES_FROZEN) {
        AbortKind::BranchesFrozen
    } else {
        AbortKind::NotAGuard
    }
}

/// What a failing statement was trying to do, so a guard abort can name it.
#[non_exhaustive]
pub enum WriteOp<'a> {
    Edge {
        source_id: &'a str,
        target_id: &'a str,
        edge_type: &'a str,
    },
    Concept {
        id: &'a str,
        recorded_at: &'a str,
        /// The lineage the upsert named, for `DbError::CrossLineage` (0.14.8).
        /// It cannot be read back after the abort, because the row it would
        /// have been on was never written.
        branch: &'a str,
    },
    Delete {
        table: &'a str,
    },
    /// A derived annotation (0.13.3, W7.2, [`crate::Annotation`]).
    ///
    /// The only [`WriteOp`] whose failure is not a `RAISE(ABORT)`.
    /// `analytics_annotations` carries no triggers at all — that is why it is
    /// the cheapest bulk table and why its chunk ceiling is the largest
    /// (D-058) — so the guard vocabulary [`abort_kind`] speaks has nothing to
    /// say about it. What it does carry is a foreign key onto `concepts`, and
    /// that is the failure a caller can actually cause.
    Annotation {
        concept_id: &'a str,
    },
}

/// `SQLITE_CONSTRAINT_FOREIGNKEY` — `SQLITE_CONSTRAINT | (3 << 8)`.
///
/// libSQL reports statement failures through
/// `libsql::Error::SqliteFailure(extended_error_code(…), …)`, so this is the
/// *extended* code and discriminates a foreign-key failure from the CHECK,
/// PRIMARY KEY and NOT NULL failures that share primary code 19. Matching the
/// primary code would classify a malformed `computed_at` — a different bug with
/// a different fix — as a missing concept.
const SQLITE_CONSTRAINT_FOREIGNKEY: std::ffi::c_int = 787;

/// Recognise a foreign-key failure by its result code, not by its message.
///
/// The deliberate counterpart to [`abort_kind`]. That function matches text
/// because it has no alternative: SQLite flattens every `RAISE(ABORT)` into one
/// generic constraint failure and the message is the only thing left. A foreign
/// key is enforced by the engine itself and carries a code of its own, so
/// nothing here depends on wording — an upstream message change cannot degrade
/// this classification, which is exactly the failure mode `abort_kind`'s
/// rustdoc warns about and cannot escape.
fn is_foreign_key_violation(err: &libsql::Error) -> bool {
    matches!(err, libsql::Error::SqliteFailure(code, _) if *code == SQLITE_CONSTRAINT_FOREIGNKEY)
}

/// Turn an engine error into the typed error §7 specifies, where one applies.
///
/// Takes a connection because `RecordedAtRegression` reports the value it
/// clashed with, and the trigger does not put it in the message. One extra query
/// on an error path buys an error a caller can act on instead of one they have
/// to reproduce by hand.
pub async fn classify(conn: &libsql::Connection, err: libsql::Error, op: WriteOp<'_>) -> DbError {
    match (abort_kind(&err), op) {
        (
            AbortKind::SingleOpenInterval,
            WriteOp::Edge {
                source_id,
                target_id,
                edge_type,
            },
        ) => DbError::SingleOpenViolation {
            source_id: source_id.to_string(),
            target_id: target_id.to_string(),
            edge_type: edge_type.to_string(),
        },
        (
            AbortKind::RecordedAtRegression,
            WriteOp::Concept {
                id, recorded_at, ..
            },
        ) => {
            let had = current_recorded_at(conn, id).await.unwrap_or_default();
            DbError::RecordedAtRegression {
                got: recorded_at.to_string(),
                had,
            }
        }
        (AbortKind::DeleteOutsideArchive, WriteOp::Delete { table }) => DbError::ArchiveViolation {
            table: table.to_string(),
        },
        (AbortKind::CrossLineage, WriteOp::Concept { id, branch, .. }) => DbError::CrossLineage {
            id: id.to_string(),
            held_by: lineage_of_concept(conn, id).await,
            attempted: branch.to_string(),
        },
        // An annotation naming a concept that is not there. The engine says
        // "FOREIGN KEY constraint failed" and no more — not which row, and a
        // rejected chunk may hold up to `chunk_rows::ANNOTATIONS` of them. The
        // typed error names the concept, which is the fact the database
        // actually knows and the one the caller has to act on.
        (_, WriteOp::Annotation { concept_id }) if is_foreign_key_violation(&err) => {
            DbError::NotFound(concept_id.to_string())
        }
        // The same treatment for an edge, which W7.2 left out because its scope
        // was the annotation path (C-1, D-176). `links` declares **two** keys
        // into `concepts`, so unlike the annotation case the message does not
        // even narrow it to one column: an unqualified "FOREIGN KEY constraint
        // failed" is all a caller gets for a batch that may have named the
        // wrong source, the wrong target, or both.
        //
        // Which one is missing is a question the database can answer, so it is
        // asked rather than guessed. The source is reported when both are
        // absent — one name a caller can act on beats a compound message that
        // has to be parsed.
        (
            _,
            WriteOp::Edge {
                source_id,
                target_id,
                ..
            },
        ) if is_foreign_key_violation(&err) => {
            DbError::NotFound(missing_endpoint(conn, source_id, target_id).await)
        }
        // A guard fired for an operation it does not describe. Reporting the raw
        // error is honest; inventing a typed one from the wrong context is not.
        _ => DbError::Engine(err),
    }
}

/// Who holds a concept id, for [`DbError::CrossLineage`].
///
/// The refused lineage is not read back — the row was never written — so it
/// comes from [`WriteOp::Concept`], which is the only place it survives the
/// abort. Falls back to `"?"` rather than guessing when the read fails, for
/// [`missing_endpoint`]'s reason: a classifier that can fail twice is worse than
/// one that answers approximately.
async fn lineage_of_concept(conn: &libsql::Connection, id: &str) -> String {
    let unknown = || "?".to_string();
    let Ok(mut rows) = conn
        .query(
            "SELECT branch_id FROM concepts WHERE id = ?1",
            libsql::params![id],
        )
        .await
    else {
        return unknown();
    };
    match rows.next().await {
        Ok(Some(row)) => row.get::<String>(0).unwrap_or_else(|_| unknown()),
        _ => unknown(),
    }
}

/// Which endpoint of a refused edge is not in `concepts` (C-1).
///
/// One query on an error path, for the reason [`classify`]'s own rustdoc gives:
/// it buys an error a caller can act on instead of one they have to reproduce
/// by hand. Falls back to the source id if the query itself fails, because a
/// classifier that can fail twice is worse than one that answers approximately.
///
/// # The concepts path, and why it still needs no arm of its own
///
/// C-1 names `links` **and** `concepts`. Since v12 `concepts` carries an
/// outbound key — `branch_id` into `branches` (§15.2) — and **since 0.14.8 a
/// caller can choose what goes in it**, which is the condition this paragraph
/// used to say would need an arm "with a different column".
///
/// It still does not, and the reason moved rather than held: the write path
/// checks every lineage a write names *before* it opens the transaction
/// (`connection::check_lineages`), so an unregistered branch comes back as
/// [`DbError::UnknownBranch`] naming the branch, and the foreign key never
/// fires. An arm here would be a classification for a state the API cannot
/// reach — defect Q's shape, a typed error no code path can produce — and the
/// honest place for the refusal is the one that can say *branch* rather than
/// *constraint*.
async fn missing_endpoint(conn: &libsql::Connection, source_id: &str, target_id: &str) -> String {
    for id in [source_id, target_id] {
        let Ok(mut rows) = conn
            .query("SELECT 1 FROM concepts WHERE id = ?1", libsql::params![id])
            .await
        else {
            return source_id.to_string();
        };
        if !matches!(rows.next().await, Ok(Some(_))) {
            return id.to_string();
        }
    }
    source_id.to_string()
}

async fn current_recorded_at(conn: &libsql::Connection, id: &str) -> Option<String> {
    conn.query(
        "SELECT recorded_at FROM concepts WHERE id = ?1",
        libsql::params![id],
    )
    .await
    .ok()?
    .next()
    .await
    .ok()??
    .get(0)
    .ok()
}

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

    /// `DbError` stays under `clippy::result_large_err`'s 128-byte threshold.
    ///
    /// Every fallible function in the crate returns `Result<T, DbError>`, so the
    /// enum's size is paid on the `Ok` path too. D-060 pushed it to 168 bytes with
    /// one seven-`String` variant and nobody noticed until D-075 read the lint
    /// output; boxing that variant brought it back. This is the tripwire, because
    /// the failure mode is a warning in a build log rather than a broken test —
    /// the kind this cycle has spent its whole length finding.
    #[test]
    fn the_error_enum_stays_small_enough_to_return_by_value() {
        let size = std::mem::size_of::<DbError>();
        assert!(
            size <= 128,
            "DbError is {size} bytes. Some variant has grown past what a Result \n             should carry — box it, as OverlappingInterval is boxed (D-075)."
        );
    }

    fn sample_overlap(within_batch: bool) -> DbError {
        DbError::OverlappingInterval {
            overlap: Box::new(Overlap {
                source_id: "a".into(),
                target_id: "b".into(),
                edge_type: "KNOWS".into(),
                valid_from: "2026-03-01T00:00:00.000000Z".into(),
                valid_to: "2026-09-01T00:00:00.000000Z".into(),
                existing_from: "2026-01-01T00:00:00.000000Z".into(),
                existing_to: "2026-06-01T00:00:00.000000Z".into(),
                within_batch,
            }),
        }
    }

    /// The boxed variant still reports both intervals.
    #[test]
    fn an_overlap_names_the_asserted_interval_and_the_other_one() {
        let msg = sample_overlap(false).to_string();
        assert!(msg.contains("a -> b (KNOWS)"), "{msg}");
        assert!(msg.contains("asserted [2026-03-01"), "{msg}");
        assert!(msg.contains("[2026-01-01"), "{msg}");
    }

    /// One error, two guards, and only one of them is talking about the
    /// database (0.13.7, D-180).
    ///
    /// `reject_overlaps_within` refuses the batch *before* the transaction
    /// opens, so the interval it names is not stored and will not become
    /// stored. Saying the edge "already holds" it sent a caller looking for a
    /// row that was never written.
    #[test]
    fn an_overlap_says_which_side_of_the_write_the_other_interval_is_on() {
        let stored = sample_overlap(false).to_string();
        assert!(stored.contains("is already recorded"), "{stored}");
        assert!(!stored.contains("batch"), "{stored}");

        let in_batch = sample_overlap(true).to_string();
        assert!(
            in_batch.contains("this same batch also asserts"),
            "{in_batch}"
        );
        assert!(!in_batch.contains("recorded"), "{in_batch}");
    }

    /// The count is the whole reason this type exists, so it has to be in the
    /// sentence a caller sees, not only in a field they have to know about
    /// (0.13.8, W7.6).
    #[test]
    fn a_partial_bulk_failure_says_how_much_landed() {
        let e = BulkInterrupted {
            written: 18_935,
            cause: DbError::NotFound("ghost".into()),
        };
        let text = e.to_string();
        assert!(text.contains("node ghost not found"), "{text}");
        assert!(text.contains("18935"), "{text}");
    }

    /// Cancellation is not a fault, and the type says which it was without the
    /// caller matching on a variant.
    #[test]
    fn cancellation_is_distinguishable_from_a_failure() {
        assert!(BulkInterrupted {
            written: 7,
            cause: DbError::BulkCancelled,
        }
        .was_cancelled());
        assert!(!BulkInterrupted {
            written: 7,
            cause: DbError::WriterUnavailable,
        }
        .was_cancelled());
    }

    /// `?` into a `Result<_, DbError>` keeps the cause and drops the count.
    /// Both halves of that are deliberate; this pins them.
    #[test]
    fn converting_to_a_db_error_keeps_the_cause_and_loses_the_count() {
        let e = BulkInterrupted {
            written: 400,
            cause: DbError::SingleOpenViolation {
                source_id: "a".into(),
                target_id: "b".into(),
                edge_type: "KNOWS".into(),
            },
        };
        let cause: DbError = e.into();
        assert!(matches!(cause, DbError::SingleOpenViolation { .. }));
        assert!(!cause.to_string().contains("400"));
    }

    /// The error chain reaches the cause, so `anyhow`-style reporters print
    /// both lines rather than only the wrapper's.
    #[test]
    fn the_cause_is_reachable_as_an_error_source() {
        use std::error::Error;
        let e = BulkInterrupted {
            written: 1,
            cause: DbError::BulkCancelled,
        };
        assert_eq!(
            e.source().map(ToString::to_string).as_deref(),
            Some("the bulk write was cancelled between chunks")
        );
    }

    /// The kind is a property of the variant, not of what it is carrying
    /// (0.14.25, C-3, [D-242]).
    ///
    /// [D-242]: ../../docs/architecture/s13-decision-register.md#d-242
    #[test]
    fn the_kind_is_the_same_whatever_the_fields_say() {
        let a = DbError::SnapshotWriteFailed {
            path: "snapshots/1.snap.zst".into(),
            reason: "no space left on device".into(),
        };
        let b = DbError::SnapshotWriteFailed {
            path: "elsewhere".into(),
            reason: "read-only file system".into(),
        };
        assert_eq!(a.kind(), b.kind());
        assert_eq!(a.kind(), ErrorKind::Temporal);
    }

    /// A snapshot that could not be written and a damaged ledger are the same
    /// *kind*, and that is deliberate: [D-240] split them so a caller learns
    /// which subject is broken, and the kind answers the coarser question. The
    /// discriminant does not replace matching the variant, and this test is
    /// where that is written down rather than assumed.
    ///
    /// [D-240]: ../../docs/architecture/s13-decision-register.md#d-240
    #[test]
    fn the_kind_is_coarser_than_the_variant_and_says_so() {
        let unwritten = DbError::SnapshotWriteFailed {
            path: "p".into(),
            reason: "r".into(),
        };
        let damaged = DbError::ReplayCorrupt {
            seq: 7,
            reason: "r".into(),
        };
        assert_eq!(unwritten.kind(), damaged.kind());
        assert_ne!(unwritten.to_string(), damaged.to_string());
    }

    /// Two kinds never share a name, or a metrics label collapses two
    /// populations into one bar.
    #[test]
    fn no_two_kinds_spell_themselves_the_same_way() {
        use std::collections::BTreeSet;
        let kinds = [
            ErrorKind::Integrity,
            ErrorKind::Validation,
            ErrorKind::Vector,
            ErrorKind::Temporal,
            ErrorKind::Writer,
            ErrorKind::Budget,
            ErrorKind::Branch,
            ErrorKind::Cancelled,
            ErrorKind::Diagnostic,
            ErrorKind::Engine,
            ErrorKind::Migration,
            ErrorKind::NotFound,
        ];
        let names: BTreeSet<&str> = kinds.iter().map(|k| k.as_str()).collect();
        assert_eq!(
            names.len(),
            kinds.len(),
            "two kinds share a label: {names:?}"
        );
        for kind in kinds {
            assert_eq!(kind.to_string(), kind.as_str(), "Display and as_str differ");
        }
    }

    /// It goes where a `DbError` cannot: a key.
    #[test]
    fn a_kind_can_be_counted() {
        use std::collections::HashMap;
        let mut seen: HashMap<ErrorKind, usize> = HashMap::new();
        for err in [
            DbError::WriterStopped("a write".into()),
            DbError::WriterDroppedResponder,
            DbError::BulkCancelled,
        ] {
            *seen.entry(err.kind()).or_default() += 1;
        }
        assert_eq!(seen[&ErrorKind::Writer], 2);
        assert_eq!(seen[&ErrorKind::Cancelled], 1);
    }
}