macrame-db 0.17.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
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
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
#[path = "common/harness.rs"]
mod harness;
#[path = "common/plan_fixture.rs"]
mod plan_fixture;
#[path = "common/v7_schema.rs"]
mod v7_schema;

#[path = "common/v11_schema.rs"]
mod v11_schema;

use harness::TestHarness;
use macrame::error::DbError;
use macrame::schema::ddl;
use macrame::schema::SCHEMA_VERSION;
use plan_fixture::populated_without_statistics;
use v7_schema::seeded_v7;

const TS: &str = "2026-01-01T00:00:00.000000Z";
const OPEN: &str = "9999-12-31T23:59:59.999999Z";

/// Open the harness database and hand back a connection.
async fn connect(harness: &TestHarness) -> libsql::Connection {
    libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap()
        .connect()
        .unwrap()
}

async fn user_version(conn: &libsql::Connection) -> u32 {
    conn.query("PRAGMA user_version", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap()
}

/// Assert `run` refused, and hand back the reason so the caller can check that
/// the message names the actual problem rather than being merely non-empty.
fn refusal_reason(err: DbError) -> String {
    match err {
        DbError::Migration { to, reason } => {
            // `to` is the version the failure was trying to *reach*, which for a
            // refusal partway up the ladder is that rung's target and not the
            // top. This asserted equality with SCHEMA_VERSION until 0.9.0, where
            // it held only because the last rung happened to be the top one —
            // adding v8 → v9 made the v7 → v8 orphan refusal report 8 and broke
            // a helper that was never testing the ladder in the first place.
            assert!(
                to <= SCHEMA_VERSION,
                "a refusal cannot name a version above the ladder's top: {to}"
            );
            reason
        }
        other => panic!("expected DbError::Migration, got {other:?}"),
    }
}

#[tokio::test]
async fn fresh_database_reaches_the_baseline_version() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);
    // The stamp is worth nothing on its own -- confirm the canonical-form CHECK
    // that v2 exists to deliver actually landed.
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) \
         VALUES ('c1', 'T', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
        (),
    )
    .await
    .expect_err("second-precision timestamps must be rejected at v2");
}

/// Re-opening must be a no-op, not a re-application. The old runner re-ran every
/// `CREATE ... IF NOT EXISTS` on every open; if that behaviour returns, data
/// written between opens is what pays for it.
#[tokio::test]
async fn run_is_idempotent_and_preserves_data() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) \
         VALUES ('c1', 'T', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .unwrap();

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);
    let surviving: i64 = conn
        .query("SELECT COUNT(*) FROM concepts", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(surviving, 1, "second run must not disturb existing rows");
}

/// Operating on a schema written by a future build is how a ledger loses
/// history: the unknown columns are invisible to every query but still there.
#[tokio::test]
async fn refuses_a_database_from_a_newer_build() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    conn.execute(&format!("PRAGMA user_version = {}", SCHEMA_VERSION + 7), ())
        .await
        .unwrap();

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains(&format!("v{}", SCHEMA_VERSION + 7)),
        "refusal should name the version found: {reason}"
    );
}

/// The legacy-free policy, enforced: a pre-0.5.4 database stamped v1 has no rung
/// leading out of it and must be refused by name, not silently accepted because
/// its tables happen to share their names with the current ones.
#[tokio::test]
async fn refuses_a_pre_canonical_v1_database() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    conn.execute("PRAGMA user_version = 1", ()).await.unwrap();

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains("v1") && reason.contains("no migration path"),
        "refusal should identify the legacy schema and say there is no path: {reason}"
    );
}

/// `user_version` defaults to 0, so an unrelated SQLite file looks fresh. Adding
/// nine triggers to somebody else's database is not a recoverable mistake.
#[tokio::test]
async fn refuses_an_unstamped_database_that_is_not_empty() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    conn.execute("CREATE TABLE somebody_elses_data (x)", ())
        .await
        .unwrap();

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains("unrelated"),
        "refusal should explain what it is protecting: {reason}"
    );
    assert_eq!(
        user_version(&conn).await,
        0,
        "a refused open must not stamp the file"
    );
}

/// The baseline either lands whole or not at all: a partial schema stamped as
/// complete is worse than no schema, because the stamp suppresses the retry.
#[tokio::test]
async fn a_refused_run_leaves_no_partial_schema() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    conn.execute("CREATE TABLE somebody_elses_data (x)", ())
        .await
        .unwrap();

    let _ = macrame::schema::run_migrations(&conn).await.unwrap_err();

    let macrame_objects: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master WHERE name IN \
             ('concepts', 'links', 'links_current', 'transaction_log')",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(macrame_objects, 0);
}

/// Verification exists to catch DDL that no-ops instead of creating, so the
/// baseline must actually leave every declared object behind.
///
/// Checked by *name*, and the counts are derived from the DDL arrays rather
/// than written as literals. The previous version asserted `4 tables, 9
/// triggers, 4 indices` as constants and failed the moment D-041 added a fifth
/// table — which is D-038's mistake reappearing in the test that guards it: a
/// count treats any addition as breakage and tells you a number, while a
/// name check tells you which object is missing. The 0.5.4 `verify()` was
/// changed for exactly this reason and the test had not followed.
#[tokio::test]
async fn the_baseline_leaves_every_declared_object_behind() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    let mut rows = conn
        .query(
            "SELECT type, name FROM sqlite_master \
             WHERE type IN ('table','trigger','index') AND name NOT LIKE 'sqlite_%'",
            (),
        )
        .await
        .unwrap();
    let mut present: Vec<(String, String)> = Vec::new();
    while let Some(row) = rows.next().await.unwrap() {
        present.push((row.get(0).unwrap(), row.get(1).unwrap()));
    }
    let has = |kind: &str, name: &str| {
        present
            .iter()
            .any(|(k, n)| k == kind && n.eq_ignore_ascii_case(name))
    };

    for table in [
        "concepts",
        "links",
        "links_current",
        "transaction_log",
        "analytics_annotations",
    ] {
        assert!(has("table", table), "missing table {table}: {present:?}");
    }

    let triggers = present.iter().filter(|(k, _)| k == "trigger").count();
    assert_eq!(
        triggers,
        ddl::CREATE_TRIGGERS.len(),
        "trigger count drifted from CREATE_TRIGGERS: {present:?}"
    );

    let indices = present.iter().filter(|(k, _)| k == "index").count();
    assert_eq!(
        indices,
        ddl::CREATE_INDICES.len(),
        "index count drifted from CREATE_INDICES: {present:?}"
    );
}

/// The v2 → v3 rung must reach v3 from a database that stopped at v2 — the
/// first time the ladder has had more than one rung, so the first time `run`'s
/// loop does anything but take the baseline.
#[tokio::test]
async fn a_v2_database_climbs_to_v3_and_gains_the_annotations_table() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    // Build a v2 database: the baseline minus what v3 added, stamped v2.
    // The four ledger tables as v11 declared them, not as today's constants
    // do. Since v12 the live `CREATE`s reference a `branches` table this
    // fixture has no business owning, and carry a `branch_id` the rung under
    // test is supposed to add — `tests/common/v11_schema.rs` says why at
    // length.
    for table in v11_schema::tables_v11() {
        conn.execute(&table, ()).await.unwrap();
    }
    for index_ddl in v11_schema::indices_v11() {
        // Every remaining index has its table *and its columns* in this
        // fixture. Through v7 one did not have its table —
        // `idx_annotations_label`, which is why this loop used to swallow its
        // result — and v8 dropped it (D-118). v14 is the column version of the
        // same problem and is excluded by `indices_v11` rather than swallowed,
        // because swallowing errors is how a fixture stops testing anything.
        conn.execute(index_ddl, ()).await.unwrap();
    }
    for trigger_ddl in v11_schema::triggers_v11() {
        conn.execute(trigger_ddl, ()).await.unwrap();
    }
    conn.execute("PRAGMA user_version = 2", ()).await.unwrap();

    macrame::schema::run_migrations(&conn).await.unwrap();

    let version: u32 = conn
        .query("PRAGMA user_version", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(version, SCHEMA_VERSION);

    conn.query(
        "SELECT concept_id, label, value, computed_at FROM analytics_annotations",
        (),
    )
    .await
    .expect("the rung must create analytics_annotations");
}

/// The v5 → v6 rung reaches v6 from a database that stopped at v5, and the
/// index it adds is actually there afterwards (D-059).
///
/// A v5 database is the baseline minus one index, so it is built by laying the
/// baseline and dropping that index rather than by reconstructing v5's DDL by
/// hand — a hand-written copy of an old schema is a second description that can
/// drift from the one the rung is written against.
#[tokio::test]
async fn a_v5_database_climbs_to_v6_and_gains_the_open_interval_index() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();
    // Wound back before the stamp is rolled, because the ladder is not
    // re-entrant: a v12 database re-stamped v5 does not replay history, it
    // meets rungs written for shapes it no longer has. `wind_back_to_v11` is
    // what makes "the baseline minus one index" true again rather than merely
    // claimed — see `tests/common/v11_schema.rs`.
    v11_schema::wind_back_to_v11(&conn).await;
    conn.execute("DROP INDEX idx_lc_open_interval", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 5", ()).await.unwrap();

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let found: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master \
             WHERE type = 'index' AND name = 'idx_lc_open_interval'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(found, 1, "the rung must create idx_lc_open_interval");
}

/// v10 → v11: the two archive indexes on `links`, and the plan they buy.
///
/// Presence is asserted, but presence alone is the weak form the gate on
/// [`a_version_bump_must_bring_its_own_rung_test`] warns against — a rung that
/// creates an index nothing seeks on passes it, and that is exactly D-089's
/// failure. So the plan is asserted too: the archiving read must go from a full
/// scan of the ledger to a seek, in the same test that stamps the version.
///
/// This is the first rung to index a **frozen** table (D-036, D-151). See
/// `add_links_archive_indices` for why that is the permitted additive case
/// rather than an exception.
#[tokio::test]
async fn a_v10_database_climbs_to_v11_and_the_archive_read_stops_scanning_links() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();
    v11_schema::wind_back_to_v11(&conn).await;
    conn.execute("DROP INDEX idx_links_recorded_at", ())
        .await
        .unwrap();
    conn.execute("DROP INDEX idx_links_target", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 10", ()).await.unwrap();

    // The archiving SELECT, reproduced from `LINKS_ARCHIVABLE`. Bounded against
    // drift by `index_plan_tests`, which holds the same query with an
    // `include_str!` check on `archive.rs`; this copy exists because the rung
    // has to be measured on both sides of itself and the registry only sees the
    // finished schema.
    const ARCHIVING_READ: &str = "SELECT source_id FROM links WHERE recorded_at < ?1          AND (valid_to <> '9999-12-31T23:59:59.999999Z' AND valid_to <= ?1)";

    let before = plan_string(&conn, ARCHIVING_READ).await;
    assert!(
        before.contains("SCAN links"),
        "the fixture is not starting from the v10 plan — expected a full scan          of `links`, got: {before}"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    for name in ["idx_links_recorded_at", "idx_links_target"] {
        let found: i64 = conn
            .query(
                "SELECT COUNT(*) FROM sqlite_master                  WHERE type = 'index' AND name = ?1",
                libsql::params![name],
            )
            .await
            .unwrap()
            .next()
            .await
            .unwrap()
            .unwrap()
            .get(0)
            .unwrap();
        assert_eq!(found, 1, "the rung must create {name}");
    }

    let after = plan_string(&conn, ARCHIVING_READ).await;
    assert!(
        after.contains("SEARCH links USING INDEX idx_links_recorded_at"),
        "the rung created the index and the planner did not take it. An index          with no reader is an index write per ledger insert, forever (D-089).          Plan: {after}"
    );
}

/// `EXPLAIN QUERY PLAN` for `sql`, joined into one line.
async fn plan_string(conn: &libsql::Connection, sql: &str) -> String {
    let mut rows = conn
        .query(&format!("EXPLAIN QUERY PLAN {sql}"), ())
        .await
        .unwrap();
    let mut lines = Vec::new();
    while let Some(r) = rows.next().await.unwrap() {
        lines.push(r.get::<String>(3).unwrap_or_default());
    }
    lines.join(" | ")
}

/// The ladder's top, asserted once rather than inside whichever rung test was
/// written last.
///
/// This used to live in the v5 → v6 test as `assert_eq!(SCHEMA_VERSION, 6)`,
/// where it did its job — the T2.1 rung tripped it immediately — but it made a
/// version bump look like a failure of the *v6* rung, which it is not. Hoisted
/// so the message names the actual obligation.
#[test]
fn a_version_bump_must_bring_its_own_rung_test() {
    assert_eq!(
        SCHEMA_VERSION, 19,
        "SCHEMA_VERSION moved. Add a test for the new rung — one that starts \
         from a database at the previous version and asserts what the rung is \
         *for*, not merely that `run` reached the top."
    );
}

/// The v12 body of the `branches` delete guard: unconditional, with no marker
/// probe. Pinned as text for `CONCEPTS_GUARD_DELETE_V8`'s reason — an old
/// schema described by hand is a second description that drifts, and this one
/// is three lines and will never change again.
const V12_BRANCHES_GUARD_DELETE: &str = "
    CREATE TRIGGER trg_branches_frozen_delete
    BEFORE DELETE ON branches
    BEGIN
        SELECT RAISE(ABORT, 'macrame: branch records are append-only');
    END;
";

/// Register `name` as a child of the trunk, by raw insert.
async fn register_branch(conn: &libsql::Connection, name: &str) {
    conn.execute(
        "INSERT INTO branches (branch_id, parent_id, forked_at, created_at) \
         VALUES (?1, 'main', ?2, ?2)",
        libsql::params![name, TS],
    )
    .await
    .unwrap();
}

/// Delete a lineage record inside a declared archive session, and say whether
/// the guard allowed it.
async fn delete_in_session(conn: &libsql::Connection, name: &str) -> bool {
    conn.execute("CREATE TABLE macrame_archive_session (x)", ())
        .await
        .unwrap();
    let outcome = conn
        .execute(
            "DELETE FROM branches WHERE branch_id = ?1",
            libsql::params![name],
        )
        .await;
    conn.execute("DROP TABLE macrame_archive_session", ())
        .await
        .unwrap();
    outcome.is_ok()
}

/// v12 → v13: the `branches` delete guard becomes marker-gated (0.14.13,
/// §15.4, D-230).
///
/// What the rung is *for*, not that `run` reached the top: a v12 guard refuses
/// the delete `archive_branch` has to perform, and after the rung the same
/// delete inside the same session succeeds. Both halves are measured, because
/// the failure this rung exists to prevent is the one `CREATE TRIGGER IF NOT
/// EXISTS` produces — the baseline re-issued, the old body kept, and nothing
/// anywhere saying so (D-126).
///
/// The last assertion is the one that keeps the rung honest. Gating a guard and
/// removing it look identical from inside a session; they differ only outside
/// one, which is where `branches` is append-only and must stay so.
#[tokio::test]
async fn a_v12_database_climbs_to_v13_and_its_branches_guard_learns_the_marker() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();

    // Wind the guard back to its v12 shape and the stamp with it.
    conn.execute("DROP TRIGGER trg_branches_frozen_delete", ())
        .await
        .unwrap();
    conn.execute(V12_BRANCHES_GUARD_DELETE, ()).await.unwrap();
    conn.execute("PRAGMA user_version = 12", ()).await.unwrap();

    register_branch(&conn, "before").await;
    assert!(
        !delete_in_session(&conn, "before").await,
        "the v12 guard is unconditional: it refuses inside a declared archive \
         session exactly as it does outside one. That is the state every \
         database written before 0.14.13 is in, and the reason this rung is not \
         a re-issue of the baseline"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    assert!(
        delete_in_session(&conn, "before").await,
        "after the rung the same delete inside the same session must succeed — \
         this is the capability `archive_branch` is built on"
    );

    register_branch(&conn, "after").await;
    let outside = conn
        .execute("DELETE FROM branches WHERE branch_id = 'after'", ())
        .await;
    assert!(
        outside.is_err(),
        "the rung gates the guard; it must not remove it. `branches` is still \
         append-only to every writer that has not declared a session"
    );
}

/// A v12 guard body under a v13 stamp is refused at open, by name.
///
/// The other half of D-126's repair, which is why this is a separate case: the
/// rung replaces the body, and `verify` is what makes a database that somehow
/// skipped it say so. Without the name in `DELETE_GUARDS` this file opens
/// cleanly and fails at the first abandonment with a trigger abort, which names
/// a trigger rather than the problem.
#[tokio::test]
async fn a_v13_stamp_over_a_v12_branches_guard_is_refused_at_open() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();

    conn.execute("DROP TRIGGER trg_branches_frozen_delete", ())
        .await
        .unwrap();
    conn.execute(V12_BRANCHES_GUARD_DELETE, ()).await.unwrap();
    // The stamp is left at the top: this is the database that claims to have
    // climbed the ladder and did not.

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains("trg_branches_frozen_delete"),
        "the refusal must name the guard whose body is stale: {reason}"
    );
}

/// The v6 → v7 rung rebuilds `links` with the weight constraint, keeps every
/// row, and puts the four triggers back (T2.1, D-082).
///
/// The only rung on the ladder that rewrites a ledger table, so it is the only
/// one where "did the data survive" is a real question. Three things have to
/// hold afterwards and each has failed in some version of this migration
/// somewhere: the rows are all still there, the triggers that were dropped with
/// the old table are back, and the constraint actually bites.
#[tokio::test]
async fn a_v6_database_climbs_to_v7_and_gains_the_weight_check() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    // A v6 database is the current baseline with an unconstrained `links`, so it
    // is built by laying the baseline and rebuilding that one table without the
    // CHECK — for the reason the v5 test gives: a hand-written copy of an old
    // schema is a second description that drifts.
    macrame::schema::run_migrations(&conn).await.unwrap();
    v11_schema::wind_back_to_v11(&conn).await;
    for stmt in [
        "ALTER TABLE links RENAME TO links_old",
        "CREATE TABLE links (
            source_id   TEXT NOT NULL REFERENCES concepts(id),
            target_id   TEXT NOT NULL REFERENCES concepts(id),
            edge_type   TEXT NOT NULL,
            valid_from  TEXT NOT NULL,
            recorded_at TEXT NOT NULL,
            valid_to    TEXT NOT NULL DEFAULT '9999-12-31T23:59:59.999999Z',
            weight      REAL NOT NULL DEFAULT 1.0,
            properties  TEXT NOT NULL DEFAULT '{}',
            PRIMARY KEY (source_id, target_id, edge_type, valid_from, recorded_at)
        )",
        "DROP TABLE links_old",
    ] {
        conn.execute(stmt, ()).await.unwrap();
    }
    for trigger_ddl in v11_schema::triggers_v11() {
        conn.execute(trigger_ddl, ()).await.unwrap();
    }
    conn.execute("PRAGMA user_version = 6", ()).await.unwrap();

    for id in ["c0", "c1"] {
        conn.execute(
            "INSERT INTO concepts (id, title, valid_from, recorded_at) \
             VALUES (?1, 'N', ?2, ?2)",
            libsql::params![id, TS],
        )
        .await
        .unwrap();
    }
    for (etype, weight) in [("A", 1.0), ("B", 0.0), ("C", 2.5)] {
        conn.execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, \
             weight, properties, recorded_at) \
             VALUES ('c0','c1',?1,?2,'9999-12-31T23:59:59.999999Z',?3,'{}',?2)",
            libsql::params![etype, TS, weight],
        )
        .await
        .unwrap();
    }

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let rows: i64 = conn
        .query("SELECT COUNT(*) FROM links", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(rows, 3, "the rebuild lost rows");

    let triggers: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master \
             WHERE type = 'trigger' AND tbl_name = 'links'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(
        triggers, 4,
        "DROP TABLE took the triggers with it and the rung did not put them back"
    );

    for (label, weight) in [("negative", "-1.0"), ("text", "'abc'")] {
        let refused = conn
            .execute(
                &format!(
                    "INSERT INTO links (source_id, target_id, edge_type, valid_from, \
                     valid_to, weight, properties, recorded_at) \
                     VALUES ('c0','c1','Z','{TS}','9999-12-31T23:59:59.999999Z',\
                     {weight},'{{}}','{TS}')"
                ),
                (),
            )
            .await;
        assert!(refused.is_err(), "a {label} weight survived the rung");
    }
}

// ---------------------------------------------------------------------------
// The v7 → v8 rung (B4, D-118, D-119)
// ---------------------------------------------------------------------------

// The v7 shape of `concepts`, its FTS index, the triggers that went with it,
// and `seeded_v7` used to live here. They moved to
// `tests/common/v7_schema.rs` in 0.8.0 so that
// `examples/v8_migration_scale_probe.rs` could measure what the rung COSTS
// against the same pinned fixture this file checks it is CORRECT against,
// rather than against a second copy that would drift (D-124).

async fn count(conn: &libsql::Connection, sql: &str) -> i64 {
    conn.query(sql, ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap()
}

/// The v7 → v8 rung rebuilds `concepts` with an explicit `rowid_pk`, keeps every
/// row and every rowid, re-keys the FTS index onto the new column, and drops the
/// two indices with no reader (D-118, D-119).
///
/// The rung runs with foreign-key enforcement suspended, which is a thing worth
/// being nervous about, so what is asserted afterwards is not "it reached v8"
/// but the four things the suspension could have broken: the rows, the identity
/// of the rows, the referential integrity of what points at them, and the search
/// index that is keyed on their rowids.
#[tokio::test]
async fn a_v7_database_climbs_to_v8_and_gains_rowid_pk() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
    seeded_v7(&conn, &["c0", "c1", "c2", "c3"]).await;

    // Recorded before, compared after: the rung claims to preserve identity,
    // not merely order.
    let rowids_before = ids_by_rowid(&conn, "rowid").await;
    assert_eq!(rowids_before.len(), 4);

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    assert_eq!(count(&conn, "SELECT COUNT(*) FROM concepts").await, 4);
    assert_eq!(count(&conn, "SELECT COUNT(*) FROM links").await, 3);
    assert_eq!(
        ids_by_rowid(&conn, "rowid_pk").await,
        rowids_before,
        "the rebuild renumbered the concepts; the FTS index is keyed on these"
    );

    // The suspension is the reason this has to be asserted rather than assumed:
    // with enforcement off, an orphan is exactly what the rung could have left.
    assert_eq!(
        count(&conn, "SELECT COUNT(*) FROM pragma_foreign_key_check").await,
        0,
        "the rung committed a foreign-key violation"
    );

    // Enforcement is back on, on this very connection.
    assert!(
        conn.execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, \
             weight, properties, recorded_at) \
             VALUES ('c0','nobody','KNOWS',?1,'9999-12-31T23:59:59.999999Z',1.0,'{}',?1)",
            libsql::params![TS],
        )
        .await
        .is_err(),
        "foreign keys were not restored after the rung"
    );

    // The search index still finds every concept, which is the property the
    // whole rung exists to protect.
    assert_eq!(
        count(
            &conn,
            "SELECT COUNT(*) FROM concepts_fts WHERE concepts_fts MATCH 'findable'"
        )
        .await,
        4,
        "the FTS index did not survive the re-keying"
    );

    // (a): the two indices with no reader are gone, and nothing else went with
    // them.
    let indices = index_names(&conn).await;
    for gone in ["idx_annotations_label", "idx_lc_tgt_active"] {
        assert!(!indices.contains(&gone.to_string()), "{gone} survived v8");
    }
    assert_eq!(
        indices.len(),
        ddl::CREATE_INDICES.len(),
        "v8 left a different index set than CREATE_INDICES declares: {indices:?}"
    );
}

/// **The suspension is load-bearing, and the `links` rows are what make it so.**
///
/// Written because the previous test would pass against a rung with
/// `suspends_foreign_keys: false` if `concepts` had nothing pointing at it —
/// which is the shape D-084 originally specified and the probe refuted. This
/// pins the refutation: the same rebuild, on the same fixture, with enforcement
/// left on, must fail. If it ever stops failing, the flag has become
/// unnecessary and should be removed rather than carried.
#[tokio::test]
async fn the_v8_rung_needs_the_suspension_and_links_rows_prove_it() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
    seeded_v7(&conn, &["c0", "c1"]).await;

    // The rung's central act, attempted the way a rung without the flag would
    // reach it: inside a transaction, with enforcement on.
    conn.execute("BEGIN IMMEDIATE", ()).await.unwrap();
    let dropped = conn.execute("DROP TABLE concepts", ()).await;
    let _ = conn.execute("ROLLBACK", ()).await;

    assert!(
        dropped.is_err(),
        "`DROP TABLE concepts` succeeded with foreign keys enforced, so \
         `suspends_foreign_keys` is buying nothing on this engine. Either the \
         engine changed or the fixture lost its `links` rows — check the latter \
         first, because a `concepts` with no inbound rows makes this pass \
         vacuously."
    );
}

/// A v7 database that already holds an orphaned link is refused, not silently
/// migrated.
///
/// The honest cost of the suspension, pinned so it is a documented behaviour
/// rather than a surprise. `foreign_key_check` runs over the whole database, so
/// a violation that predates the rung fails the rung — and the alternative is
/// worse: enforcement is off during the rebuild, so without the check such a
/// database would migrate cleanly and carry the damage forward under a schema
/// version asserting it had been examined.
#[tokio::test]
async fn a_v7_database_with_a_pre_existing_orphan_is_refused() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    // Off for the seed, which is the only way to write the orphan at all — and
    // is how such a file would have come to exist.
    conn.execute("PRAGMA foreign_keys = OFF", ()).await.unwrap();
    seeded_v7(&conn, &["c0", "c1"]).await;
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, \
         weight, properties, recorded_at) \
         VALUES ('c0','ghost','KNOWS',?1,'9999-12-31T23:59:59.999999Z',1.0,'{}',?1)",
        libsql::params![TS],
    )
    .await
    .unwrap();

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains("suspended foreign keys and left a violation") && reason.contains("links"),
        "the refusal should name the check and the table, not merely fail: {reason}"
    );
    assert_eq!(
        user_version(&conn).await,
        7,
        "a refused rung must leave the database honestly at its old version"
    );
}

async fn ids_by_rowid(conn: &libsql::Connection, col: &str) -> Vec<(i64, String)> {
    let mut rows = conn
        .query(
            &format!("SELECT {col}, id FROM concepts ORDER BY {col}"),
            (),
        )
        .await
        .unwrap();
    let mut out = Vec::new();
    while let Some(r) = rows.next().await.unwrap() {
        out.push((r.get(0).unwrap(), r.get(1).unwrap()));
    }
    out
}

async fn index_names(conn: &libsql::Connection) -> Vec<String> {
    let mut rows = conn
        .query(
            "SELECT name FROM sqlite_master WHERE type = 'index' \
             AND name NOT LIKE 'sqlite_%' ORDER BY name",
            (),
        )
        .await
        .unwrap();
    let mut out = Vec::new();
    while let Some(r) = rows.next().await.unwrap() {
        out.push(r.get(0).unwrap());
    }
    out
}

/// A database holding a weight the v7 constraint rejects is refused, and told
/// why — it is not migrated with the offending rows altered or dropped.
///
/// Doctrine III is the whole reason: the rung copies every row verbatim, so a
/// row that cannot be represented in the new shape has no correct automatic
/// resolution. Clamping to zero and dropping the row are both edits to an
/// assertion, which is the one thing this ledger does not do. The migration
/// stops before touching anything and names a row, so the operator can decide.
#[tokio::test]
async fn a_negative_weight_already_stored_blocks_the_v7_rung_with_an_explanation() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;

    macrame::schema::run_migrations(&conn).await.unwrap();
    v11_schema::wind_back_to_v11(&conn).await;
    for stmt in [
        "ALTER TABLE links RENAME TO links_old",
        "CREATE TABLE links (
            source_id   TEXT NOT NULL REFERENCES concepts(id),
            target_id   TEXT NOT NULL REFERENCES concepts(id),
            edge_type   TEXT NOT NULL,
            valid_from  TEXT NOT NULL,
            recorded_at TEXT NOT NULL,
            valid_to    TEXT NOT NULL DEFAULT '9999-12-31T23:59:59.999999Z',
            weight      REAL NOT NULL DEFAULT 1.0,
            properties  TEXT NOT NULL DEFAULT '{}',
            PRIMARY KEY (source_id, target_id, edge_type, valid_from, recorded_at)
        )",
        "DROP TABLE links_old",
    ] {
        conn.execute(stmt, ()).await.unwrap();
    }
    conn.execute("PRAGMA user_version = 6", ()).await.unwrap();

    for id in ["c0", "c1"] {
        conn.execute(
            "INSERT INTO concepts (id, title, valid_from, recorded_at) \
             VALUES (?1, 'N', ?2, ?2)",
            libsql::params![id, TS],
        )
        .await
        .unwrap();
    }
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, \
         weight, properties, recorded_at) \
         VALUES ('c0','c1','NEG',?1,'9999-12-31T23:59:59.999999Z',-1.5,'{}',?1)",
        libsql::params![TS],
    )
    .await
    .unwrap();

    let err = macrame::schema::run_migrations(&conn)
        .await
        .expect_err("the rung cannot represent this row and must say so");
    let msg = err.to_string();
    assert!(
        msg.contains("c0 -> c1") && msg.contains("Doctrine III"),
        "the refusal must name a row and why it will not choose: {msg}"
    );

    // Refused *before* touching anything: still at v6, row still present.
    assert_eq!(user_version(&conn).await, 6);
    let rows: i64 = conn
        .query("SELECT COUNT(*) FROM links", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(rows, 1, "the failed rung was not clean");
}

/// **The point of the D-059 rung: the single-open-interval probe seeks on all
/// three equality columns instead of scanning a source's out-degree.**
///
/// This is the acceptance test the index exists for, and it has to inspect the
/// plan rather than time the insert. A timing assertion would need a hub large
/// enough for the difference to clear the noise — the measured spread only opens
/// up around 2,000 edges — which is a slow test that fails for machine reasons.
/// The plan is the causal claim: D-059 diagnosed the cost as `EXISTS` being
/// served by `idx_lc_traversal_cover` with only `source_id` bound, so what must
/// be asserted is which index is chosen and how much of it is bound.
///
/// The trigger body cannot be handed to `EXPLAIN QUERY PLAN` directly, so the
/// probe's `SELECT` is reproduced here. That is a second copy of the predicate
/// and the risk is real — if the trigger's `WHERE` changes and this does not,
/// the test goes on proving something about a query nobody runs. It is bounded
/// by `the_open_interval_probe_matches_the_trigger` below, which checks the
/// trigger DDL still contains the predicate this test models.
///
/// **And it runs against a populated fixture too (D-274).** The first arm was
/// the only one through 0.16.0, and it is the weaker of the two: on an empty
/// database `idx_lc_lineage_cut` is empty, and an empty index is attractive to
/// nobody — the same reason D-273 pinned its partial indexes against a fixture
/// holding live lineages. The populated arm is the state a bulk import runs
/// in — rows, no statistics, D-198's fixture — and that is where the planner
/// misbehaved: with the branch predicate seekable it served the probe from
/// `idx_lc_lineage_cut` with only `branch_id` bound, a whole-lineage scan per
/// trigger firing. Asserting that index by name in both arms is the pin.
#[tokio::test]
async fn the_single_open_probe_seeks_rather_than_scans() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // The `+` is part of the shipped body (D-274) and part of what this probe
    // models: without it the branch predicate is seekable and the planner's
    // choice is statistics-dependent, which is what the populated arm below
    // pins.
    let probe = "SELECT 1 FROM links_current \
                 WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 \
                   AND +branch_id = ?4 AND valid_from <> ?4 AND valid_to = ?5";

    let mut rows = conn
        .query(&format!("EXPLAIN QUERY PLAN {probe}"), ())
        .await
        .unwrap();
    let mut plan = Vec::new();
    while let Some(r) = rows.next().await.unwrap() {
        plan.push(r.get::<String>(3).unwrap());
    }
    let step = plan.join(" | ");

    assert!(
        step.contains("idx_lc_open_interval"),
        "the probe is not using its own index: {step}"
    );
    // Three equality columns bound, not one. `(source_id=?)` alone is the
    // pre-D-059 plan and the whole defect — it makes the probe O(out-degree).
    assert!(
        step.contains("source_id=? AND target_id=? AND edge_type=?"),
        "the probe binds fewer columns than the index offers, so it still scans: {step}"
    );

    // The populated arm: rows, no statistics — D-198's fixture, and the state
    // a fresh ledger holds for the whole of a bulk import. The empty arm
    // above passes under either body; this one is where the wrong index has
    // rows to be attractive to the planner with.
    let populated =
        populated_without_statistics(&harness.temp_dir.path().join("single_open_populated.db"))
            .await;
    let populated_plan = plan_string(&populated, probe).await;
    assert!(
        populated_plan.contains("idx_lc_open_interval"),
        "on a populated, statistics-free database the probe left its own \
         index: {populated_plan}"
    );
    assert!(
        populated_plan.contains("source_id=? AND target_id=? AND edge_type=?"),
        "the populated probe binds fewer columns than the index offers: \
         {populated_plan}"
    );
    assert!(
        !populated_plan.contains("idx_lc_lineage_cut"),
        "the branch-led index is serving a key-led lookup — a whole-lineage \
         scan per trigger firing, the D-274 defect in the plan: {populated_plan}"
    );
}

/// **The filtered subgraph walk still uses the traversal index (D-073).**
///
/// Adding `edge_types` and `min_weight` to this query lands in exactly the code
/// where D-064 found that a *narrowing* predicate can push the planner off the
/// index it was written for — a covering index is chosen for containing the
/// columns, not for discriminating between rows. That defect returned the right
/// answer throughout, so only a plan test can see it.
///
/// Both arms are checked, because the filtered one is the new shape and the
/// unfiltered one is what `load_subgraph` still compiles to: a filter that made
/// SQLite abandon `idx_lc_traversal_cover` would slow the walk without changing
/// a single returned row.
#[tokio::test]
async fn the_filtered_subgraph_walk_stays_on_the_traversal_index() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // The recursive step as `load_subgraph_with` emits it, with and without the
    // edge-type filter.
    let step = |edge_filter: &str| {
        format!(
            "SELECT l.target_id FROM links_current l \
             WHERE l.source_id = ?1 \
               AND l.valid_from <= ?3 AND ?3 < l.valid_to \
               AND l.weight >= ?4{edge_filter}"
        )
    };

    for (label, sql) in [
        ("unfiltered", step("")),
        ("edge-type filtered", step(" AND l.edge_type IN (?5)")),
    ] {
        let mut rows = conn
            .query(&format!("EXPLAIN QUERY PLAN {sql}"), ())
            .await
            .unwrap();
        let mut plan = Vec::new();
        while let Some(r) = rows.next().await.unwrap() {
            plan.push(r.get::<String>(3).unwrap());
        }
        let step = plan.join(" | ");

        assert!(
            step.contains("idx_lc_traversal_cover"),
            "{label}: the filtered walk left its index: {step}"
        );
        assert!(
            step.contains("COVERING INDEX"),
            "{label}: the walk is no longer index-only: {step}"
        );
    }
}

/// The predicate the plan test models is still the predicate the trigger runs.
///
/// Guards the one weakness of testing a reproduced query: a trigger body is not
/// reachable by `EXPLAIN QUERY PLAN`, so the plan test necessarily works on a
/// copy, and a copy can outlive its original.
#[test]
fn the_open_interval_probe_matches_the_trigger() {
    let trigger = ddl::CREATE_TRIGGERS
        .iter()
        .find(|t| t.contains("trg_links_single_open"))
        .expect("trg_links_single_open must exist");

    let flat = trigger.split_whitespace().collect::<Vec<_>>().join(" ");
    for clause in [
        "source_id = NEW.source_id",
        "target_id = NEW.target_id",
        "edge_type = NEW.edge_type",
        // The `+` is the plan (D-274): without it the branch predicate is
        // seekable and the populated planner serves this probe from
        // `idx_lc_lineage_cut` with one column bound.
        "+branch_id = NEW.branch_id",
        "valid_from <> NEW.valid_from",
        "valid_to = '9999-12-31T23:59:59.999999Z'",
    ] {
        assert!(
            flat.contains(clause),
            "the trigger no longer contains {clause:?}; \
             the_single_open_probe_seeks_rather_than_scans models a stale query:\n{flat}"
        );
    }
}

/// **The test that pins the column order, not merely the index's existence.**
///
/// Two things are asserted and the second is the one with teeth. `COVERING`
/// says the recursive step never fetches a base-table row. The seek constraint
/// says how much of the index it walks to get there: with `edge_type` ahead of
/// the range columns the unfiltered traversal — the default, since `edge_types`
/// is empty unless a caller sets it — degrades to `(source_id=?)` and evaluates
/// the valid-time window as a filter across that whole source's slice, while
/// the shipped order gives `(source_id=? AND valid_from<?)` and walks only the
/// slice that can match.
///
/// Both orders are *covering* once `idx_lc_src_active` is dropped, so asserting
/// `COVERING` alone passes under either and proves nothing about the ordering
/// (verified by mutation). The seek text is what distinguishes them (D-042).
#[tokio::test]
async fn the_traversal_walks_inside_the_index_with_and_without_an_edge_type_filter() {
    use macrame::graph::TraversalBuilder;

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    let plan_of = |sql: String| {
        let conn = conn.clone();
        async move {
            let sql = sql.trim().trim_end_matches(';').to_string();
            let mut rows = conn
                .query(&format!("EXPLAIN QUERY PLAN {sql}"), ())
                .await
                .unwrap();
            let mut lines = Vec::new();
            while let Some(r) = rows.next().await.unwrap() {
                lines.push(r.get::<String>(3).unwrap());
            }
            lines
        }
    };

    for (label, sql) in [
        (
            "unfiltered",
            TraversalBuilder::new("A").max_depth(3).build_sql(),
        ),
        (
            "edge-type filtered",
            TraversalBuilder::new("A")
                .max_depth(3)
                .edge_types(vec!["CITES".into()])
                .build_sql(),
        ),
    ] {
        let plan = plan_of(sql).await;
        let step = plan
            .iter()
            .find(|l| l.contains(" l ") || l.ends_with(" l"))
            .unwrap_or_else(|| panic!("{label}: no plan line for links_current: {plan:?}"));
        assert!(
            step.contains("COVERING INDEX idx_lc_traversal_cover"),
            "{label}: recursive step is not index-only: {step}"
        );
        assert!(
            step.contains("valid_from<?"),
            "{label}: the valid-time window is not in the index seek, only a \
             filter over the whole source slice — check the column order: {step}"
        );
    }
}

/// The covering index has the same seek column as `idx_lc_src_active` and
/// strictly more payload, so keeping both would pay a second index write on
/// every assertion for nothing. The v3 → v4 rung drops it; if a later edit
/// reinstates it, that cost comes back silently.
#[tokio::test]
async fn the_subsumed_source_index_is_gone() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    let n: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_lc_src_active'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(n, 0, "idx_lc_src_active is subsumed and must not survive");
}

/// The **shipped** traversal CTE keeps D-042's covering index, filtered or not.
///
/// The test above approximates the recursive step by hand, which is one hazard
/// away from testing a query nobody runs. This one explains the exact string
/// `TraversalBuilder::build_sql` emits, so T0.1's rewrite cannot have moved the
/// planner off `idx_lc_traversal_cover` while every returned row stayed correct
/// — D-064's failure mode, and the reason plan shape is a test category here.
#[tokio::test]
async fn the_shipped_traversal_cte_stays_on_the_covering_index() {
    use macrame::graph::TraversalBuilder;

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    for (label, builder) in [
        ("unfiltered", TraversalBuilder::new("a").max_depth(3)),
        (
            "edge-type filtered",
            TraversalBuilder::new("a")
                .max_depth(3)
                .edge_types(vec!["CITES".to_string()]),
        ),
    ] {
        let sql = builder.build_sql();
        let mut rows = conn
            .query(&format!("EXPLAIN QUERY PLAN {sql}"), ())
            .await
            .unwrap();
        let mut plan = Vec::new();
        while let Some(r) = rows.next().await.unwrap() {
            plan.push(r.get::<String>(3).unwrap());
        }
        let plan = plan.join(" | ");

        assert!(
            plan.contains("idx_lc_traversal_cover"),
            "{label}: the walk left its index: {plan}"
        );
        assert!(
            plan.contains("COVERING INDEX"),
            "{label}: the walk is no longer index-only: {plan}"
        );
    }
}

// ---------------------------------------------------------------------------
// v13 → v14 — the lineage read gets an index to seek on (0.14.14, D-231)
// ---------------------------------------------------------------------------

/// The rung is index-only, so *what it is for* is a plan and not a row count.
///
/// Two assertions, and the second is the one that makes this rung the shape it
/// is rather than the one §15.4 asked for. Before the rung the branched read
/// has no persistent index leading on `branch_id` and SQLite builds one per
/// execution; after it, the two base scans over `links_current` seek
/// `idx_lc_lineage_cut`. And the **trunk** walk is unchanged across the rung —
/// which every single-index shape D-231 measured could not manage, because
/// leading on `branch_id` evicts the trunk walk from `idx_lc_traversal_cover`
/// altogether.
///
/// The fixture winds a real database back rather than building a v13 one:
/// `DROP INDEX` plus a stamp is exactly what a v13 database is, because this
/// rung changes nothing else.
#[tokio::test]
async fn a_v13_database_climbs_to_v14_and_the_lineage_read_stops_building_its_own_index() {
    use macrame::graph::TraversalBuilder;

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // A second lineage, so `build_sql` emits the resolved shape below and the
    // plan is the one a forked database actually runs.
    conn.execute(
        "INSERT INTO branches (branch_id, parent_id, forked_at, created_at) \
         VALUES ('b1', 'main', ?1, ?1)",
        libsql::params!["2026-01-01T00:00:00.000000Z"],
    )
    .await
    .unwrap();

    let branched = TraversalBuilder::new("a")
        .max_depth(3)
        .on_branch("b1")
        .build_sql();
    let trunk = TraversalBuilder::new("a").max_depth(3).build_sql();

    conn.execute("DROP INDEX idx_lc_lineage_cut", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 13", ()).await.unwrap();

    let before = plan_string(&conn, &branched).await;
    assert!(
        before.contains("AUTOMATIC"),
        "the fixture is not starting from the v13 plan — expected SQLite to be \
         building the index itself, got: {before}"
    );
    assert!(
        !before.contains("idx_lc_lineage_cut"),
        "the index survived the drop: {before}"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let after = plan_string(&conn, &branched).await;
    assert!(
        after.contains("COVERING INDEX idx_lc_lineage_cut"),
        "the rung created the index and the branched read did not take it — an \
         index nothing seeks on is D-089's failure, not a schema change: {after}"
    );

    // The half the plan's own rung could not have kept. Asserted after the
    // rung, on the same connection, so it is a statement about the schema this
    // release ships rather than about the one it started from.
    let trunk_plan = plan_string(&conn, &trunk).await;
    assert!(
        trunk_plan.contains("COVERING INDEX idx_lc_traversal_cover"),
        "the new index displaced the trunk walk from its own — which is what \
         D-231 measured every `branch_id`-leading shape doing: {trunk_plan}"
    );
}

/// A v14 stamp over a database that never ran the rung is refused at open.
///
/// The index is in `CREATE_INDICES`, and `verify` compares the declared index
/// names against what the file holds — so this needs no new list to be added
/// to, which is the difference between an index rung and the trigger rung
/// below it. Pinned anyway: the guarantee is that a mis-stamped database is a
/// sentence at open time rather than a branched read that is quietly three
/// times slower, and nothing else in this file would notice that.
#[tokio::test]
async fn a_v14_stamp_over_a_v13_index_set_is_refused_at_open() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    conn.execute("DROP INDEX idx_lc_lineage_cut", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 14", ()).await.unwrap();

    let err = macrame::schema::run_migrations(&conn)
        .await
        .expect_err("a v14 stamp over a v13 index set");
    let msg = err.to_string();
    assert!(
        msg.contains("idx_lc_lineage_cut"),
        "the refusal does not name what is missing: {msg}"
    );
}

// ---------------------------------------------------------------------------
// v14 → v15 — the ledger is keyed by lineage (0.14.15, D-232)
// ---------------------------------------------------------------------------

/// `links` **as v14 declared it**, pinned as text.
///
/// Pinned for `v11_schema`'s reason and for one more that is specific to this
/// rung: the fixture cannot be built by omitting something. Every v15 object
/// exists at v14 too — same tables, same triggers, same indices — and the only
/// difference is a clause inside one `CREATE TABLE`. So the wind-back has to
/// *rebuild the table backwards*, which means it needs the shape it is winding
/// back to, written out.
const LINKS_V14: &str = r#"
CREATE TABLE links_v14 (
    source_id   TEXT NOT NULL REFERENCES concepts(id),
    target_id   TEXT NOT NULL REFERENCES concepts(id),
    edge_type   TEXT NOT NULL,
    valid_from  TEXT NOT NULL,
    recorded_at TEXT NOT NULL,
    valid_to    TEXT NOT NULL DEFAULT '9999-12-31T23:59:59.999999Z',
    weight      REAL NOT NULL DEFAULT 1.0,
    properties  TEXT NOT NULL DEFAULT '{}',
    branch_id   TEXT NOT NULL DEFAULT 'main' REFERENCES branches(branch_id),
    PRIMARY KEY (source_id, target_id, edge_type, valid_from, recorded_at),
    CHECK (weight >= 0.0 AND weight < 9e999 AND typeof(weight) = 'real'),
    CHECK (valid_from GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][0-9][0-9][0-9]Z' AND valid_to GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][0-9][0-9][0-9]Z' AND recorded_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][0-9][0-9][0-9]Z' AND 1)
)
"#;

/// Rebuild `links` under the v14 key, rows and all, and put back what the drop
/// took.
///
/// The rung's own recipe run in reverse, which is the only honest fixture here:
/// a database that merely *claims* v14 would be one this rung repairs by
/// accident.
async fn wind_links_back_to_v14(conn: &libsql::Connection) {
    conn.execute(LINKS_V14, ()).await.unwrap();
    conn.execute(
        "INSERT INTO links_v14 (source_id, target_id, edge_type, valid_from, \
         recorded_at, valid_to, weight, properties, branch_id) \
         SELECT source_id, target_id, edge_type, valid_from, recorded_at, \
                valid_to, weight, properties, branch_id FROM links",
        (),
    )
    .await
    .unwrap();
    conn.execute("DROP TABLE links", ()).await.unwrap();
    conn.execute("ALTER TABLE links_v14 RENAME TO links", ())
        .await
        .unwrap();

    for ddl in [
        ddl::CREATE_LINKS_CURRENT_SYNC,
        ddl::CREATE_LINKS_SINGLE_OPEN,
        ddl::CREATE_LINKS_LOG_INSERT,
        ddl::CREATE_LINKS_GUARD_DELETE,
    ] {
        conn.execute(ddl, ()).await.unwrap();
    }
    for sql in ddl::CREATE_INDICES {
        if sql.contains("idx_links_recorded_at") || sql.contains("idx_links_target") {
            conn.execute(sql, ()).await.unwrap();
        }
    }
}

/// One `SELECT COUNT(*)`-shaped read, since this test asks for three.
async fn scalar(conn: &libsql::Connection, sql: &str) -> i64 {
    conn.query(sql, ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap()
}

/// One batch, one edge key, two lineages — refused at v14, written at v15.
///
/// **This is what the rung is for**, and it is a row count rather than a plan
/// because the rung changes what the ledger will accept, not how it is read.
/// The `INSERT`s are issued directly and share a `recorded_at` on purpose: that
/// is not a contrivance, it is precisely what `write_bulk_atomic` and
/// `bulk_import` do — one stamp for the whole batch, by contract (D-014) —
/// which is why §15.4's "unreachable through the crate" stopped being true at
/// 0.14.8 without anything noticing.
///
/// Three further assertions, each covering a way a table rebuild goes wrong
/// quietly:
///
/// * **Every row survives.** A rung that rebuilds the ledger and loses a row
///   has violated Doctrine III whatever its key says.
/// * **The four triggers come back.** `DROP TABLE` takes them, and a database
///   missing `trg_links_current_sync` writes to `links` and never updates
///   `links_current` — reads go stale with no error at all.
/// * **The two indices come back.** They were not the v6 → v7 rung's problem
///   (there was no index on `links` at v7) and they are this one's.
#[tokio::test]
async fn a_v14_database_climbs_to_v15_and_two_lineages_may_assert_one_edge_at_one_instant() {
    const TS: &str = "2026-01-01T00:00:00.000000Z";
    const FOREVER: &str = "9999-12-31T23:59:59.999999Z";

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    for id in ["a", "b"] {
        conn.execute(
            "INSERT INTO concepts (id, title, valid_from, recorded_at) \
             VALUES (?1, 't', ?2, ?2)",
            libsql::params![id, TS],
        )
        .await
        .unwrap();
    }
    conn.execute(
        "INSERT INTO branches (branch_id, parent_id, forked_at, created_at) \
         VALUES ('b1', 'main', ?1, ?1)",
        libsql::params![TS],
    )
    .await
    .unwrap();

    wind_links_back_to_v14(&conn).await;
    conn.execute("PRAGMA user_version = 14", ()).await.unwrap();

    let insert = |branch: &'static str| {
        conn.execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, \
             valid_to, weight, properties, recorded_at, branch_id) \
             VALUES ('a', 'b', 'LINKS', ?1, ?2, 1.0, '{}', ?1, ?3)",
            libsql::params![TS, FOREVER, branch],
        )
    };

    insert("main").await.unwrap();
    let err = insert("b1")
        .await
        .expect_err("the fixture is not starting from the v14 key");
    assert!(
        err.to_string().contains("UNIQUE constraint failed: links."),
        "the fixture failed for some other reason: {err}"
    );

    let before = scalar(&conn, "SELECT COUNT(*) FROM links").await;

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    insert("b1")
        .await
        .expect("v15 still refuses a second lineage's belief about one edge");

    let after = scalar(&conn, "SELECT COUNT(*) FROM links").await;
    assert_eq!(
        after,
        before + 1,
        "the rebuild did not carry every row across: {before} before, {after} \
         after one insert"
    );

    for name in [
        "trg_links_current_sync",
        "trg_links_single_open",
        "trg_links_log_insert",
        "trg_links_guard_delete",
    ] {
        let found: i64 = conn
            .query(
                "SELECT COUNT(*) FROM sqlite_master \
                 WHERE type = 'trigger' AND name = ?1",
                libsql::params![name],
            )
            .await
            .unwrap()
            .next()
            .await
            .unwrap()
            .unwrap()
            .get(0)
            .unwrap();
        assert_eq!(found, 1, "`DROP TABLE links` took {name} and left it off");
    }

    for name in ["idx_links_recorded_at", "idx_links_target"] {
        let found: i64 = conn
            .query(
                "SELECT COUNT(*) FROM sqlite_master \
                 WHERE type = 'index' AND name = ?1",
                libsql::params![name],
            )
            .await
            .unwrap()
            .next()
            .await
            .unwrap()
            .unwrap()
            .get(0)
            .unwrap();
        assert_eq!(
            found, 1,
            "the rebuild dropped {name} and did not put it back"
        );
    }

    // The sync trigger is back *and wired*: the row just written reached the
    // materialization on its own lineage. A trigger present but pointed at the
    // old table would satisfy the name check above and fail this.
    let current = scalar(
        &conn,
        "SELECT COUNT(*) FROM links_current WHERE branch_id = 'b1'",
    )
    .await;
    assert_eq!(current, 1, "the restored sync trigger did not fire");
}

/// A v15 stamp over a v14 key is refused at open.
///
/// **The one guarantee this release could not get for free.** Every previous
/// rung added an object with a name, and `verify` finds a missing name without
/// being told to look. A primary key has no name — a v15 stamp over a v14
/// `links` opens cleanly, reads correctly, and then refuses one legal batch in
/// a hundred with raw engine text. So `verify` gained a check on the key
/// itself, and this is what pins it.
#[tokio::test]
async fn a_v15_stamp_over_a_v14_links_key_is_refused_at_open() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    wind_links_back_to_v14(&conn).await;
    conn.execute("PRAGMA user_version = 15", ()).await.unwrap();

    let err = macrame::schema::run_migrations(&conn)
        .await
        .expect_err("a v15 stamp over a v14 key");
    let msg = err.to_string();
    assert!(
        msg.contains("keyed by lineage") && msg.contains("branch_id"),
        "the refusal does not say what is wrong with the table: {msg}"
    );
}

// ---------------------------------------------------------------------------
// v15 → v16 — the log records whether anything has left it (W14.5, D-249)
// ---------------------------------------------------------------------------

/// The v15 intactness test, written out rather than imported.
///
/// `hot_log_is_intact` was this expression until 0.15.7 and is now a one-row
/// read, so there is nothing left to import — and importing it would be asking
/// the thing under test what it used to think. Returns 1 for *intact*, which is
/// the polarity the old function had; `log_integrity.rows_removed` is the
/// opposite polarity, and the tests below convert rather than assume.
const V15_INTACT: &str = "SELECT CASE \
     WHEN COUNT(*) = 0 THEN 1 \
     WHEN MIN(seq_id) = 1 AND COUNT(*) = MAX(seq_id) THEN 1 \
     ELSE 0 END FROM transaction_log";

/// Take a v16 database back to v15: drop what the rung adds, and stamp.
///
/// The rung adds a table and a trigger and touches nothing else, so this really
/// is what a v15 database is — unlike the wind-backs below it, which have to
/// rebuild a table to undo a key.
async fn wind_back_to_v15(conn: &libsql::Connection) {
    conn.execute("DROP TRIGGER IF EXISTS trg_txlog_mark_gap", ())
        .await
        .unwrap();
    conn.execute("DROP TABLE IF EXISTS log_integrity", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 15", ()).await.unwrap();
}

/// Delete log rows the way an archive session does, guard and all.
///
/// `trg_txlog_guard_delete` refuses a delete unless `macrame_archive_session`
/// exists (D-126), so a test that wants a gap has to take the same route the
/// archive takes. Which is the point: on a v16 database this also fires
/// `trg_txlog_mark_gap`, so these helpers exercise the maintenance path rather
/// than reaching around it.
async fn delete_log_rows(conn: &libsql::Connection, where_clause: &str) {
    conn.execute("CREATE TABLE macrame_archive_session (marker INTEGER)", ())
        .await
        .unwrap();
    conn.execute(
        &format!("DELETE FROM transaction_log WHERE {where_clause}"),
        (),
    )
    .await
    .unwrap();
    conn.execute("DROP TABLE macrame_archive_session", ())
        .await
        .unwrap();
}

/// Write `n` concepts starting at `first`, each of which logs a row.
///
/// `first` rather than a counter because one caller writes again *after* a
/// delete, and a second `c0` would fail on the primary key rather than on
/// anything this file is about.
async fn log_some_rows(conn: &libsql::Connection, first: usize, n: usize) {
    for i in first..first + n {
        conn.execute(
            "INSERT INTO concepts (id, title, valid_from, recorded_at) \
             VALUES (?1, 't', ?2, ?2)",
            libsql::params![format!("c{i}"), TS],
        )
        .await
        .unwrap();
    }
}

/// v15 → v16: the rung reads the log's history off `sqlite_sequence` and writes
/// down the one bit the reach guard used to count for (W14.5, [D-249], C-5).
///
/// Three v15 databases, differing only in what has been taken out of the log,
/// and the rung has to tell them apart on arrival. The third is the one that
/// makes this a rung rather than a default: a log archived down to nothing is
/// indistinguishable from a log that was never written *by counting it*, and
/// the high-water mark is what distinguishes them.
#[tokio::test]
async fn a_v15_database_climbs_to_v16_and_the_rung_seeds_the_bit_from_the_log() {
    // Intact: three rows written, none removed.
    let intact = TestHarness::new();
    let conn = connect(&intact).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    log_some_rows(&conn, 0, 3).await;
    wind_back_to_v15(&conn).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        0,
        "an intact log was seeded as if it had been archived"
    );

    // A gap in the middle, which is the shape `LOG_ARCHIVABLE` actually leaves.
    let holed = TestHarness::new();
    let conn = connect(&holed).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    log_some_rows(&conn, 0, 3).await;
    wind_back_to_v15(&conn).await;
    delete_log_rows(&conn, "seq_id = 2").await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        1,
        "an interior gap was seeded as intact"
    );

    // Everything archived. `COUNT(*) = 0` is where the old test said *intact*.
    let emptied = TestHarness::new();
    let conn = connect(&emptied).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    log_some_rows(&conn, 0, 3).await;
    wind_back_to_v15(&conn).await;
    delete_log_rows(&conn, "1 = 1").await;
    assert_eq!(
        scalar(&conn, V15_INTACT).await,
        1,
        "the fixture is not standing on the state the old test got wrong"
    );
    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        1,
        "a fully archived log was seeded as a young one — which is the read \
         defect D-249 exists to close, reintroduced at the rung"
    );
}

/// The trigger keeps the bit true after the rung, on the one route that can
/// change it (W14.5, [D-249]).
///
/// A seeded bit that never moves again would pass the rung test above and be
/// worthless. This asserts the maintenance: intact at v16, then one archive
/// session, then not.
#[tokio::test]
async fn the_bit_is_set_by_the_delete_and_not_by_the_write_path() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    log_some_rows(&conn, 0, 3).await;
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        0,
        "writing to the log marked it as having lost rows"
    );

    delete_log_rows(&conn, "seq_id = 1").await;
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        1,
        "a log row was deleted and the log did not notice"
    );

    // And it does not come back. There is no route that clears the bit, which
    // is what makes it safe to read instead of counting.
    log_some_rows(&conn, 3, 1).await;
    assert_eq!(
        scalar(&conn, "SELECT rows_removed FROM log_integrity").await,
        1,
        "a later write cleared a gap that is still there"
    );
}

/// The bit, read in the polarity [`V15_INTACT`] uses, so the two are comparable
/// without a reader having to hold the inversion in their head.
async fn intact_by_bit(conn: &libsql::Connection) -> i64 {
    scalar(conn, "SELECT 1 - rows_removed FROM log_integrity").await
}

/// The bit agrees with the count it replaced — and where it does not, the
/// count was wrong (W14.5, [D-249]).
///
/// The v15 test was exact and was argued for at length: `seq_id` is
/// `AUTOINCREMENT` so ids are never reused, a rollback leaves no gap (D-049),
/// and `MIN = 1` with `COUNT(*) = MAX` forces the ids to be all of `1..=MAX`.
/// The argument holds. What it never covered is the empty log, where the
/// function returned *intact* by a separate arm and no proof at all — and an
/// emptied log is precisely a log rows were removed from.
///
/// So this walks a database through four states and asserts agreement in three
/// of them and disagreement in the fourth, in the direction that says the bit
/// is right. A test asserting agreement everywhere would be asserting the bug.
#[tokio::test]
async fn the_bit_agrees_with_the_count_it_replaced() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // (1) Never written.
    assert_eq!(scalar(&conn, V15_INTACT).await, 1);
    assert_eq!(intact_by_bit(&conn).await, 1, "a fresh log is intact");

    // (2) Written, nothing removed.
    log_some_rows(&conn, 0, 4).await;
    assert_eq!(scalar(&conn, V15_INTACT).await, 1);
    assert_eq!(intact_by_bit(&conn).await, 1, "a full log is intact");

    // (3) An interior row gone — the shape archiving leaves, and the shape
    // only a count can find.
    delete_log_rows(&conn, "seq_id = 3").await;
    assert_eq!(scalar(&conn, V15_INTACT).await, 0);
    assert_eq!(intact_by_bit(&conn).await, 0, "a hole is not intact");

    // (4) Emptied. Here they part company, and the old one is the one that is
    // wrong: every row this log ever held has been archived away, and it
    // reports itself as a database nothing was ever written to.
    delete_log_rows(&conn, "1 = 1").await;
    assert_eq!(
        scalar(&conn, V15_INTACT).await,
        1,
        "the v15 expression has been transcribed wrongly — it called an empty \
         log intact, and this test is about that"
    );
    assert_eq!(
        intact_by_bit(&conn).await,
        0,
        "an emptied log claims to be intact, which is the conflation between a \
         young database and a fully archived one that D-249 closes"
    );
}

// ---------------------------------------------------------------------------
// v8 → v9 — the concepts delete guard becomes marker-gated (C2, D-126)
// ---------------------------------------------------------------------------

/// The v8 guard body, reproduced here rather than imported.
///
/// A test that asked the crate what v8 looked like would be asking the thing
/// under test, and would pass no matter what the rung did. This is the same
/// discipline `v7_schema.rs` follows and the same trap the plan flagged for this
/// item: a fixture built from today's `ddl::` constants already has the change.
const CONCEPTS_GUARD_V8: &str = "
    CREATE TRIGGER trg_concepts_guard_delete
    BEFORE DELETE ON concepts
    BEGIN
        SELECT RAISE(ABORT, 'macrame: concepts are never physically archived (D-022)');
    END;
";

/// Put a v9 database back into the v8 state this rung exists to leave behind:
/// the unconditional guard, and the version stamp to match.
async fn downgrade_guard_to_v8(conn: &libsql::Connection) {
    v11_schema::wind_back_to_v11(conn).await;
    conn.execute("DROP TRIGGER trg_concepts_guard_delete", ())
        .await
        .unwrap();
    conn.execute(CONCEPTS_GUARD_V8, ()).await.unwrap();
    conn.execute("PRAGMA user_version = 8", ()).await.unwrap();
}

async fn guard_sql(conn: &libsql::Connection) -> String {
    conn.query(
        "SELECT sql FROM sqlite_master WHERE type = 'trigger' \
         AND name = 'trg_concepts_guard_delete'",
        (),
    )
    .await
    .unwrap()
    .next()
    .await
    .unwrap()
    .expect("the concepts delete guard should exist")
    .get(0)
    .unwrap()
}

#[tokio::test]
async fn a_v8_database_climbs_past_v9_and_the_concepts_guard_becomes_conditional() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    downgrade_guard_to_v8(&conn).await;

    // Precondition, asserted rather than assumed: the fixture really is v8.
    assert!(
        guard_sql(&conn).await.contains("never physically archived"),
        "the fixture did not start from the v8 guard"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);
    let sql = guard_sql(&conn).await;
    assert!(
        sql.contains(ddl::ARCHIVE_SESSION_MARKER),
        "the guard is not marker-gated after the rung: {sql}"
    );
    assert!(
        !sql.contains("never physically archived"),
        "the v8 body survived the rung: {sql}"
    );
}

/// **The rung cannot be replaced by re-issuing the baseline, and this is the
/// measurement that says so** (D-126).
///
/// `CREATE TRIGGER IF NOT EXISTS` on an existing name keeps the old body. That
/// is the whole reason C2 needs a schema rung rather than a baseline re-issue,
/// and it is a claim about libSQL rather than about this crate — so it is
/// verified against the engine here, not argued in a comment.
#[tokio::test]
async fn re_issuing_the_baseline_guard_keeps_the_v8_body() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    downgrade_guard_to_v8(&conn).await;

    conn.execute(ddl::CREATE_CONCEPTS_GUARD_DELETE, ())
        .await
        .unwrap();

    let sql = guard_sql(&conn).await;
    assert!(
        sql.contains("never physically archived"),
        "IF NOT EXISTS replaced the body — D-126's premise no longer holds and \
         the v8 → v9 rung may be unnecessary: {sql}"
    );
}

/// **The other half of D-126's hole: `verify` used to compare names only.**
///
/// A guard with the right name and a pre-v9 body passed verification in
/// silence, which is what made the stale-guard failure mode invisible. A
/// database stamped v9 whose guard is not marker-gated must now be refused —
/// otherwise the rung above is the only thing standing between a user and a
/// concept archival that aborts at the trigger.
#[tokio::test]
async fn a_v9_stamp_over_an_ungated_guard_is_refused() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // The stamp says v9; the guard says v8. Nothing in the ladder runs.
    conn.execute("DROP TRIGGER trg_concepts_guard_delete", ())
        .await
        .unwrap();
    conn.execute(CONCEPTS_GUARD_V8, ()).await.unwrap();

    let reason = refusal_reason(macrame::schema::run_migrations(&conn).await.unwrap_err());
    assert!(
        reason.contains("trg_concepts_guard_delete") && reason.contains("archive-session"),
        "the refusal should name the guard and what it lacks: {reason}"
    );
}

/// The climb from v7 passes *through* v8's guard, not around it.
///
/// `add_concepts_rowid_pk` rebuilds `concepts` and restores its triggers from
/// `CREATE_TRIGGERS`, which is today's DDL — so without the pinned
/// `CONCEPTS_GUARD_DELETE_V8` the v7 → v8 rung would install the v9 body and
/// this whole ladder would reach v9 without the v8 → v9 rung ever doing
/// anything. There is no way to observe that from the outside once the climb
/// finishes, so what is asserted is the end state plus the fact that the guard
/// is genuinely functional: an ad-hoc delete is refused, and the same delete
/// inside a declared session is not.
#[tokio::test]
async fn a_v7_database_climbs_all_the_way_to_the_top_with_a_working_guard() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    seeded_v7(&conn, &["c1", "c2"]).await;
    conn.execute("PRAGMA user_version = 7", ()).await.unwrap();

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let res = conn
        .execute("DELETE FROM concepts WHERE id = 'c1'", ())
        .await;
    assert!(
        res.is_err(),
        "an ad-hoc concept delete must still be refused"
    );

    // Inside a declared archive session the same delete is legal — which is the
    // capability the rung exists to grant, and the thing v8 could not do.
    conn.execute(
        &format!("CREATE TABLE {} (x)", ddl::ARCHIVE_SESSION_MARKER),
        (),
    )
    .await
    .unwrap();
    // Links first. `seeded_v7` gives c1 an outbound edge, so deleting the
    // concept while that edge is hot fails on the foreign key rather than on the
    // guard — which is precisely the downstream relationship C1's predicate
    // describes (D-128), reached here from the schema side.
    conn.execute(
        "DELETE FROM links WHERE source_id = 'c1' OR target_id = 'c1'",
        (),
    )
    .await
    .unwrap();
    conn.execute("DELETE FROM concepts WHERE id = 'c1'", ())
        .await
        .expect("a concept delete inside an archive session must be permitted at v9");
    conn.execute(&format!("DROP TABLE {}", ddl::ARCHIVE_SESSION_MARKER), ())
        .await
        .unwrap();
}

// ---------------------------------------------------------------------------
// v9 → v10 — the concepts insert log trigger becomes marker-gated (C3)
// ---------------------------------------------------------------------------

/// The v9 body, reproduced rather than imported, for the reason
/// [`CONCEPTS_GUARD_V8`] gives.
const CONCEPTS_LOG_INSERT_V9_FIXTURE: &str = "
    CREATE TRIGGER trg_concepts_log_insert
    AFTER INSERT ON concepts
    BEGIN
        INSERT INTO transaction_log (table_name, entity_id, operation, payload, recorded_at)
        VALUES ('concepts', NEW.id, 'I',
                json_object('v', 2, 'title', NEW.title, 'content', NEW.content,
                            'valid_from', NEW.valid_from, 'valid_to', NEW.valid_to,
                            'retired', NEW.retired,
                            'embedding_model', NEW.embedding_model),
                NEW.recorded_at);
    END;
";

async fn log_insert_sql(conn: &libsql::Connection) -> String {
    conn.query(
        "SELECT sql FROM sqlite_master WHERE type = 'trigger' \
         AND name = 'trg_concepts_log_insert'",
        (),
    )
    .await
    .unwrap()
    .next()
    .await
    .unwrap()
    .expect("the concepts insert log trigger should exist")
    .get(0)
    .unwrap()
}

#[tokio::test]
async fn a_v9_database_climbs_to_v10_and_the_insert_log_becomes_marker_gated() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();
    v11_schema::wind_back_to_v11(&conn).await;

    conn.execute("DROP TRIGGER trg_concepts_log_insert", ())
        .await
        .unwrap();
    conn.execute(CONCEPTS_LOG_INSERT_V9_FIXTURE, ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 9", ()).await.unwrap();

    assert!(
        !log_insert_sql(&conn)
            .await
            .contains(ddl::ARCHIVE_SESSION_MARKER),
        "the fixture did not start from the v9 trigger"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();

    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);
    assert!(
        log_insert_sql(&conn)
            .await
            .contains(ddl::ARCHIVE_SESSION_MARKER),
        "the insert log trigger is not marker-gated after the rung"
    );
}

/// **What the rung is *for*, asserted as behaviour rather than as DDL text.**
///
/// Outside a session a concept insert logs, as it always has. Inside one it does
/// not — which is what makes rehydration a physical move rather than a write,
/// and what stops a rehydrated concept from outranking its own retirement in the
/// fold (C3).
#[tokio::test]
async fn an_insert_inside_a_session_writes_no_log_row_and_outside_one_still_does() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    let log_rows = |conn: libsql::Connection| async move {
        conn.query("SELECT COUNT(*) FROM transaction_log", ())
            .await
            .unwrap()
            .next()
            .await
            .unwrap()
            .unwrap()
            .get::<i64>(0)
            .unwrap()
    };

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) \
         VALUES ('outside', 'T', ?1, ?1)",
        libsql::params![TS],
    )
    .await
    .unwrap();
    assert_eq!(
        log_rows(conn.clone()).await,
        1,
        "an ordinary concept insert must still be logged"
    );

    conn.execute(
        &format!("CREATE TABLE {} (x)", ddl::ARCHIVE_SESSION_MARKER),
        (),
    )
    .await
    .unwrap();
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) \
         VALUES ('inside', 'T', ?1, ?1)",
        libsql::params![TS],
    )
    .await
    .unwrap();
    conn.execute(&format!("DROP TABLE {}", ddl::ARCHIVE_SESSION_MARKER), ())
        .await
        .unwrap();

    assert_eq!(
        log_rows(conn.clone()).await,
        1,
        "an insert inside an archive session wrote a transaction_log row; \
         rehydration is a move back and mints no transaction-time facts"
    );
}

// ---------------------------------------------------------------------------
// v16 → v17 — the fold gets its partition in an index (0.15.12, W15.2, D-254)
// ---------------------------------------------------------------------------

/// The fold is a window function, and the rung is what stops it sorting.
///
/// Index-only, so *what it is for* is a plan rather than a row count — the same
/// shape as v13 → v14 above, and the fixture is built the same way: a real
/// database wound back by `DROP INDEX` plus a stamp, which is exactly what a
/// v16 database is, because this rung changes nothing else.
///
/// Three assertions, and the second is the one that makes the rung worth a
/// version.
///
/// 1. **Before**, the plan carries a temp B-tree. Every reconstruction sorted
///    the whole log to put it in partition-then-order sequence.
/// 2. **After**, that step is *gone* — not merely that the index appears. The
///    ascending form of the identical columns also appears in the plan and
///    still sorts (`USE TEMP B-TREE FOR RIGHT PART OF ORDER BY`), at 60.2 ms
///    against this shape's 46.2 and the same cost on the write path — so "the
///    index is used" is not the property this rung buys. The sort's absence
///    is.
/// 3. **`idx_txlog_time` keeps the readers it has left.** The fold was the
///    reader `index_plan_tests` recorded for it, and the fold has moved off it;
///    what remains is the pair of aggregates over `recorded_at`, and they must
///    still be served without touching the table. An index whose last reader
///    leaves is D-089's failure, and this is where that would show.
#[tokio::test]
async fn a_v16_database_climbs_to_v17_and_the_log_fold_stops_sorting() {
    // The fold's shape, copied — the original is a private `const` in
    // `temporal::replay` and `EXPLAIN QUERY PLAN` cannot reach it.
    // `index_plan_tests` bounds the same copy against its source with an
    // `include_str!` fragment, so a divergence is caught there rather than
    // here, where it would look like a passing test.
    const FOLD: &str = "SELECT seq_id, table_name, entity_id, operation, payload, branch_id \
         FROM ( \
           SELECT seq_id, table_name, entity_id, operation, payload, branch_id, \
                  ROW_NUMBER() OVER (PARTITION BY table_name, entity_id, branch_id \
                                     ORDER BY seq_id DESC) as rn \
           FROM transaction_log WHERE recorded_at <= ?1) WHERE rn = 1";

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    conn.execute("DROP INDEX idx_txlog_fold_partition", ())
        .await
        .unwrap();
    conn.execute("PRAGMA user_version = 16", ()).await.unwrap();

    let before = plan_string(&conn, FOLD).await;
    assert!(
        before.contains("TEMP B-TREE"),
        "the fixture is not starting from the v16 plan — expected the window \
         function to be sorting its input, got: {before}"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let after = plan_string(&conn, FOLD).await;
    assert!(
        after.contains("idx_txlog_fold_partition"),
        "the rung created the index and the fold did not take it — an index \
         nothing seeks on is D-089's failure, not a schema change: {after}"
    );
    assert!(
        !after.contains("TEMP B-TREE"),
        "the fold still sorts. The index is being used and is not supplying \
         the order, which is what the ascending form of these same columns \
         does — 60.2 ms against 46.2, for the same file and the same writes: \
         {after}"
    );

    // The half the rung could take away by accident.
    let aggregate = plan_string(&conn, "SELECT MAX(recorded_at) FROM transaction_log").await;
    assert!(
        aggregate.contains("idx_txlog_time"),
        "the new index displaced the stamp aggregates from idx_txlog_time, \
         which would leave that index with no reader at all: {aggregate}"
    );
}

/// A v17 stamp over a database that never ran the rung is refused at open.
///
/// The counterpart of `a_v14_stamp_over_a_v13_index_set_is_refused_at_open`,
/// and pinned for the same reason: `verify` compares declared index names
/// against what the file holds, so this needs no new list — and the guarantee
/// worth having is that a mis-stamped database is a sentence at open time
/// rather than a reconstruction that is quietly a third slower with nothing to
/// say about it.
#[tokio::test]
async fn a_v17_stamp_over_a_v16_index_set_is_refused_at_open() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    conn.execute("DROP INDEX idx_txlog_fold_partition", ())
        .await
        .unwrap();

    let err = macrame::schema::run_migrations(&conn)
        .await
        .expect_err("a v17 stamp over a missing index was accepted");
    let message = err.to_string();
    assert!(
        message.contains("idx_txlog_fold_partition"),
        "the refusal does not name the missing index: {message}"
    );
}

// ---------------------------------------------------------------------------
// v17 → v18 — the archive gets the lineage it archives (0.15.30, W16.6, D-273)
// ---------------------------------------------------------------------------

/// The rung is what stops `archive_branch` reading the whole ledger to find
/// twenty rows.
///
/// Index-only, so *what it is for* is a plan, exactly as on the two rungs
/// above, and the fixture is built the same way: a real database wound back by
/// `DROP INDEX` plus a stamp, which is what a v17 database is, because this
/// rung changes nothing else.
///
/// Three assertions, and the third is the one that makes this rung different
/// from an ordinary index.
///
/// 1. **Before**, both statements scan a trunk-sized table for a lineage-sized
///    answer — `links` and `transaction_log`, six statements between them,
///    which is why a twenty-row lineage cost 22.0 ms at an 8,000-edge trunk.
/// 2. **After**, both seek. The indexes are **partial** (`WHERE branch_id <>
///    'main'`), so this is not merely "the index exists": it is only reachable
///    from a query that restates that predicate, and
///    `archive_branch_session` is written to.
/// 3. **The cutoff path must not move.** `archive_session` archives across
///    every lineage *including* the trunk, so if either of its statements
///    started using one of these indexes it would silently stop seeing most of
///    the ledger. A partial index cannot be reached from a query that does not
///    imply its predicate — this asserts that property rather than trusting it.
#[tokio::test]
async fn a_v17_database_climbs_to_v18_and_the_branch_archive_stops_scanning_the_trunk() {
    // The two shapes, copied — the originals are inline in
    // `archive_branch_session` and `EXPLAIN QUERY PLAN` cannot reach them.
    // `index_plan_tests` bounds the same copies against their source with
    // `include_str!` fragments, so a divergence is caught there.
    const LINEAGE_LINKS: &str =
        "DELETE FROM links WHERE branch_id = ?1 AND branch_id <> 'main'";
    const LINEAGE_LOG: &str =
        "DELETE FROM transaction_log WHERE branch_id = ?1 AND branch_id <> 'main'";

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    for index in ["idx_links_branch", "idx_txlog_branch"] {
        conn.execute(&format!("DROP INDEX {index}"), ()).await.unwrap();
    }
    conn.execute("PRAGMA user_version = 17", ()).await.unwrap();

    for (label, sql) in [("links", LINEAGE_LINKS), ("the log", LINEAGE_LOG)] {
        let before = plan_string(&conn, sql).await;
        assert!(
            before.contains("SCAN"),
            "the fixture is not starting from the v17 plan — expected the \
             archive to scan {label} for one lineage, got: {before}"
        );
    }

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    for (sql, index) in [
        (LINEAGE_LINKS, "idx_links_branch"),
        (LINEAGE_LOG, "idx_txlog_branch"),
    ] {
        let after = plan_string(&conn, sql).await;
        assert!(
            after.contains(index) && after.contains("branch_id=?"),
            "the rung created {index} and the archive did not take it — an \
             index nothing seeks on is D-089's failure, not a schema change: \
             {after}"
        );
    }

    // The half the rung could take away by accident.
    for (label, sql) in [
        (
            "the cutoff's links sweep",
            "SELECT source_id FROM links WHERE recorded_at < ?1",
        ),
        (
            "the cutoff's log sweep",
            "SELECT seq_id FROM transaction_log WHERE recorded_at < ?1",
        ),
    ] {
        let plan = plan_string(&conn, sql).await;
        assert!(
            !plan.contains("idx_links_branch") && !plan.contains("idx_txlog_branch"),
            "{label} archives every lineage including the trunk, and a partial \
             index that excludes the trunk cannot answer it: {plan}"
        );
    }
}

/// **v18 → v19: the single-open probe's plan is pinned against statistics, on
/// every database the ladder brings forward (D-274).**
///
/// The counterpart of the climb test above and pinned for the same reason — a
/// rung whose reader is on the bulk path must be asserted on a database that
/// *reached* it, not only on the baseline. The v18 body is reproduced here as
/// `TRIGGERS_V11` reproduces the v11 ones: it is the body the crate shipped
/// through 0.16.0, and the rung that replaces it must be shown to replace it
/// rather than stamp over it.
///
/// The populated part is the point. On an empty database the plan is already
/// right — the wrong index is empty and attractive to nobody — so the defect
/// is only visible after rows exist, and `sqlite_stat1` is what the fresh-file
/// bulk import never has (D-198). Both states are seeded by hand, because the
/// fixture helpers run the ladder and this test must hold the ladder back.
#[tokio::test]
async fn a_v18_database_climbs_to_v19_and_the_single_open_probe_stops_scanning_the_lineage() {
    // The v18 body — the pre-`+` trigger exactly as shipped through 0.16.0.
    const SINGLE_OPEN_V18: &str = r#"
    CREATE TRIGGER IF NOT EXISTS trg_links_single_open
    BEFORE INSERT ON links
    WHEN NEW.valid_to = '9999-12-31T23:59:59.999999Z'
         AND EXISTS (
             SELECT 1 FROM links_current
             WHERE source_id  = NEW.source_id
               AND target_id  = NEW.target_id
               AND edge_type  = NEW.edge_type
               AND branch_id  = NEW.branch_id
               AND valid_from <> NEW.valid_from
               AND valid_to   = '9999-12-31T23:59:59.999999Z'
         )
    BEGIN
        SELECT RAISE(ABORT, 'macrame: edge already has an open interval; retire it first');
    END;
    "#;
    // The probe, copied — the original is a trigger body and `EXPLAIN QUERY
    // PLAN` cannot reach it. Two of them, because the claim spans the rung:
    // the v18 probe plans the scan, the v19 probe must not.
    // `the_single_open_probe_seeks_rather_than_scans` bounds the v19 copy
    // against its source.
    const PROBE_V18: &str = "SELECT 1 FROM links_current \
         WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 \
           AND branch_id = ?4 AND valid_from <> ?4 \
           AND valid_to = '9999-12-31T23:59:59.999999Z'";
    const PROBE_V19: &str = "SELECT 1 FROM links_current \
         WHERE source_id = ?1 AND target_id = ?2 AND edge_type = ?3 \
           AND +branch_id = ?4 AND valid_from <> ?4 \
           AND valid_to = '9999-12-31T23:59:59.999999Z'";

    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    // Downgrade to v18 honestly: the pre-`+` body, the v18 stamp.
    conn.execute("DROP TRIGGER trg_links_single_open", ()).await.unwrap();
    conn.execute(SINGLE_OPEN_V18, ()).await.unwrap();
    conn.execute("PRAGMA user_version = 18", ()).await.unwrap();

    // Rows first — the plan is only wrong where the index has rows — then
    // the defect, observed before the climb can touch it.
    conn.execute("BEGIN", ()).await.unwrap();
    for i in 0..260 {
        conn.execute(
            "INSERT INTO concepts (id, title, content, valid_from, valid_to, \
             recorded_at, retired) VALUES (?1, ?2, '', ?3, ?4, ?3, 0)",
            libsql::params![format!("c{i:03}"), format!("C{i}"), TS, OPEN],
        )
        .await
        .unwrap();
    }
    for i in 1..210 {
        conn.execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, \
             valid_to, weight, properties, recorded_at) \
             VALUES (?1, ?2, 'LINKS', ?3, ?4, 1.0, '{}', ?3)",
            libsql::params!["c000", format!("c{i:03}"), TS, OPEN],
        )
        .await
        .unwrap();
    }
    conn.execute("COMMIT", ()).await.unwrap();

    let before = plan_string(&conn, PROBE_V18).await;
    assert!(
        before.contains("idx_lc_lineage_cut") && before.contains("branch_id=?"),
        "the fixture is not starting from the v18 plan — expected the probe \
         to be served by the branch-led index with one column bound, got: {before}"
    );

    macrame::schema::run_migrations(&conn).await.unwrap();
    assert_eq!(user_version(&conn).await, SCHEMA_VERSION);

    let after = plan_string(&conn, PROBE_V19).await;
    assert!(
        after.contains("idx_lc_open_interval") && after.contains("source_id=?"),
        "the rung restored the body and the probe still did not take its own \
         index: {after}"
    );
    assert!(
        !after.contains("idx_lc_lineage_cut"),
        "the climbed database still plans the whole-lineage scan: {after}"
    );

    // The body the rung put down, read back from the database rather than
    // assumed from the constant.
    let mut rows = conn
        .query(
            "SELECT sql FROM sqlite_master WHERE type = 'trigger' \
             AND name = 'trg_links_single_open'",
            (),
        )
        .await
        .unwrap();
    let body = rows.next().await.unwrap().unwrap().get::<String>(0).unwrap();
    assert!(
        body.contains("+branch_id = NEW.branch_id"),
        "the climbed database does not carry the pinned body: {body}"
    );

    // And the rule the trigger exists to enforce is untouched: the `+` is a
    // plan, not a permission. A second open interval on the same key, from the
    // same lineage, is still a refusal.
    let err = conn
        .execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, \
             valid_to, weight, properties, recorded_at) \
             VALUES ('c000', 'c001', 'LINKS', '2027-01-01T00:00:00.000000Z', \
                     '9999-12-31T23:59:59.999999Z', 1.0, '{}', ?1)",
            libsql::params![TS],
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("already has an open interval"),
        "the single-open guard stopped refusing with the plan pinned: {err}"
    );
}

/// A v18 stamp over a database that never ran the rung is refused at open.
///
/// The counterpart of `a_v17_stamp_over_a_v16_index_set_is_refused_at_open`,
/// and pinned for the same reason: a mis-stamped database should be a sentence
/// at open time rather than an archive that quietly reads the whole ledger with
/// nothing to say about it.
#[tokio::test]
async fn a_v18_stamp_over_a_v17_index_set_is_refused_at_open() {
    let harness = TestHarness::new();
    let conn = connect(&harness).await;
    macrame::schema::run_migrations(&conn).await.unwrap();

    conn.execute("DROP INDEX idx_txlog_branch", ()).await.unwrap();

    let err = macrame::schema::run_migrations(&conn)
        .await
        .expect_err("a v18 stamp over a missing index was accepted");
    let message = err.to_string();
    assert!(
        message.contains("idx_txlog_branch"),
        "the refusal does not name the missing index: {message}"
    );
}