1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
//! Reading one lineage's belief out of a ledger that holds several (§15.2,
//! §15.3, D-219, D-220, D-223).
//!
//! # Three shapes, and the measurements that forced them
//!
//! `links_current` is keyed `(source_id, target_id, edge_type, valid_from,
//! branch_id)` since v12, so a branch that corrects or retires an edge it
//! inherited writes its **own** row beside the ancestor's rather than over it.
//! Reading a lineage therefore means picking one row per edge key: the one
//! belonging to the **nearest** branch on the path from the reader to the root.
//!
//! The naive alternative — admit every row whose `branch_id` is anywhere on the
//! path — is not a resolution and `branch_traversal_probe` §4b measures what it
//! costs. A branch that retires an inherited edge by shadowing it gets the
//! *whole subtree back*: 1,111 nodes where the resolved read gives 1,000. The
//! union form does not merely report a stale weight, it discards retirement.
//!
//! Resolution is not free and does not become free when there is nothing to
//! resolve. Measured on a single-lineage database — every database this crate
//! has ever written — the resolved traversal is **3.0×** the unresolved one,
//! because a window function is opaque to the planner and it cannot see that
//! every partition holds exactly one row. So the read path picks a shape, the
//! way `temporal::replay::cold_lineage` picks one at the archive boundary
//! (D-216): [`LineageShape::Trunk`] emits today's SQL, [`LineageShape::Resolved`]
//! emits the ancestry join.
//!
//! The third shape is the trunk's, on a database that has forked
//! ([`LineageShape::TrunkOnForked`], 0.15.2, D-244). Once `branches` holds
//! two rows the trunk's read was `Resolved` like everyone else's, and paid
//! the hybrid's fixed cost — D-223 measured 1.45× at zero churn, and the
//! trunk has zero churn *structurally*: it has no ancestors, so no cutoff
//! and no churned set. Its resolved read reduces to its own rows, and the
//! third shape emits that reduction as one predicate on `branch_id`. It is
//! the escalation D-223 named — the naive filter, emitted when the answer
//! to *does any ancestor hold a post-cutoff row* is no — taken where the
//! answer is no by construction rather than by probing.
//!
//! # Why one lineage is a sufficient condition for the fast shape
//!
//! `branch_id` is `NOT NULL DEFAULT 'main' REFERENCES branches(branch_id)` on
//! every ledger table (D-215), and the key is real. So a `branches` table
//! holding one row is a database in which every ledger row reads `'main'` — not
//! by convention but because nothing else could have been stored. The ancestry
//! of `main` is `{main}`, every partition has one member, and the resolved form
//! and the plain form return the same rows by construction. The check is
//! therefore exact rather than a heuristic, which is what makes it safe to skip
//! the work rather than merely cheap.
//!
//! # The fork point is a visibility cutoff, and one filter cannot apply it
//!
//! 0.14.4 resolved *which lineage holds an edge* and never looked at
//! `branches.forked_at`, so a branch kept absorbing writes its parent made
//! after the fork. §15.3 says the opposite in as many words — rows written on
//! each ancestor **before the fork point on the path down from A** — and
//! `ddl`'s own comment calls `forked_at` "what §15.3's visibility cutoffs are
//! computed over". Nothing computed them. 0.14.6 does (D-223).
//!
//! **The finding is not that a filter was missing.** `links_current` answers
//! *current as of now* and structurally cannot answer *current as of t*: the
//! projection holds one belief per key per lineage, and
//! `trg_links_current_sync` is `ON CONFLICT … DO UPDATE … recorded_at =
//! excluded.recorded_at`. So the moment the trunk reweights or retires an edge
//! after the fork, the pre-fork version is **not in the table at all**, and its
//! only home is `transaction_log`. Adding `recorded_at <= cutoff` to the
//! existing read would therefore not show the branch its inherited edge — it
//! would make that edge *vanish*, which is wrong in a new and quieter way.
//! Every "just add the filter" instinct fails for that one reason.
//!
//! So the read is a **hybrid**: [`links_cut_cte`] takes the `links_current`
//! rows a lineage may still see directly, and folds the log for exactly the
//! keys where it may not. The fold arm's cost scales with **post-fork churn on
//! the ancestors**, not with history size, and the untouched keys — the common
//! case, because a fork exists to diverge from a trunk that mostly stands still
//! — stay on the projection.
//!
//! **The two arms are disjoint by construction, and that is why [`churned_cte`]
//! is defined over `links_current` rather than over the log.** One predicate on
//! one row decides which arm emits a given `(edge key, lineage)`:
//! `recorded_at <= cutoff` sends it to the projection arm, `>` sends it to the
//! fold arm. Deriving the churned set from `transaction_log` instead would have
//! been a cheaper seek — `idx_txlog_time` is a range index and the projection
//! has none on `recorded_at` — but disjointness would then be an argument about
//! what the archive does and does not remove, rather than a property of a
//! single comparison. Two arms emitting one key would put two rows at the same
//! `dist` into [`visible_cte`]'s partition, where the winner is whichever the
//! engine happened to order first.
//!
//! **Where this degrades, named rather than left to be found.** The fold arm
//! reads the *hot* log, and `LOG_ARCHIVABLE` archives any entry superseded by a
//! later one for the same entity. A pre-fork assertion superseded by a
//! post-fork correction is superseded, so once the retention horizon passes the
//! fork point that entry can be cold — and then the branch loses an edge its
//! ancestor churned. That is §3.2's already-carried `AtTime` degradation
//! reached from the branch side, not a new class of loss, and it is bounded to
//! churned keys: the projection arm never degrades, because `links_current` is
//! re-derived from surviving `links` rather than deleted from. It is
//! deliberately **not** guarded by `check_recorded_reach`, and the reason has
//! changed shape without changing sides (0.15.4, D-246). It used to be that the
//! guard's bit was coarse — any archive at all flipped it, so guarding here
//! would have refused every branched read on every archived database. The guard
//! is now scoped to the instants the archive really took, which removes that
//! objection and leaves the smaller one: `links_cut` reads the log for a *fork
//! point*, not for a belief, and a fork point that has gone cold is a different
//! question from an instant that has. A cold arm for `links_cut` is the fix if
//! it is ever needed, and it belongs with §3.2 rather than with the cutoff.
use crate;
use crate;
use crateddl;
/// Which form of the read to emit. See the module docs.
pub
/// The shape, and the ancestry the shape needs — one round trip for both.
///
/// This is what `lineage_shape` became (0.15.17, [D-259]). Where that asked
/// SQLite for three aggregates, this loads the rows and answers from them;
/// measured, that is **10.0 µs against 11.0**
/// (`examples/ancestry_resolve_probe.rs` §5), so the ancestry arrives for less
/// than the shape alone used to cost and nothing has to be cached to afford it.
///
/// The ancestry is empty under the two trunk shapes. Neither emits a `lineage`
/// relation, so resolving one would be a walk whose result no SQL names — and
/// an empty slice is what makes [`crate::graph::plan::lower`] able to ignore
/// the field rather than branch on whether it was populated.
///
/// A caller wanting the question and not the answer goes through [`Lineages`]
/// directly: `branch::diff` loads the register once and asks [`Lineages::shape`]
/// per name, which refuses an unregistered lineage before either side is
/// lowered — and is one round trip for both, where a free function per name was
/// two.
///
/// [D-259]: ../../docs/architecture/s13-decision-register.md#d-259
pub async
/// One lineage's row in `branches`, as the resolution needs it.
///
/// Three columns and not the table: `created_at` is the audit column and no
/// read resolves over it, so loading it would be bytes moved for nothing.
pub
/// Every lineage the database holds — the table [`resolve`] walks.
///
/// A `Vec` and a linear scan, for the reason `distinct_branches` gives: the
/// bound is the number of lineages, which is small and human-authored, and a
/// map would allocate to index a list that is usually of length one.
///
/// # Why this is loaded per read rather than cached (0.15.17, [D-259])
///
/// [A-2] proposed a cached `Vec<Branch>` with a generation counter, on the
/// premise that resolving ancestry in Rust needs the *rows* where the shape
/// needed only three aggregates, and that the extra read has to be paid for.
/// Measured (`examples/ancestry_resolve_probe.rs`, §5), it does not: loading 17
/// rows costs **10.0 µs** against the three-aggregate `SELECT`'s **11.0 µs**,
/// so the rows arrive for *less* than the answer they replace. The cache is an
/// optimisation nothing has asked for, and a cache the read side does not need
/// is a coherency question the read side does not have to answer.
///
/// The actor keeps its copy ([`crate::connection`]'s `ActorState`) because the
/// write path already had one and invalidates it on the two commands that write
/// `branches`. That is a cache with an owner; this is not.
///
/// [A-2]: ../../docs/Macrame%20Codebase%20Review%20v0.15.0.md
/// [D-259]: ../../docs/architecture/s13-decision-register.md#d-259
pub
/// One resolved ancestor: exactly the three columns the recursive
/// `ancestry_cte` produced until 0.15.17.
///
/// Public through [`crate::branch`] as the answer `reconstruct_on` resolves
/// over, which is review C-10: until 0.15.17 the resolution rule existed only
/// as SQL, so a caller holding a `Vec<EdgeBelief>` had no function to finish
/// the question the fold started.
///
/// # Usually read, occasionally built (0.15.17, [D-255])
///
/// `#[non_exhaustive]`, and [`new`](Ancestor::new) is the way in — a fourth
/// column is plausible (the fork's own `created_at` has been wanted twice) and
/// a struct literal outside this crate would make it a major version.
///
/// Almost every caller *reads* one: [`Database::ancestry`] resolves it out of
/// `branches`, refusing an unregistered lineage first, and
/// [`resolve_beliefs`](crate::temporal::resolve_beliefs) consumes what it
/// returned. The constructor exists for the caller who is exercising that pure
/// function rather than a database, which is a real case — it is what this
/// crate's own test for it does — and is worth naming, because an ancestry
/// assembled by hand is a distance rule the caller has stated and
/// `resolve_beliefs` will apply as faithfully as it applies a resolved one.
///
/// [D-255]: ../../docs/architecture/s13-decision-register.md#d-255
/// [`Database::ancestry`]: crate::Database::ancestry
/// Walk `branches` from `start` to its root, carrying the running minimum.
///
/// The Rust half of [D-259]: the same relation [`ancestry_cte`] computed with
/// `WITH RECURSIVE`, computed here instead. Term for term — the reader at
/// `dist` 0 with no cutoff, then one row per ancestor, each carrying the
/// **minimum** `forked_at` seen on the path down to it.
///
/// See [`ancestry_cte`] for why the cutoff is the *child's* `forked_at` and why
/// the minimum is running rather than assigned. The property that matters here
/// is that this is a second implementation of a rule the crate already had, so
/// it is pinned against the original differentially rather than against a
/// restatement of the rule (`the_rust_walk_agrees_with_the_cte`, below).
///
/// # Termination without trusting the data
///
/// `branches.parent_id` is a foreign key into an append-only table whose parent
/// must exist before its child, so the graph is a forest and the walk is finite.
/// The loop is bounded by the row count anyway. That bound is not the
/// termination argument — it is what stops a corrupted file from hanging a read,
/// which is a different failure from the one the schema rules out, and the walk
/// returns the prefix it had rather than raising: a caller reading a broken
/// `branches` gets a narrower answer, not a panic.
///
/// [D-259]: ../../docs/architecture/s13-decision-register.md#d-259
pub
/// The ancestry as a bound `VALUES` table, replacing the recursive CTE.
///
/// `first_slot` is where the block starts; it occupies `3 × rows` placeholders
/// from there, and every reader puts it **after** its own fixed slots so that no
/// existing layout moves.
///
/// # Bound and not interpolated
///
/// A branch id is caller-supplied text. The crate has exactly one arbitrary-SQL
/// surface ([D-258]) and this is not a second one, so every value binds — the
/// cutoff too, `NULL` included, which libSQL accepts inside `VALUES`
/// (`ancestry_resolve_probe.rs` §1 checks it rather than assuming it). The
/// consequence is that the statement *text* varies with ancestry **depth** and
/// with nothing else, so a prepared-statement cache keyed on text sees one entry
/// per distinct fork depth rather than one per lineage.
///
/// `dist` binds too, though it is the row's own index and could be a literal.
/// Measured (`ancestry_resolve_probe.rs` §7) that saves a third of the
/// placeholders and **1–5%**, inside the noise, so it is spelled the way the
/// other two columns are rather than differently for a gain that did not
/// survive being measured.
///
/// [D-258]: ../../docs/architecture/s13-decision-register.md#d-258
pub
/// The ancestry's placeholder values, in the order [`ancestry_values`] names
/// them.
pub
/// The ancestry of the reading branch, nearest first, each with its cutoff.
///
/// `dist` is what makes this a resolution rather than a union: it is the
/// distance from the reader to each ancestor, and the row a lineage sees is the
/// one belonging to the smallest `dist` holding that edge key.
///
/// The recursion terminates on `parent_id IS NULL`, which the `branches` CHECK
/// pairs with `forked_at IS NULL` so that exactly one row — the root — can end
/// it. A cycle is not representable: `parent_id` is a foreign key into a table
/// whose rows are append-only and whose parent must already exist when the child
/// is written, so the graph is a forest by construction and the walk is finite
/// without a depth bound.
/// `slot` is where the reading branch binds, and it is passed rather than
/// spelled: the placeholder layout belongs to
/// [`TraversalBuilder`](crate::graph::TraversalBuilder), which computes it once
/// so that no two call sites can agree on it separately (D-030, D-035).
///
/// # `cutoff`, and why it is the child's `forked_at` rather than the row's
///
/// §15.3: a read on B sees rows written on each ancestor A *before the fork
/// point on the path down from A*. The fork point on the path down from A is
/// where **A's child on that path** diverged — so stepping from a branch to its
/// parent, the parent's cutoff is the stepping branch's own `forked_at`. The
/// reader itself has no cutoff at all, which is `NULL` in the anchor row and
/// the only `NULL` the column ever holds.
///
/// It is a running minimum rather than a plain assignment. `b` forks from `a`
/// at *t₂* and `a` from `main` at *t₁*, so `b` sees `main` as of *t₁* and not
/// as of *t₂* — inheritance composes, and each step can only narrow the window.
/// With `forked_at` monotone down a chain the `min` never fires; it is here
/// because the schema does not enforce that ordering and a read should not be
/// the thing that discovers it isn't.
///
/// # The equivalence that makes the fold arm safe
///
/// Under these cutoffs, **nearest-ancestor-wins and latest-`recorded_at`-wins
/// coincide**: each ancestor's visible window ends where its descendant's
/// begins, so the deepest lineage member holding a pre-cutoff row for a key is
/// also the one holding the newest such row. That is why
/// [`links_cut_cte`]'s fold arm may bound per lineage with a plain
/// `ROW_NUMBER() … PARTITION BY entity_id, branch_id` and hand the cross-lineage
/// question to [`visible_cte`], with no tiebreak between ancestors anywhere.
///
/// Stated as a consequence of the write path, not as a theorem about the
/// schema: it holds because a branch's own writes follow its fork, which
/// `fork()` and branch-scoped writes guarantee and no CHECK does. The
/// resolution still orders by `dist`, which is the definition; the equivalence
/// is what says the fold cannot disagree with it.
///
/// # `tag`, and the one query that needs two of these (0.14.11, [D-228])
///
/// Every read before `diff` resolved **one** lineage, so the four CTEs could
/// take their names as constants. A diff resolves two in one statement — it
/// has to, because two statements compare two snapshots and can report a
/// difference that never existed — and SQLite has one namespace per `WITH`
/// list. So each name here takes a suffix, and every caller that resolves one
/// lineage passes `""` and emits exactly the text it emitted before.
///
/// A suffix rather than a second copy of the hybrid, for the reason
/// [D-227](../../docs/architecture/s13-decision-register.md#d-227) gave when it
/// declined to hand-write the cutoff into `query_as_of_edges_on`: the two arms
/// of [`links_cut_cte`] must partition, and that is a property of one
/// comparison written once, not an argument to restate in a second place.
///
/// [D-228]: ../../docs/architecture/s13-decision-register.md#d-228
/// The three placeholders that fix one edge key, when the reader has one.
///
/// The write path always does: [`crate::connection`]'s overlap guard and its
/// retirement both hold a `(source, target, edge_type)` before any SQL exists,
/// and asking the resolution about the whole projection to then discard all but
/// one key would make a branched bulk write O(rows) per row.
///
/// Narrowing is **not** a filter appended to the resolved relation. It is
/// pushed into the base scans of [`churned_cte`] and [`links_cut_cte`], where
/// `idx_lc_open_interval` leads with exactly these three columns and each arm
/// becomes a seek (0.14.8, [D-225]; lowered 0.15.8, W13.3, [D-250]).
///
/// It also decides one column. A keyed read is a *write* path read, and the
/// write path carries `properties` through the resolution because
/// [`retire_from_resolved`] restates it on the shadow row; an
/// unkeyed traversal does not, and carrying a JSON blob through a window over
/// the whole projection is not a cost a reader should pay for a column it never
/// selects.
///
/// [D-225]: ../../docs/architecture/s13-decision-register.md#d-225
/// [D-250]: ../../docs/architecture/s13-decision-register.md#d-250
pub
/// # Retained as the oracle, not as production SQL (0.15.17, [D-259])
///
/// Nothing emits this any more — [`ancestry_values`] does, with the same three
/// columns computed by [`resolve`] instead of by SQLite. It is compiled for
/// tests only, and it stays because deleting it would leave
/// [`resolve`] pinned against a *restatement* of the rule rather than against
/// the implementation it replaced. `the_rust_walk_agrees_with_the_cte` is the
/// differential test; this is the half of it that cannot be wrong by the same
/// mistake.
///
/// [D-259]: ../../docs/architecture/s13-decision-register.md#d-259
pub
/// The `(edge key, lineage)` pairs whose projected row is *younger* than the
/// cutoff, and therefore cannot be shown to the reader.
///
/// One row here means: this ancestor holds a belief about this edge, and it
/// wrote that belief after the reader's line diverged. `links_current` has
/// overwritten whatever it believed before — the sync trigger's `DO UPDATE`
/// carries `recorded_at` forward — so the pre-fork version has to come from the
/// log. [`links_cut_cte`] is what goes and gets it.
///
/// **`entity_id` is composed here in the same order the log triggers compose
/// it**, `source|target|type|valid_from`, because that is the key the fold
/// joins on. It is a second spelling of a format the schema owns, and the thing
/// that keeps it honest is that a mismatch cannot be quiet: the join would
/// match nothing, every churned key would drop out of both arms, and
/// `branch_read_tests`' retire and reweight cases would go red together.
///
/// The `cutoff IS NOT NULL` clause is what makes this empty for a read on the
/// root — `main` has no ancestors and no cutoff, so a forked database still
/// pays nothing here to read its own trunk.
pub
/// `links_current` as each lineage on the ancestry was entitled to see it.
///
/// The hybrid §15.3 did not have a name for, entered there as option (4). Two
/// arms over one predicate:
///
/// * rows whose lineage may still show them directly — the reader's own
/// (`cutoff IS NULL`) and every ancestor row recorded at or before its cutoff;
/// * for the rest, the last log entry that lineage wrote at or before its
/// cutoff, which is what `links_current` held for that key at the fork.
///
/// A key the ancestor first asserted *after* the cutoff contributes nothing
/// from either arm, and that is correct rather than a gap: the branch's line
/// diverged before that edge existed, so there is no pre-fork row to resurrect.
/// The fold returning empty is the answer.
///
/// **`UNION ALL` is sound because the arms partition, not because duplicates
/// are harmless.** They split `links_current ⋈ lineage` on `recorded_at <=
/// cutoff`; see [`churned_cte`] for why the churned set is derived from the
/// projection and not from the log, which is the same point from the other
/// side.
///
/// The column list matches `links_current`'s and `links_at_tx`'s exactly, which
/// is what lets [`visible_cte`] reduce any of the three without knowing which.
///
/// # The log arm's join order, which is four words and was worth 1,387x
/// (0.15.29, [D-272])
///
/// The `CROSS JOIN` is not a different join. It is the same inner join with
/// the loops nailed down, which is what `CROSS` means to SQLite and the only
/// thing it means: *do not reorder this*.
///
/// Left to choose, the planner drove from `transaction_log` on the one
/// equality it could see — `table_name = 'links'` — and inlined `churned` as
/// the inner loop, where the key narrowing and the `recorded_at > cutoff`
/// bound both fell out of the access path:
///
/// ```text
/// SEARCH transaction_log USING INDEX idx_txlog_fold_partition (table_name=?)
/// SEARCH lc USING COVERING INDEX idx_lc_lineage_cut (branch_id=?)
/// ```
///
/// One column bound on the inner scan, so the whole of that lineage's
/// `links_current` per row of the links log, per execution of this relation.
/// [`crate::connection`]'s write path executes it **once per asserted row**,
/// which is how a 200-edge batch on a fork of a 2,000-edge trunk came to cost
/// **68 s against the trunk's 26 ms** — and 20x that for a 4x trunk, because
/// the shape is a product of two things that both grow.
///
/// With `churned` driving, the log is reached on three bound columns instead
/// of one:
///
/// ```text
/// SEARCH lc USING COVERING INDEX idx_lc_lineage_cut (branch_id=? AND recorded_at>?)
/// SEARCH transaction_log USING INDEX idx_txlog_fold_partition
/// (table_name=? AND entity_id=? AND branch_id=?)
/// ```
///
/// **`idx_txlog_fold_partition` is not the villain and did not move.** Its
/// leading `table_name` is what the planner grabbed, but the index serves this
/// arm better than the `idx_txlog_entity (entity_id=?)` seek the arm had
/// before [D-254] existed — three equality columns rather than one. It was
/// being used with a third of itself bound.
///
/// **Why reordering cannot change the answer.** `links_current`'s primary key
/// is `(source_id, target_id, edge_type, valid_from, branch_id)` and
/// [`churned_cte`] composes `entity_id` from the first four, so `churned` is
/// unique on the `(entity_id, branch_id)` pair this join matches. The join is
/// one-to-many in exactly one direction whichever side drives, so the window
/// below sees the same input rows and `ROW_NUMBER` picks the same one.
///
/// **This arm is not only the write path's.** `key` is `None` for every
/// branched *current-belief read*, where the churned set is the whole of it
/// rather than one edge, and the same plan was there. Measured through the
/// public API on a fixture with deliberate post-fork churn
/// (`examples/resolved_read_probe.rs`, best of 40, 400 concepts):
///
/// ```text
/// depth 1 depth 8
/// edges(plan), current belief 5.6 -> 1.3 ms 13.6 -> 1.3 ms
/// traverse, depth 6 5.4 -> 1.2 ms 13.7 -> 1.4 ms
/// edges(plan), recorded instant 1.87 -> 1.90 2.43 -> 2.44 (no arm here)
/// edges(plan) on the trunk 0.33 -> 0.33 0.33 -> 0.33 [control]
/// ```
///
/// The branched read **stopped growing with fork depth**, which is the durable
/// half of that table: depth multiplies the ancestry, the ancestry multiplied
/// the churned set, and the churned set was being re-derived per log row.
///
/// The gate is `the_log_arm_is_driven_by_the_churned_set` below, and it pins
/// the bound column rather than a millisecond — [D-055] is why.
///
/// [D-254]: ../../docs/architecture/s13-decision-register.md#d-254
/// [D-272]: ../../docs/architecture/s13-decision-register.md#d-272
/// [D-055]: ../../docs/architecture/s13-decision-register.md#d-055
pub
/// The slots the write path binds, which are fixed by its two statements
/// rather than by a layout type (0.14.8, D-225).
///
/// `?1` source, `?2` target, `?3` edge type, `?4` the `valid_from` each tail
/// selects on, `?5` the writing lineage, and for the retirement `?6` the new
/// `valid_to` and `?7` the stamp. Both callers bind all of them positionally
/// at one site each.
const WRITE_KEY: KeySlots = KeySlots ;
const WRITE_BRANCH_SLOT: usize = 5;
/// Where the guard's ancestry block starts: after the five it already binds.
///
/// The two write statements have different layouts, so the slot is passed to
/// [`write_resolution`] rather than named once here — the guard binds five
/// (`key`, `valid_from`, `branch`) and the retirement binds seven.
const GUARD_ANCESTRY_SLOT: usize = 6;
/// Where the retirement's ancestry block starts: after `valid_to` and `stamp`.
const RETIRE_ANCESTRY_SLOT: usize = 8;
/// What the write path has decided before any SQL exists.
///
/// Current belief always: the guard asks what this lineage believes *now*, and
/// an assertion is made against now. There is no recorded slot to name.
/// Overlap candidates as the writing lineage can see them (0.14.8, §15.4,
/// [D-225]; lowered 0.15.8, W13.3, [D-250]).
///
/// # Why the write path needs a resolution at all
///
/// [`crate::connection`]'s overlap guard reads `links_current` for the edge key
/// being asserted and refuses an assertion whose valid-time interval overlaps
/// one already recorded (defect AA, D-060). Until 0.14.8 every row in the table
/// was `main`'s, so reading the key with no lineage predicate was exact. The
/// moment a second lineage can write, the same statement is wrong in **both
/// directions at once**: a branch would be refused for overlapping its parent's
/// belief that it is entitled to supersede, and the trunk would be refused for
/// overlapping a branch's belief it cannot even see. An unfiltered read is not
/// a conservative approximation of a filtered one here; it is a different
/// question.
///
/// Adding `AND branch_id = ?` would fix the trunk direction and leave the
/// branch one wrong the other way — a branch would then be checked against
/// *only its own* rows and could assert `[10,20)` over an inherited `[5,15)`,
/// putting two overlapping intervals into its own view. That is defect AA
/// reintroduced across lineages, and it is the shape
/// `trg_links_single_open`'s v12 comment left open as "§15.4's write-path
/// question": the trigger sees one row and cannot answer it. This is the
/// answer. **What a lineage may not overlap is what that lineage can see**,
/// which is the read's definition and now the write's.
///
/// # It was a second spelling of that definition until 0.15.8
///
/// The narrowing was real and is unchanged — [`churned_cte`] and
/// [`links_cut_cte`] are written for a traversal and scan `links_current`
/// whole, so calling them per assertion would make a branched bulk write
/// O(rows) per row, and pushing the key into the base scans turns each arm
/// into a seek on `idx_lc_open_interval`. What was not real was the *copy*:
/// a `key_visibility_cte` holding its own `lineage`, its own churned set, its
/// own two-arm hybrid and its own nearest-lineage window, four relations that
/// had to keep agreeing with four in [`crate::graph::plan`] and were kept
/// honest only by `branch_write_tests` asserting the two answers match on one
/// fixture. [D-227](../../docs/architecture/s13-decision-register.md#d-227) is
/// four releases of what happens when a reader spells its own. The key is a
/// [`KeySlots`] on [`Resolution`] now, and this function is the lowering plus
/// one line.
///
/// # What that cost, and bought, on `examples/edge_write_probe`
///
/// Best of 500 `assert_edge` calls, three runs each, release build:
///
/// ```text
/// 0.15.7 0.15.8
/// trunk 0.0958 0.0966 ms unchanged
/// forked 0.1044 0.0975 ms -6.6%
/// branch 0.1059 0.1091 ms +3.0%
/// ```
///
/// The forked trunk gains because it stopped taking the resolved form: it was
/// exact there only because a root's ancestry is itself, and D-248's C-24
/// repair is what lets [`crate::graph::LineageShape`] tell a root apart from a
/// branch at all. It now lowers to a two-predicate lookup on `links_current`.
///
/// The branch loses because the shared [`visible_cte`] joins `lineage` to order
/// by `dist`, where the deleted `key_visibility_cte` carried `dist` through its
/// own relations and needed no join. Buying that 3% back means giving the keyed
/// spelling its own `dist` column in three functions — a second shape for the
/// hybrid, decided by the caller — which is the divergence this release exists
/// to remove, over a join against a materialised ancestry of two rows.
///
/// **The `churned` base scan is unchanged and was never the cost.** It planned
/// as `SEARCH lc USING COVERING INDEX idx_lc_lineage_cut (branch_id=? AND
/// recorded_at>?)` in 0.15.7 and it plans that way now: SQLite inlines the
/// key-narrowed CTE into each use, so the equalities and the `recorded_at`
/// range meet in one scan either way. Splitting them apart with
/// `AS MATERIALIZED` does restore the key seek, and costs more than it saves —
/// the log arm then loses `SEARCH transaction_log USING INDEX idx_txlog_entity
/// (entity_id=?)` and scans the whole log, because a materialised `churned` is
/// no longer a small driving set the planner can see through. It was measured
/// and not taken.
///
/// **The middle sentence of that paragraph stopped being true at 0.15.12 and
/// was true again at 0.15.29** ([D-272]). `idx_txlog_fold_partition` ([D-254])
/// gave the planner a reason to drive from `transaction_log` instead, and the
/// churned base scan then planned as `idx_lc_lineage_cut (branch_id=?)` —
/// **one** column, not the two the paragraph reports — because it had become
/// an inner loop. The paragraph is left as written because what it says about
/// 0.15.7 and 0.15.8 is still what happened; what it could not know is that
/// this plan was a *choice* the planner was free to revisit, and it did. It is
/// nailed down now: see [`links_cut_cte`]'s `CROSS JOIN`.
///
/// The refusal of `AS MATERIALIZED` survives that and is now refused twice
/// over. Re-measured against the current schema
/// (`examples/branch_write_guard_probe.rs`, per asserted row): materialised
/// alone is **0.158 ms** at a 2,000-edge trunk and **0.565 ms** at 8,000,
/// against the forced join order's **0.012** and **0.016** — it fixes the
/// symptom partially and the growth not at all, because a materialised
/// `churned` is still the inner loop.
///
/// # The predicate set, which is three equalities and nothing else
///
/// `valid_from <> ?4` excludes the row being re-asserted: re-assertion at the
/// same `valid_from` is Doctrine III's ordinary case and is settled by the
/// primary key and the single-open trigger, not by this guard.
///
/// **The "and nothing else" was measured, not assumed**, and it is the half of
/// this statement a lowering must not quietly improve. The first version added
/// `AND valid_from < :new_valid_to`, a provably safe narrowing — overlap
/// requires `max(start) < min(end)`, so an interval starting at or after the
/// new one's end cannot overlap it. It cost **9.8 ms on a 90-edge chunk into a
/// 2,000-edge hub**, because it walked the planner straight into D-059's trap:
///
/// ```text
/// with the range: SEARCH links_current USING COVERING INDEX
/// idx_lc_traversal_cover (source_id=? AND valid_from<?)
/// without it: SEARCH links_current USING COVERING INDEX
/// idx_lc_open_interval (source_id=? AND target_id=? AND edge_type=?)
/// ```
///
/// `idx_lc_traversal_cover` leads on `(source_id, valid_from, …)` and contains
/// every column that query mentions, so with a `valid_from` range available it
/// wins as a covering index while binding **one** equality column — and the
/// guard scans the source's entire out-degree. Same shape as the defect D-059
/// diagnosed in `trg_links_single_open`, reintroduced by an optimisation one
/// wave after it was fixed. Three equalities make it a point lookup that
/// `idx_lc_open_interval` serves exactly, and the rows it returns are a version
/// count rather than an out-degree. **A narrowing predicate is not free if it
/// changes the plan** — which is also why [`KeySlots`] pushes its equalities
/// into the base scans rather than appending them to the resolved relation,
/// and why `index_plan_tests` pins this statement's plan on every shape.
///
/// [D-225]: ../../docs/architecture/s13-decision-register.md#d-225
/// [D-250]: ../../docs/architecture/s13-decision-register.md#d-250
pub
/// The row a branch is retiring, which may belong to an ancestor.
///
/// Retirement on a branch is **shadow retirement**: the branch writes its own
/// row at the ancestor's key carrying a closed interval, the read prefers it by
/// `dist`, and the ancestor's row is untouched. [`visible_cte`]'s rustdoc has
/// described this write since 0.14.4; this is it. Closing the ancestor's own
/// row is the parent corruption
/// [Doctrine III](../../docs/architecture/s0-s3-foundations.md#doctrine-iii)
/// forbids, and it is not merely avoided by policy — `links` is append-only and
/// there is no statement in the crate that could do it.
///
/// `?6` is the new `valid_to`, `?7` the stamp. `weight` and `properties` are
/// carried from the visible row rather than restated, which is what makes this
/// a retirement rather than a new assertion that happens to be closed — and it
/// is the reason a keyed resolution carries `properties` at all (see
/// [`KeySlots`]).
pub
/// What one lineage believes and another does not, in **one** statement
/// (0.14.11, §15.4, [D-228]).
///
/// # Why one statement rather than two reads and a difference in Rust
///
/// Not for the round trip. A diff is a *comparison*, and two statements
/// against [`Database::read_conn`](crate::Database::read_conn) are two
/// snapshots — a write landing between them can make the answer report a
/// difference that never existed at any instant. The obvious repair, a read
/// transaction, is not available: `read_conn()` is public and shared, so
/// beginning one inside a library call would change what every other holder of
/// that connection sees. One statement gets the single snapshot for free.
///
/// # Why the CTEs are tagged rather than copied
///
/// This resolves two lineages, so it needs two of each of the four CTEs, and
/// SQLite has one namespace per `WITH` list. Hence the `tag` parameter on
/// [`ancestry_cte`] and its three companions rather than a second spelling of
/// the hybrid — which [D-227](../../docs/architecture/s13-decision-register.md#d-227)
/// declined for `query_as_of_edges_on` and would be the same mistake here.
/// Every single-lineage caller passes `""` and emits the text it always did.
///
/// # What it compares, and what it does not
///
/// A `LEFT JOIN` on the **edge key** — `(source, target, type, valid_from)` —
/// and a row survives when `b` holds no belief about that key, or holds one
/// whose interval or weight differs. So a retirement is reported: `a`'s row is
/// the closed one, `b`'s is open, and they differ. That is the case a
/// valid-time filter would have hidden, which is why there is no `ts` here at
/// all — a diff filtered to an instant cannot see the one divergence that is
/// *about* an instant having passed.
///
/// **`properties` is not compared**, and that is a limit rather than an
/// oversight: no read surface in the crate returns edge properties —
/// `EdgeAssertion::properties` writes them and nothing reads them back — so a
/// diff reporting a change there would be the only reader resolving a column,
/// and it would name a difference the caller has no way to look at. It is the
/// first thing to widen if edge properties ever become readable.
///
/// Float equality on `weight` is deliberate. The question is whether `b` holds
/// the *same belief*, and a belief is a stored value; an epsilon here would
/// invent a tolerance the ledger does not have and would make `diff(a, b)`
/// disagree with what a traversal on either lineage shows.
///
/// Slots: `?1` the lineage being asked about, `?2` the one it is compared to.
///
/// [D-228]: ../../docs/architecture/s13-decision-register.md#d-228
pub
/// One row per edge key, from the nearest lineage that holds it.
///
/// `source` is the relation to resolve — [`links_cut_cte`] under current
/// belief, or the `links_at_tx` fold when the traversal names a transaction-time
/// instant. Both expose the same columns under the same names, which is what
/// lets this be written once, and both have already applied the ancestry's
/// cutoffs before this sees them.
///
/// **The partition is the edge key and not the edge.** Two lineages asserting
/// the same `(source, target, type)` at *different* `valid_from` are two
/// assertions in valid time and stay two rows; two lineages asserting at the
/// same `valid_from` are one edge believed twice and resolve to one. That is
/// also what makes shadow-retirement work: a branch writes its own row at the
/// ancestor's key with a closed interval, the resolution prefers it, and the
/// edge is gone from that lineage's view while the ancestor's row is untouched.
/// Closing the ancestor's own row is the parent corruption
/// [Doctrine III](../../docs/architecture/s0-s3-foundations.md#doctrine-iii)
/// forbids, and shadowing is the only retirement across lineages that does not
/// commit it.
///
/// **`ORDER BY g.dist` is a total order over the surviving rows**, because each
/// source contributes at most one row per `(edge key, lineage)` and each
/// lineage appears in `lineage` once. See [`ancestry_cte`] for why ordering by
/// `recorded_at` instead would pick the same row.
pub