ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
use core::time::Duration;

use super::{AckMode, Effect, Feeder, ItemId, Listen, NodeName, Station};

#[test]
fn an_item_id_is_its_sequence_position_and_orders_by_it() {
  let first = ItemId::new(0);
  let later = ItemId::new(9);
  assert_eq!(first.seq(), 0);
  assert!(first < later);
  assert_eq!(later.to_string(), "item#9");
}

#[test]
fn the_four_delivery_modes_name_themselves() {
  assert_eq!(Listen::Channel.as_str(), "channel");
  assert_eq!(Listen::Changes(Feeder::InGraph).as_str(), "changes");
  assert_eq!(Listen::Poll(Duration::from_secs(600)).as_str(), "poll");
  // The fourth is a second EDGE KIND rather than a fourth way of being fed the first kind's
  // messages — see `drive::invoke` — and it rides this vocabulary because the query path IS
  // topology.
  assert_eq!(Listen::Transient.as_str(), "transient");
  assert!(Listen::Channel.is_channel());
  assert!(Listen::Poll(Duration::from_secs(600)).is_poll());
  assert!(Listen::Transient.is_transient());
  assert!(!Listen::Transient.is_channel());
  assert_eq!(Listen::Changes(Feeder::InGraph).to_string(), "changes");
  assert_eq!(Listen::Transient.to_string(), "transient");
  // The NAME and not the schedule: an interval is a fact about one source's wiring, and two poll
  // sources at different cadences are the same WORD.
  assert_eq!(Listen::Poll(Duration::from_secs(1)).to_string(), "poll");
  assert_ne!(
    Listen::Poll(Duration::from_secs(1)),
    Listen::Poll(Duration::from_secs(2)),
    "the interval is part of the wiring even though it is not part of the name"
  );
}

#[test]
fn the_two_ack_modes_name_themselves() {
  assert_eq!(AckMode::Local.as_str(), "local");
  assert_eq!(AckMode::Chained.as_str(), "chained");
  assert!(AckMode::Chained.is_chained());
  assert_eq!(AckMode::Local.to_string(), "local");
}

#[test]
fn the_two_effects_name_themselves() {
  assert_eq!(Effect::Lands.as_str(), "lands");
  assert_eq!(Effect::Pure.as_str(), "pure");
  assert!(Effect::Pure.is_pure());
  assert_eq!(Effect::Lands.to_string(), "lands");
}

#[test]
fn the_station_an_effect_reaches_is_the_one_its_lifecycle_carries() {
  // ONE table, and three places spend it — a delivery's verdict, that verdict's station taken
  // without its payload, and a poll tick's own answer. The pin is that the two halves cannot drift:
  // a `reached` that answered `Persisted` for a pure node would let a sweep claim a durability
  // nobody achieved.
  for effect in [Effect::Lands, Effect::Pure] {
    assert_eq!(effect.reached(()).station(), effect.station());
  }
  assert_eq!(Effect::Lands.station(), Station::Persisted);
  assert_eq!(Effect::Pure.station(), Station::Processed);
}

#[test]
fn a_node_name_is_a_borrowed_view_and_keys_a_map_as_its_string() {
  use std::collections::HashMap;

  let mut runs: HashMap<&NodeName, usize> = HashMap::new();
  runs.insert(NodeName::new("decode"), 3);
  // `Borrow<str>` is what makes the name and the string one key, which is what a journal keyed
  // by (root, node) needs.
  assert_eq!(runs.get(NodeName::new("decode")), Some(&3));
  assert_eq!(NodeName::new("decode").as_str(), "decode");
}

/// The whole layer's ONE ordering, driven end to end by the pieces that ship rather than by a test
/// standing in for any of them.
///
/// Every other walk in this layer answers its own module's question with the neighbouring piece
/// simulated — a hand-answered ack in [`changes`](super::changes), a hand-built delivery in
/// [`resident`](super::resident), an in-memory map wherever a position is read. Each is right for
/// what it pins and none of them can observe the claim the layer actually rests on, because that
/// claim spans all of them: **a durable position moves only after the effect it covers is durable,
/// and it moves in a DATABASE.**
///
/// So this module wires the shipped pieces and nothing else — a real SQLite file, a real
/// [`SqliteFeed`](super::SqliteFeed) over a real table, a real [`ChangeIntake`](super::ChangeIntake),
/// a real [`Resident`](super::Resident) on a real OS thread, a real
/// [`SqlitePositions`](super::SqlitePositions), and a real [`Sweeper`](super::Sweeper) for the clock
/// — and reads the answer through a connection none of them owns. A file rather than
/// `sqlite::memory:` for the same reason: each in-memory connection is its OWN database, so the
/// three parties would agree about a position none of them shared, and a restart would have nothing
/// to re-open.
#[cfg(feature = "sqlite")]
mod durable {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{
    collections::BTreeMap,
    path::Path,
    sync::{Arc, Mutex},
    thread,
    time::Instant,
  };

  use sqlx::{Connection as _, Row as _, sqlite::SqliteConnection};

  use super::super::{
    ChangeIntake, Drained, Effect, ItemId, Resident, SqliteFeed, SqlitePositions, Sweeper, Track,
    channel, doorbell,
  };
  use crate::{Delivery, Emitter, Operator};

  /// The declared struct the table holds and the edge moves.
  #[derive(Debug, Clone, PartialEq, Eq)]
  pub(super) struct Scene {
    pub(super) id: i64,
    pub(super) title: String,
  }

  // Written rather than derived, as the emitter will write one: sqlx's derive rides a feature this
  // crate declines.
  impl<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow> for Scene {
    fn from_row(row: &'r sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {
      Ok(Self {
        id: row.try_get("id")?,
        title: row.try_get("title")?,
      })
    }
  }

  /// What the node KEEPS — its own store, keyed by the app's own id.
  ///
  /// Keyed and not appended, which is the half of exactly-once-effect this side owns: a replayed
  /// delivery overwrites the entry it wrote last time, so a re-read after a crash costs a write and
  /// never a duplicate. A test that asserts on the LENGTH of this is asserting exactly that.
  type Titles = Arc<Mutex<BTreeMap<i64, String>>>;

  /// A landing consumer: it writes what it saw and emits nothing.
  ///
  /// Emitting nothing is deliberate — it is what makes the station [`Persisted`], since a
  /// [`AsyncLands`](Effect::Lands) node with no emission has reached durability and said so, and it is
  /// the shape whose ack the whole ordering is stated about.
  ///
  /// The GATE is `None` everywhere except in the sweep's own walk, and it is what lets that walk
  /// state a "not yet" rather than only a "yes eventually": with it, the ack provably arrives after
  /// the intake's first pass has already settled, which is where a quiescent store leaves every
  /// answer.
  ///
  /// [`Persisted`]: super::super::Station::Persisted
  struct Titling {
    titles: Titles,
    arrived: Option<flume::Sender<()>>,
    gate: Option<flume::Receiver<()>>,
  }

  impl Titling {
    /// A consumer that answers as soon as it is given something.
    fn new(titles: Titles) -> Self {
      Self {
        titles,
        arrived: None,
        gate: None,
      }
    }

    /// A consumer that reports its arrival and then waits to be let through, ONCE.
    fn gated(titles: Titles, arrived: flume::Sender<()>, gate: flume::Receiver<()>) -> Self {
      Self {
        titles,
        arrived: Some(arrived),
        gate: Some(gate),
      }
    }
  }

  impl Operator for Titling {
    type Error = core::convert::Infallible;
    type In = Scene;
    type Out = Scene;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      _emitter: &mut Emitter<Scene>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let item = item.into_value();
        if let Some(gate) = self.gate.take() {
          if let Some(arrived) = self.arrived.take() {
            arrived.send(()).expect("the walk is waiting");
          }
          gate
            .recv_timeout(Duration::from_secs(20))
            .expect("the gate opened");
        }
        self
          .titles
          .lock()
          .expect("the node's own store")
          .insert(item.id, item.title);
      }
      Ok(())
    }
  }

  /// A connection to the database at `path`, creating the file if it is not there.
  ///
  /// `connect_with` rather than a URI, so a temporary directory's path never has to survive being
  /// spliced into one. The busy timeout is what lets three connections share one file without a
  /// reader losing to the writer: SQLite serialises writers, and the default is to fail rather than
  /// to wait.
  pub(super) async fn open(path: &Path) -> SqliteConnection {
    let options = sqlx::sqlite::SqliteConnectOptions::new()
      .filename(path)
      .create_if_missing(true)
      .busy_timeout(Duration::from_secs(10));
    SqliteConnection::connect_with(&options)
      .await
      .expect("the database file")
  }

  /// Create the table if it is not there and append `rows` — what a WRITER does, on its own
  /// connection.
  pub(super) async fn append(path: &Path, rows: &[(i64, &str)]) {
    let mut db = open(path).await;
    sqlx::query("CREATE TABLE IF NOT EXISTS scene (id INTEGER PRIMARY KEY, title TEXT NOT NULL)")
      .execute(&mut db)
      .await
      .expect("the table");
    for (id, title) in rows {
      sqlx::query("INSERT INTO scene (id, title) VALUES (?, ?)")
        .bind(id)
        .bind(title)
        .execute(&mut db)
        .await
        .expect("the row");
    }
  }

  /// The durable position for `track`, read through a connection NEITHER the feed nor the positions
  /// map owns.
  ///
  /// That is the whole point of reading it here: `ChangeIntake::position` answers from the handle
  /// that wrote it, so it would report a position that never reached the disk exactly as happily.
  pub(super) async fn durable(path: &Path, node: &str, source: &str) -> Option<i64> {
    let mut watcher = open(path).await;
    sqlx::query("SELECT position FROM ingraph_position WHERE unit = ? AND source = ?")
      .bind(node)
      .bind(source)
      .fetch_optional(&mut watcher)
      .await
      .expect("the durable read")
      .map(|row| row.get::<i64, _>(0))
  }

  /// How many rows the positions table holds.
  pub(super) async fn position_rows(path: &Path) -> i64 {
    let mut watcher = open(path).await;
    sqlx::query("SELECT COUNT(*) FROM ingraph_position")
      .fetch_one(&mut watcher)
      .await
      .expect("the count")
      .get(0)
  }

  /// One PROCESS over `path`: an intake feeding a resident that stores, driven until the durable
  /// position reaches `until`, then shut down.
  ///
  /// Shutting down by dropping the intake is the shipped shutdown and not a test convenience: the
  /// intake owns the only [`Outbox`](super::super::Outbox), so dropping it disconnects the inbox,
  /// which is the one thing that ends a resident's loop.
  async fn process(path: &Path, titles: &Titles, until: i64) -> Drained {
    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> =
      SqliteFeed::new(open(path).await, "scene", "id", bell).expect("the feed");
    let positions = SqlitePositions::open(open(path).await)
      .await
      .expect("the positions table");
    let (out, inbox) = channel::<ItemId, Scene>(8);
    let resident = Resident::new("titles", Titling::new(titles.clone()), inbox)
      .with_effect(Effect::Lands)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _>::new(Track::new("titles", "scene"), feed, positions, out)
        .with_page(2);

    // Each pass sends whatever is new and settles whatever came back. The consumer answers on its
    // own thread, so the position reaches `until` a pass or two after the rows went out — which is
    // the ordering itself, observed rather than asserted.
    let deadline = Instant::now() + Duration::from_secs(20);
    loop {
      intake.drain().await.expect("the walk");
      if intake.position() == Some(&until) {
        break;
      }
      assert!(
        Instant::now() < deadline,
        "the position stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }

    drop(intake);
    engine.join().expect("the engine thread")
  }

  #[tokio::test]
  async fn the_loop_carries_a_real_table_to_a_position_that_is_in_the_database() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two"), (3, "three")]).await;

    let titles: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    let report = process(&path, &titles, 3).await;

    assert_eq!(report.items(), 3);
    assert_eq!(report.tally().processed(), 3);
    assert_eq!(report.tally().emitted(), 0, "a landing node that emits");
    assert_eq!(
      titles
        .lock()
        .expect("the store")
        .values()
        .cloned()
        .collect::<Vec<_>>(),
      ["one", "two", "three"]
    );

    // The assertion the whole module exists for: the position is a ROW, visible to somebody who
    // holds neither of the handles that wrote it.
    assert_eq!(durable(&path, "titles", "scene").await, Some(3));
    assert_eq!(position_rows(&path).await, 1);
  }

  #[tokio::test]
  async fn a_restart_resumes_past_the_durable_position_and_re_reads_nothing() {
    // A process ends, another begins over the same file with new connections everywhere. What the
    // second one may NOT do is walk the rows the first one already answered for: that is what the
    // durable position is for, and re-reading them would be work nobody asked for.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two")]).await;

    let first: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    process(&path, &first, 2).await;
    assert_eq!(durable(&path, "titles", "scene").await, Some(2));

    append(&path, &[(3, "three")]).await;
    let second: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    let report = process(&path, &second, 3).await;

    assert_eq!(report.items(), 1, "only the row written since");
    assert_eq!(
      second
        .lock()
        .expect("the store")
        .keys()
        .copied()
        .collect::<Vec<_>>(),
      [3]
    );
    assert_eq!(durable(&path, "titles", "scene").await, Some(3));
    // Five advances across two processes, and the table still holds one row: keyed replace on
    // `(unit, source)` is the storage law applied to the cursor, and a COUNT is what proves it.
    assert_eq!(position_rows(&path).await, 1);
  }

  #[tokio::test]
  async fn two_units_over_one_table_keep_positions_that_do_not_collide() {
    // The key is BOTH halves, so a second node reading the same store starts from the beginning
    // rather than from the first node's answer. Keyed on the source alone, the second walk below
    // would see nothing at all.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two")]).await;

    let titles: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    process(&path, &titles, 2).await;

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> =
      SqliteFeed::new(open(&path).await, "scene", "id", bell).expect("the feed");
    let positions = SqlitePositions::open(open(&path).await)
      .await
      .expect("the positions table");
    let (out, inbox) = channel::<ItemId, Scene>(8);
    let other: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    let resident = Resident::new("captions", Titling::new(other.clone()), inbox)
      .with_effect(Effect::Lands)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _>::new(
      Track::new("captions", "scene"),
      feed,
      positions,
      out,
    );

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&2) {
      intake.drain().await.expect("the second node's walk");
      assert!(Instant::now() < deadline, "the second node stalled");
      thread::sleep(Duration::from_millis(5));
    }
    drop(intake);
    engine.join().expect("the engine thread");

    assert_eq!(other.lock().expect("the store").len(), 2, "from the start");
    assert_eq!(durable(&path, "titles", "scene").await, Some(2));
    assert_eq!(durable(&path, "captions", "scene").await, Some(2));
    assert_eq!(position_rows(&path).await, 2, "one row per track");
  }

  /// Long enough for a pass that touches nothing but an empty pull and an empty window to finish,
  /// short enough to keep the walk cheap.
  ///
  /// It is a bound on LOCAL work with no cross-thread dependency in it — the intake's first pass has
  /// already delivered by the time the consumer reports arrival, so what remains is one `WHERE id >
  /// ?` that returns no rows and one harvest of an unanswered oneshot.
  const QUIESCED: Duration = Duration::from_millis(200);

  async fn pause(how_long: Duration) {
    // `spawn_blocking` rather than a bare sleep: this walk's runtime is single-threaded, so blocking
    // it would be blocking the intake task the walk is waiting on.
    tokio::task::spawn_blocking(move || thread::sleep(how_long))
      .await
      .expect("the pause");
  }

  #[tokio::test]
  async fn a_quiescent_store_needs_the_sweep_before_an_answer_becomes_durable() {
    // The liveness floor, and it is load-bearing rather than decorative. An intake in `run` parks on
    // its doorbell, and a doorbell is rung by WRITERS — so where nobody is writing, the consumer's
    // ack sits in a oneshot nobody is coming back to collect and the position never becomes durable.
    // The sweep is the thing that comes back.
    //
    // The GATE is what lets that be stated as a "not yet" rather than only as a "yes eventually":
    // the consumer is held inside `accept` until the intake's first pass has settled, so the answer
    // provably arrives with the intake already parked. Without it this walk passes whether or not a
    // ring re-drains anything, because the ack races the first pass and usually wins.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two")]).await;

    let titles: Titles = Arc::new(Mutex::new(BTreeMap::new()));
    let (hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> =
      SqliteFeed::new(open(&path).await, "scene", "id", bell).expect("the feed");
    let positions = SqlitePositions::open(open(&path).await)
      .await
      .expect("the positions table");
    let (out, inbox) = channel::<ItemId, Scene>(8);
    let (report_arrival, arrived) = flume::bounded::<()>(1);
    let (open_gate, gate) = flume::bounded::<()>(1);
    let resident = Resident::new(
      "titles",
      Titling::gated(titles.clone(), report_arrival, gate),
      inbox,
    )
    .with_effect(Effect::Lands)
    .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _>::new(Track::new("titles", "scene"), feed, positions, out);
    // The hint is held HERE and never rung: for now this walk is the store's only writer, and it has
    // stopped writing.
    let driving = tokio::spawn(async move {
      let outcome = intake.run().await;
      (outcome, intake)
    });

    // The consumer is now inside `accept`, so the page has been delivered and cannot have been
    // answered. Waiting past that leaves the intake parked with an empty window.
    let waiting =
      tokio::task::spawn_blocking(move || arrived.recv_timeout(Duration::from_secs(20)));
    waiting.await.expect("the wait").expect("the page arrived");
    pause(QUIESCED).await;
    assert_eq!(
      durable(&path, "titles", "scene").await,
      None,
      "nothing has been answered yet"
    );

    open_gate.send(()).expect("the consumer is waiting");
    pause(QUIESCED).await;
    assert_eq!(
      titles.lock().expect("the store").len(),
      2,
      "the consumer's own write is durable"
    );
    // THE ASSERTION THIS WALK EXISTS FOR. The effect has landed and the ack has been sent, and the
    // durable position is still nothing — because the party that owns the position is parked, and
    // nobody has rung it.
    assert_eq!(
      durable(&path, "titles", "scene").await,
      None,
      "an answer nobody collected is not a position"
    );

    let sweeper = Sweeper::spawn(Duration::from_millis(5), vec![Box::new(hint)]);
    let deadline = Instant::now() + Duration::from_secs(20);
    loop {
      if durable(&path, "titles", "scene").await == Some(2) {
        break;
      }
      assert!(Instant::now() < deadline, "the sweep never brought it back");
      pause(Duration::from_millis(5)).await;
    }

    // Dropping the clock drops the hint it was ringing, which is what makes the doorbell go SILENT
    // and ends `run` — the shutdown path of a feed nobody will ever write again.
    drop(sweeper);
    let (outcome, intake) = driving.await.expect("the intake task");
    outcome.expect("the intake ran to silence");
    assert_eq!(intake.position(), Some(&2));
    drop(intake);
    engine.join().expect("the engine thread");
  }
}

/// The BLOB storage node on the same socket, with the blob write lane that already ships.
///
/// Nothing new was needed to put it there: [`AsyncBlobEngine::put`](crate::AsyncBlobEngine) takes a record and hands
/// back a future, which is the shape [`AsyncLands::land`](super::AsyncLands) consumes, so the lane is a
/// loop over `put` that names the positions it got through. The per-item answer falls out of the
/// seam being per record rather than being designed for it.
///
/// Ungated, as the backend is: a local filesystem names no database.
mod blob {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{fs, path::PathBuf, thread};

  use super::super::{
    Answer, AsyncLands, Commit, Delivery, Item, ItemId, Payload, Resident, Station, ack_channel,
    channel,
  };
  use crate::{
    AsyncBlobEngine, AsyncBlobStore, AsyncLocate, BlobRecord, Connected, Emitter, Identifiable,
    KeySegments, LocalFsBlob, LocalFsBlobError, LocalFsBlobRecord, LocalFsStore, Operator,
    Segments, Transformer,
  };

  /// The artifact family — the first path level under the store's root.
  const SLOT: &str = "thumbnail";

  /// A two-level key: the media it came from, then the frame — lineage order, parents first.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct ThumbKey {
    media: String,
    frame: i64,
  }

  impl KeySegments for ThumbKey {
    fn segments(&self, out: &mut Segments) {
      out.push(&self.media);
      out.push(&self.frame);
    }
  }

  /// The ancestor half of that key: the media, with the frame left off.
  struct ThumbLineage {
    #[expect(
      dead_code,
      reason = "`Transformer` names the type; no blob seam projects the lineage half"
    )]
    media: String,
  }

  /// What the edge moves and the lane places: an addressed record carrying its own bytes.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Thumbnail {
    key: ThumbKey,
    bytes: Vec<u8>,
  }

  impl Identifiable for Thumbnail {
    type Id = i64;

    fn id_ref(&self) -> &i64 {
      &self.key.frame
    }
  }

  impl Transformer for Thumbnail {
    type Graphql = ();
    type Key = ThumbKey;
    type Lineage = ThumbLineage;
    type Record = Self;

    fn key(&self) -> ThumbKey {
      self.key.clone()
    }
  }

  impl BlobRecord for Thumbnail {
    type Bytes = Vec<u8>;

    fn bytes(&self) -> &Vec<u8> {
      &self.bytes
    }

    fn extension() -> Option<&'static str> {
      Some("png")
    }
  }

  /// The blob write lane: the shipped [`AsyncBlobEngine`] face behind the socket's seam.
  ///
  /// It holds the connection-manager and the per-slot handle, which is the two-layer division the
  /// store seams already draw — the manager is opened once and the handle is stateless — so a lane
  /// is exactly those two values and a loop.
  struct BlobLane {
    store: LocalFsStore,
    handle: LocalFsBlob,
  }

  impl<R> AsyncLands<R> for BlobLane
  where
    R: LocalFsBlobRecord + Sync,
    R::Bytes: AsRef<[u8]>,
  {
    type Error = LocalFsBlobError;

    async fn land(&mut self, items: &[R]) -> Commit<Self::Error> {
      let mut committed = Vec::new();
      for (position, record) in items.iter().enumerate() {
        // The scope is `()` because a standalone blob store threads no cross-face transaction and
        // each publish is its own atomically-visible node — the backend's own words, and what makes
        // "which of these got through" answerable one record at a time.
        match self
          .handle
          .put(Connected::new(&self.store, ()), record)
          .await
        {
          Ok(()) => committed.push(position),
          Err(error) => return Commit::only(committed, error),
        }
      }
      Commit::all()
    }
  }

  /// Raw bytes as they arrive, before they are addressed.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Frame {
    media: String,
    frame: i64,
    bytes: Vec<u8>,
  }

  /// The operator: it ADDRESSES, and the lane places.
  struct Thumbing;

  impl Operator for Thumbing {
    type Error = core::convert::Infallible;
    type In = Frame;
    type Out = Thumbnail;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Thumbnail>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let frame = item.into_value();
        emitter.emit(Thumbnail {
          key: ThumbKey {
            media: frame.media,
            frame: frame.frame,
          },
          bytes: frame.bytes,
        });
      }
      Ok(())
    }
  }

  /// Where the shipped address resolver says `key`'s blob lives — asked of the store rather than
  /// spelled by the walk, so the assertion is about the file the lane placed and not about a path
  /// this test believes in.
  fn located(store: &LocalFsStore, key: &ThumbKey) -> PathBuf {
    let handle = LocalFsBlob::new(SLOT);
    AsyncLocate::<Thumbnail>::locate(
      &handle,
      Connected::new(store, ()),
      key,
      Thumbnail::extension(),
    )
    .expect("the address")
  }

  #[test]
  fn a_blob_unit_answers_after_its_bytes_are_on_disk() {
    // B3: the same socket, a different family. Bytes in, files placed, and an ack that means the
    // files are there — read back through the store's own address resolver.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let root = dir.path().join("blobs");
    let store = LocalFsStore::open(&root).expect("the blob store");
    let handle = store.blob(SLOT);

    let (feed, inbox) = channel::<ItemId, Frame>(8);
    let resident = Resident::new("thumbs", Thumbing, inbox)
      .land(BlobLane {
        store: store.clone(),
        handle,
      })
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let frames = [
      Frame {
        media: "movie".to_owned(),
        frame: 1,
        bytes: b"first".to_vec(),
      },
      Frame {
        media: "movie".to_owned(),
        frame: 2,
        bytes: b"second".to_vec(),
      },
    ];
    let (ack, answers) = ack_channel();
    let items = frames
      .iter()
      .zip(1u64..)
      .map(|(frame, seq)| Item::new(ItemId::new(seq), frame.clone()))
      .collect();
    feed
      .deliver(Delivery::new(Payload::Batch(items), ack))
      .expect("the resident is listening");

    let answer = loop {
      match answers.take() {
        Answer::Settled(settled) => break settled,
        Answer::HungUp => panic!("the node hung up"),
        Answer::Waiting => thread::sleep(Duration::from_millis(2)),
      }
    };
    assert_eq!(answer.released().len(), 2);
    assert_eq!(answer.observation().station(), Some(Station::Persisted));

    for frame in &frames {
      let key = ThumbKey {
        media: frame.media.clone(),
        frame: frame.frame,
      };
      let placed = located(&store, &key);
      assert_eq!(
        fs::read(&placed).expect("the placed blob"),
        frame.bytes,
        "at {placed:?}"
      );
    }

    drop(feed);
    let report = engine.join().expect("the engine thread");
    assert_eq!(report.tally().refused(), 0);
    // The framework never named the record: the lane addressed it from the key's own fields, which
    // is why nothing in `drive` had to learn what a thumbnail is.
    assert_eq!(report.tally().emitted(), 0, "nothing went on a wire");
  }
}

/// The storage socket against a REAL store: a node whose durability is its own write, and whose
/// answer is a fact about a database rather than about a dispatch.
///
/// [`durable`](super::tests::durable) proved the position moves after the effect. What it could not
/// prove is that the effect is the CONSUMER's own — its node wrote inside `accept`, into a map, and
/// nothing in the layer knew that a write had happened at all. Here the write goes through the
/// shipped seam, into SQLite, and the two things a socket is for are visible: an ack that waits for
/// a commit, and a replay that a keyed replace absorbs.
///
/// A file rather than `sqlite::memory:` for [`durable`](super::tests::durable)'s reason, and the
/// fixtures are shared with it for the same one — the walks differ in what they drive, not in what
/// a database is.
#[cfg(feature = "sqlite")]
mod socket {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{path::Path, sync::Arc, thread, time::Instant};

  use sqlx::{Row as _, sqlite::SqliteConnection};

  use super::{
    super::{
      AckMode, AsyncLands, ChangeIntake, Commit, ItemId, RecordingTap, Resident, SqliteFeed,
      SqlitePositions, Station, Taps, Track, channel, doorbell,
    },
    durable::{Scene, append, durable, open, position_rows},
  };
  use crate::{Delivery, Emitter, Operator};

  /// What a scene BECOMES: the record the store holds.
  ///
  /// A second type and not the source row, so the edge between the two nodes carries a real
  /// transformation and the landing node is writing something its upstream made rather than
  /// forwarding what it read.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Title {
    id: i64,
    text: String,
  }

  /// The PURE node: it computes and lands nothing.
  struct Shouting;

  impl Operator for Shouting {
    type Error = core::convert::Infallible;
    type In = Scene;
    type Out = Title;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Title>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let scene = item.into_value();
        emitter.emit(Title {
          id: scene.id,
          text: scene.title.to_uppercase(),
        });
      }
      Ok(())
    }
  }

  /// The LANDING node's operator: it hands its input to the lane and computes nothing.
  ///
  /// That is the shape an emitted store node has. The record is already made by the time it reaches
  /// the store, and what the node adds is the write — which is why the socket lives in the loop
  /// rather than in an operator body.
  struct Keeping;

  impl Operator for Keeping {
    type Error = core::convert::Infallible;
    type In = Title;
    type Out = Title;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Title>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let title = item.into_value();
        emitter.emit(title);
      }
      Ok(())
    }
  }

  /// A row the store would not take, with sqlx's own error kept rather than rendered.
  #[derive(Debug, derive_more::Display)]
  #[display("the title table refused a row: {_0}")]
  struct TitleRefused(sqlx::Error);

  impl core::error::Error for TitleRefused {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
      Some(&self.0)
    }
  }

  /// The write lane: a KEYED REPLACE per record, on the node's own connection.
  ///
  /// Keyed and not appended, which is the half of exactly-once-EFFECT this side owns — a delivery
  /// replayed after a lost ack rewrites the rows it already wrote, so the cost of the crash is one
  /// write and never a duplicate. The walk below asserts exactly that, with a `COUNT`.
  ///
  /// A statement per record rather than one for the page, because that is what makes the answer
  /// per item: the loop stops at the first row the store refuses and names the ones behind it,
  /// which is a [`Commit::only`]. A backend with a batch statement answers the same shape from one
  /// round trip.
  struct TitleLane {
    conn: SqliteConnection,
  }

  impl TitleLane {
    /// Open the title table on `path`, creating it if it is not there.
    async fn open(path: &Path) -> Self {
      let mut conn = open(path).await;
      sqlx::query("CREATE TABLE IF NOT EXISTS title (id INTEGER PRIMARY KEY, text TEXT NOT NULL)")
        .execute(&mut conn)
        .await
        .expect("the title table");
      Self { conn }
    }
  }

  impl AsyncLands<Title> for TitleLane {
    type Error = TitleRefused;

    async fn land(&mut self, items: &[Title]) -> Commit<Self::Error> {
      let mut committed = Vec::new();
      for (position, title) in items.iter().enumerate() {
        let written = sqlx::query(
          "INSERT INTO title (id, text) VALUES (?, ?) \
           ON CONFLICT (id) DO UPDATE SET text = excluded.text",
        )
        .bind(title.id)
        .bind(title.text.as_str())
        .execute(&mut self.conn)
        .await;
        match written {
          Ok(_) => committed.push(position),
          Err(error) => return Commit::only(committed, TitleRefused(error)),
        }
      }
      Commit::all()
    }
  }

  /// Every title in the database, in id order, read through a connection the lane does not own.
  async fn titles(path: &Path) -> Vec<String> {
    let mut watcher = open(path).await;
    sqlx::query("SELECT text FROM title ORDER BY id")
      .fetch_all(&mut watcher)
      .await
      .expect("the titles")
      .iter()
      .map(|row| row.get::<String, _>(0))
      .collect()
  }

  /// How many rows the title table holds — the flat count a replay must not grow.
  async fn title_rows(path: &Path) -> i64 {
    let mut watcher = open(path).await;
    sqlx::query("SELECT COUNT(*) FROM title")
      .fetch_one(&mut watcher)
      .await
      .expect("the count")
      .get(0)
  }

  /// Poll `check` until it holds, or give up.
  async fn until(deadline: Duration, what: &str, mut check: impl AsyncFnMut() -> bool) {
    let give_up = Instant::now() + deadline;
    while !check().await {
      assert!(Instant::now() < give_up, "{what}");
      thread::sleep(Duration::from_millis(5));
    }
  }

  #[tokio::test]
  async fn a_replay_after_a_lost_ack_rewrites_its_rows_and_the_position_lands_once() {
    // The crash the whole ordering is built around: the write commits, and the party that owns the
    // position never comes back to collect the answer. What makes that safe is not the drive layer
    // — it is the lane writing BY KEY, so the re-delivery the missing position causes is a rewrite.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two"), (3, "three")]).await;

    // PROCESS ONE. The intake's pass runs to completion BEFORE the consumer exists, so the answer
    // provably arrives at a window nobody is holding any more — the crash, not a race.
    {
      let (_hint, bell) = doorbell();
      let feed: SqliteFeed<Scene> =
        SqliteFeed::new(open(&path).await, "scene", "id", bell).expect("the feed");
      let positions = SqlitePositions::open(open(&path).await)
        .await
        .expect("the positions table");
      let (out, inbox) = channel::<ItemId, Scene>(8);
      let mut intake = ChangeIntake::<sqlx::Sqlite, _, _>::new(
        Track::new("titles", "scene"),
        feed,
        positions,
        out,
      );
      intake.drain().await.expect("the page went out");
      assert_eq!(intake.position(), None, "nobody has answered anything");

      let resident = Resident::new("titles", Shouting, inbox)
        .land(TitleLane::open(&path).await)
        .with_sweep(Duration::from_millis(5));
      let engine = thread::spawn(move || {
        let mut resident = resident;
        resident.run()
      });
      until(
        Duration::from_secs(20),
        "the first write never landed",
        async || title_rows(&path).await == 3,
      )
      .await;

      // The effect is durable and the answer has been sent. The position is nothing, because the
      // intake is not running and never will be again.
      assert_eq!(durable(&path, "titles", "scene").await, None);
      drop(intake);
      engine.join().expect("the engine thread");
    }

    // PROCESS TWO: everything new over the same file. With no durable position it starts at the
    // beginning of the feed's order, so every row is read and written a SECOND time.
    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> =
      SqliteFeed::new(open(&path).await, "scene", "id", bell).expect("the feed");
    let positions = SqlitePositions::open(open(&path).await)
      .await
      .expect("the positions table");
    let (out, inbox) = channel::<ItemId, Scene>(8);
    let resident = Resident::new("titles", Shouting, inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });
    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _>::new(Track::new("titles", "scene"), feed, positions, out);
    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&3) {
      intake.drain().await.expect("the replay");
      assert!(
        Instant::now() < deadline,
        "the replay stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }
    drop(intake);
    let report = engine.join().expect("the engine thread");

    assert_eq!(report.items(), 3, "the whole source was read again");
    // THE ASSERTION THIS WALK EXISTS FOR: three rows were written twice and there are three of
    // them. An appending lane would leave six here.
    assert_eq!(title_rows(&path).await, 3);
    assert_eq!(titles(&path).await, ["ONE", "TWO", "THREE"]);
    assert_eq!(durable(&path, "titles", "scene").await, Some(3));
    assert_eq!(position_rows(&path).await, 1, "one row per track");
  }

  #[tokio::test]
  async fn the_indexing_direction_runs_end_to_end_to_a_position_the_write_earned() {
    // The whole B-floor in one walk, with every piece the shipped one: source rows, a change
    // intake, a PURE operator on its own thread, a bounded channel edge, a LANDING consumer whose
    // durability is its own write into SQLite, the ack that write earns, the window it releases,
    // and the durable position that follows.
    //
    // The pure node is CHAINED, and that is what makes the last link an implication rather than a
    // coincidence: it withholds the intake's ack until its own output has been released downstream,
    // so a position of 3 cannot be reached unless three rows are in the title table.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    append(&path, &[(1, "one"), (2, "two"), (3, "three")]).await;

    let (to_store, store_inbox) = channel::<ItemId, Title>(8);
    let storing = Resident::new("titles", Keeping, store_inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let store_engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let tap = Arc::new(RecordingTap::new());
    let (to_pure, pure_inbox) = channel::<ItemId, Scene>(8);
    let pure = Resident::new("shout", Shouting, pure_inbox)
      .publish(to_store)
      .with_ack(AckMode::Chained)
      .with_taps(Taps::new().with(tap.clone()))
      .with_sweep(Duration::from_millis(5));
    let pure_engine = thread::spawn(move || {
      let mut pure = pure;
      pure.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> =
      SqliteFeed::new(open(&path).await, "scene", "id", bell).expect("the feed");
    let positions = SqlitePositions::open(open(&path).await)
      .await
      .expect("the positions table");
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _>::new(
      Track::new("shout", "scene"),
      feed,
      positions,
      to_pure,
    )
    .with_page(2);

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&3) {
      intake.drain().await.expect("the walk");
      assert!(
        Instant::now() < deadline,
        "the chain stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }

    drop(intake);
    let pure_report = pure_engine.join().expect("the pure engine");
    let store_report = store_engine.join().expect("the storing engine");

    assert_eq!(titles(&path).await, ["ONE", "TWO", "THREE"]);
    assert_eq!(title_rows(&path).await, 3);
    assert_eq!(durable(&path, "shout", "scene").await, Some(3));
    assert_eq!(position_rows(&path).await, 1);
    assert_eq!(pure_report.tally().emitted(), 3);
    assert_eq!(store_report.tally().processed(), 3);
    assert_eq!(store_report.tally().refused(), 0);
    // The station the pure node was answered with is the landing node's, and it is the one a write
    // earns. `Processed` here would mean the ack crossed the edge without the durability.
    //
    // And the node named is `titles` and NOT `shout`: the tap hangs on the pure node, but the
    // observation describes the work its downstream consumer did. Attributed to the sender, every
    // journal row this arrangement wrote would name the node that lands nothing.
    assert!(
      tap
        .seen()
        .iter()
        .all(|(node, station)| node == "titles" && *station == Station::Persisted),
      "the answers the outputs earned: {:?}",
      tap.seen()
    );
    assert!(!tap.is_empty(), "the tap saw nothing at all");
  }
}

/// The JOURNAL's strong half against a real control store: the `(root, node)` row a node's own
/// completion writes, and the transaction it shares with the position.
///
/// [`socket`](super::tests::socket) proved a position moves only after the effect is durable. What
/// it could not say is HOW FAR a given media got through a given node, because nothing in the layer
/// could name a media. Here a node projects the root out of the record it emits, and the row that
/// projection keys is written where the position is written — in ONE transaction, so a crash cannot
/// leave a cursor claiming more than the record does.
#[cfg(feature = "sqlite")]
mod record {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{
    path::Path,
    sync::{Arc, Mutex},
    thread,
    time::{Instant, SystemTime},
  };

  use sqlx::{Connection as _, Row as _, sqlite::SqliteConnection};

  use super::{
    super::{
      AckMode, Answer, AsyncLands, ChangeIntake, Commit, Delivery, Item, ItemId, JournalRow,
      JournalTap, JournalWriter, Ledger, NodeName, Payload, Positions, Resident, Station, Track,
      ack_channel, channel, doorbell, journal_queue,
    },
    durable::open,
  };
  use crate::{Arrival, Attributes, Emitter, Operator, SqliteFeed};

  /// A source row: its own id, the MEDIA it descends from, and its content.
  ///
  /// The media column is what makes the root real rather than a stand-in — the projection below
  /// reads it, exactly as an emitted wrapper reads a declared key's first column.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Shot {
    id: i64,
    media: i64,
    title: String,
  }

  impl<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow> for Shot {
    fn from_row(row: &'r sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {
      Ok(Self {
        id: row.try_get("id")?,
        media: row.try_get("media")?,
        title: row.try_get("title")?,
      })
    }
  }

  /// What the landing node keeps.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Title {
    id: i64,
    media: i64,
    text: String,
  }

  /// The deployment's own journal row — three columns, `(media, node)` the key.
  #[derive(Debug, Clone, PartialEq, Eq)]
  struct Journal {
    media: i64,
    unit: String,
    station: String,
  }

  impl JournalRow<i64> for Journal {
    fn of(root: &i64, node: &NodeName, arrival: &Arrival, _at: SystemTime) -> Self {
      Self {
        media: *root,
        unit: node.as_str().to_owned(),
        station: arrival.station().as_str().to_owned(),
      }
    }
  }

  /// A control-store statement failed.
  #[derive(Debug, derive_more::Display)]
  #[display("the control store refused a statement: {_0}")]
  struct ControlRefused(sqlx::Error);

  impl core::error::Error for ControlRefused {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
      Some(&self.0)
    }
  }

  /// The CONTROL STORE: the position table and the journal table, on ONE connection.
  ///
  /// One connection is what makes the co-location expressible at all — SQLite has no transaction
  /// spanning two of them — and one transaction is what makes it true.
  struct Control {
    conn: SqliteConnection,
    /// Make the POSITION statement fail while the journal rows succeed.
    ///
    /// The apparatus the torn-state walk is built on: without a way to break exactly one of the two
    /// writes, a walk asserting they agree passes whether or not they share a transaction.
    poison: bool,
  }

  impl Control {
    async fn open(path: &Path) -> Self {
      let mut conn = open(path).await;
      for statement in [
        "CREATE TABLE IF NOT EXISTS ingraph_position (\
           unit TEXT NOT NULL, source TEXT NOT NULL, position INTEGER NOT NULL, \
           PRIMARY KEY (unit, source)) WITHOUT ROWID",
        "CREATE TABLE IF NOT EXISTS ingraph_journal (\
           media INTEGER NOT NULL, unit TEXT NOT NULL, station TEXT NOT NULL, \
           PRIMARY KEY (media, unit)) WITHOUT ROWID",
      ] {
        sqlx::query(statement)
          .execute(&mut conn)
          .await
          .expect("the control tables");
      }
      Self {
        conn,
        poison: false,
      }
    }

    const fn poisoning(mut self) -> Self {
      self.poison = true;
      self
    }
  }

  /// Upsert `rows` into `tx` — KEYED REPLACE on `(media, node)`, which is what makes the row the
  /// LAST STATE rather than an append.
  async fn write_journal(
    tx: &mut sqlx::SqliteConnection,
    rows: &[Journal],
  ) -> Result<(), ControlRefused> {
    for row in rows {
      sqlx::query(
        "INSERT INTO ingraph_journal (media, unit, station) VALUES (?, ?, ?) \
         ON CONFLICT (media, unit) DO UPDATE SET station = excluded.station",
      )
      .bind(row.media)
      .bind(row.unit.as_str())
      .bind(row.station.as_str())
      .execute(&mut *tx)
      .await
      .map_err(ControlRefused)?;
    }
    Ok(())
  }

  /// `sqlx` has no blocking face, so the blocking spellings are the awaited bodies under the drive
  /// layer's own driver — `SqlitePositions`' posture, which is what a real async backend does.
  impl Ledger for Control {
    type Error = ControlRefused;
    type Row = Journal;

    fn record(&mut self, rows: &[Journal]) -> Result<(), ControlRefused> {
      crate::drive::lane::block_on(self.record_async(rows))
    }

    async fn record_async(&mut self, rows: &[Journal]) -> Result<(), ControlRefused> {
      if rows.is_empty() {
        return Ok(());
      }
      let mut tx = self.conn.begin().await.map_err(ControlRefused)?;
      write_journal(&mut tx, rows).await?;
      tx.commit().await.map_err(ControlRefused)
    }
  }

  impl Positions<i64> for Control {
    fn position(&mut self, track: &Track) -> Result<Option<i64>, ControlRefused> {
      crate::drive::lane::block_on(self.position_async(track))
    }

    fn advance(&mut self, track: &Track, to: i64, rows: &[Journal]) -> Result<(), ControlRefused> {
      crate::drive::lane::block_on(self.advance_async(track, to, rows))
    }

    async fn position_async(&mut self, track: &Track) -> Result<Option<i64>, ControlRefused> {
      let row = sqlx::query("SELECT position FROM ingraph_position WHERE unit = ? AND source = ?")
        .bind(track.node())
        .bind(track.source())
        .fetch_optional(&mut self.conn)
        .await
        .map_err(ControlRefused)?;
      row
        .map(|row| row.try_get::<i64, _>(0))
        .transpose()
        .map_err(ControlRefused)
    }

    async fn advance_async(
      &mut self,
      track: &Track,
      to: i64,
      rows: &[Journal],
    ) -> Result<(), ControlRefused> {
      let poison = self.poison;
      let mut tx = self.conn.begin().await.map_err(ControlRefused)?;
      write_journal(&mut tx, rows).await?;
      // The position, in the SAME transaction. Poisoned, the statement violates `position NOT NULL`
      // and the whole transaction — the journal rows included — is rolled back.
      let position = if poison {
        sqlx::query("INSERT INTO ingraph_position (unit, source) VALUES (?, ?)")
          .bind(track.node())
          .bind(track.source())
          .execute(&mut *tx)
          .await
      } else {
        sqlx::query(
          "INSERT INTO ingraph_position (unit, source, position) VALUES (?, ?, ?) \
           ON CONFLICT (unit, source) DO UPDATE SET position = excluded.position",
        )
        .bind(track.node())
        .bind(track.source())
        .bind(to)
        .execute(&mut *tx)
        .await
      };
      position.map_err(ControlRefused)?;
      tx.commit().await.map_err(ControlRefused)
    }
  }

  /// The PURE node: it addresses a shot into a title and lands nothing.
  struct Shouting;

  impl Operator for Shouting {
    type Error = core::convert::Infallible;
    type In = Shot;
    type Out = Title;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Title>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let shot = item.into_value();
        emitter.emit(Title {
          id: shot.id,
          media: shot.media,
          text: shot.title.to_uppercase(),
        });
      }
      Ok(())
    }
  }

  /// The LANDING node's operator: it hands its input to the lane.
  struct Keeping;

  impl Operator for Keeping {
    type Error = core::convert::Infallible;
    type In = Title;
    type Out = Title;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Title>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let title = item.into_value();
        emitter.emit(title);
      }
      Ok(())
    }
  }

  /// A row the title table would not take.
  #[derive(Debug, derive_more::Display)]
  #[display("the title table refused a row: {_0}")]
  struct TitleRefused(sqlx::Error);

  impl core::error::Error for TitleRefused {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
      Some(&self.0)
    }
  }

  /// The CONTENT lane — a keyed replace per record, on the node's own connection.
  struct TitleLane {
    conn: SqliteConnection,
  }

  impl TitleLane {
    async fn open(path: &Path) -> Self {
      let mut conn = open(path).await;
      sqlx::query(
        "CREATE TABLE IF NOT EXISTS title (\
           id INTEGER PRIMARY KEY, media INTEGER NOT NULL, text TEXT NOT NULL)",
      )
      .execute(&mut conn)
      .await
      .expect("the title table");
      Self { conn }
    }
  }

  impl AsyncLands<Title> for TitleLane {
    type Error = TitleRefused;

    async fn land(&mut self, items: &[Title]) -> Commit<Self::Error> {
      let mut committed = Vec::new();
      for (position, title) in items.iter().enumerate() {
        let written = sqlx::query(
          "INSERT INTO title (id, media, text) VALUES (?, ?, ?) \
           ON CONFLICT (id) DO UPDATE SET text = excluded.text",
        )
        .bind(title.id)
        .bind(title.media)
        .bind(title.text.as_str())
        .execute(&mut self.conn)
        .await;
        match written {
          Ok(_) => committed.push(position),
          Err(error) => return Commit::only(committed, TitleRefused(error)),
        }
      }
      Commit::all()
    }
  }

  /// The projection an emitted wrapper supplies: the ROOT column of the record's declared key.
  ///
  /// One hand-written hook, two nodes — the intake projects out of the row it pulled and the
  /// resident out of the record it lands, and both answer with the same media.
  struct Media {
    seen: Arc<Mutex<Vec<(i64, String, Station)>>>,
  }

  impl Attributes<Shot> for Media {
    type Root = i64;

    fn root(&self, shot: &Shot) -> i64 {
      shot.media
    }

    fn observe(&self, root: &i64, worker: &NodeName, arrival: &Arrival) {
      self.seen.lock().expect("the seen list").push((
        *root,
        worker.as_str().to_owned(),
        arrival.station(),
      ));
    }
  }

  impl Attributes<Title> for Media {
    type Root = i64;

    fn root(&self, title: &Title) -> i64 {
      title.media
    }

    fn observe(&self, root: &i64, worker: &NodeName, arrival: &Arrival) {
      self.seen.lock().expect("the seen list").push((
        *root,
        worker.as_str().to_owned(),
        arrival.station(),
      ));
    }
  }

  /// Create the source table if it is not there and append `rows`.
  async fn append(path: &Path, rows: &[(i64, i64, &str)]) {
    let mut db = open(path).await;
    sqlx::query(
      "CREATE TABLE IF NOT EXISTS shot (\
         id INTEGER PRIMARY KEY, media INTEGER NOT NULL, title TEXT NOT NULL)",
    )
    .execute(&mut db)
    .await
    .expect("the table");
    for (id, media, title) in rows {
      sqlx::query("INSERT INTO shot (id, media, title) VALUES (?, ?, ?)")
        .bind(id)
        .bind(media)
        .bind(title)
        .execute(&mut db)
        .await
        .expect("the row");
    }
  }

  /// Every journal row, in `(media, node)` order, read through a connection no writer owns.
  async fn journal_of(path: &Path) -> Vec<(i64, String, String)> {
    let mut watcher = open(path).await;
    sqlx::query("SELECT media, unit, station FROM ingraph_journal ORDER BY media, unit")
      .fetch_all(&mut watcher)
      .await
      .expect("the journal rows")
      .iter()
      .map(|row| {
        (
          row.get::<i64, _>(0),
          row.get::<String, _>(1),
          row.get::<String, _>(2),
        )
      })
      .collect()
  }

  /// The durable position, read the same way.
  async fn position(path: &Path, node: &str, source: &str) -> Option<i64> {
    let mut watcher = open(path).await;
    sqlx::query("SELECT position FROM ingraph_position WHERE unit = ? AND source = ?")
      .bind(node)
      .bind(source)
      .fetch_optional(&mut watcher)
      .await
      .expect("the durable read")
      .map(|row| row.get::<i64, _>(0))
  }

  /// How many journal rows there are — the count a keyed replace holds flat.
  async fn journal_rows(path: &Path) -> i64 {
    let mut watcher = open(path).await;
    sqlx::query("SELECT COUNT(*) FROM ingraph_journal")
      .fetch_one(&mut watcher)
      .await
      .expect("the count")
      .get(0)
  }

  async fn title_rows(path: &Path) -> i64 {
    let mut watcher = open(path).await;
    sqlx::query("SELECT COUNT(*) FROM title")
      .fetch_one(&mut watcher)
      .await
      .expect("the count")
      .get(0)
  }

  #[tokio::test]
  async fn the_position_and_the_run_record_move_together_or_not_at_all() {
    // THE TORN-STATE WALK. The content write lands; the control transaction then fails. What the
    // co-location buys is that the position and the journal are the SAME transaction, so the
    // crash leaves them agreeing — both old — instead of leaving a cursor claiming a completion the
    // record has no row for.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(&path, &[(1, 100, "one"), (2, 100, "two")]).await;

    let seen = Arc::new(Mutex::new(Vec::new()));
    let (out, inbox) = channel::<ItemId, Shot>(8);
    let storing = Resident::new("titles", Shouting, inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(&path).await, "shot", "id", bell).expect("the feed");
    let control = Control::open(&path).await.poisoning();
    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _, _>::new(Track::new("titles", "shot"), feed, control, out)
        .attributing(Media { seen });

    // Drain until the answers come back and the poisoned control refuses. The content is durable
    // by then, which is the crash's precondition.
    let deadline = Instant::now() + Duration::from_secs(20);
    let refusal = loop {
      match intake.drain().await {
        Err(refusal) => break refusal,
        Ok(_) => {
          assert!(Instant::now() < deadline, "the control never refused");
          thread::sleep(Duration::from_millis(5));
        }
      }
    };
    assert!(refusal.is_positions(), "{refusal}");

    assert_eq!(title_rows(&path).await, 2, "the content is durable");
    // THE ASSERTION THIS WALK EXISTS FOR. Neither moved, so they agree.
    assert_eq!(position(&path, "titles", "shot").await, None);
    assert_eq!(journal_of(&path).await, [], "no row without the position");

    drop(intake);
    engine.join().expect("the engine thread");
  }

  #[tokio::test]
  async fn a_healthy_control_lands_the_position_and_the_row_in_the_same_pass() {
    // The other side of the same fact, and the one a reader wants: two medias, two nodes' worth of
    // work, and one row per `(media, node)` however many rows each media contributed.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(
      &path,
      &[(1, 100, "one"), (2, 100, "two"), (3, 200, "three")],
    )
    .await;

    let seen = Arc::new(Mutex::new(Vec::new()));
    let (out, inbox) = channel::<ItemId, Shot>(8);
    let storing = Resident::new("titles", Shouting, inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(&path).await, "shot", "id", bell).expect("the feed");
    let control = Control::open(&path).await;
    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _, _>::new(Track::new("titles", "shot"), feed, control, out)
        .attributing(Media { seen: seen.clone() });

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&3) {
      intake.drain().await.expect("the walk");
      assert!(
        Instant::now() < deadline,
        "stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }
    drop(intake);
    engine.join().expect("the engine thread");

    assert_eq!(position(&path, "titles", "shot").await, Some(3));
    // Two medias, ONE node: two rows, whatever the page shapes were. A media contributing two rows
    // contributes one `(media, node)` row.
    assert_eq!(
      journal_of(&path).await,
      [
        (100, "titles".to_owned(), "persisted".to_owned()),
        (200, "titles".to_owned(), "persisted".to_owned()),
      ]
    );
    assert_eq!(title_rows(&path).await, 3);
  }

  /// One PROCESS over `path`: an intake feeding a storing resident, driven until the durable
  /// position reaches `until`, then shut down.
  async fn process(path: &Path, until: i64) {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let (out, inbox) = channel::<ItemId, Shot>(8);
    let storing = Resident::new("titles", Shouting, inbox)
      .land(TitleLane::open(path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(path).await, "shot", "id", bell).expect("the feed");
    let control = Control::open(path).await;
    let mut intake =
      ChangeIntake::<sqlx::Sqlite, _, _, _>::new(Track::new("titles", "shot"), feed, control, out)
        .with_page(2)
        .attributing(Media { seen });

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&until) {
      intake.drain().await.expect("the walk");
      assert!(
        Instant::now() < deadline,
        "stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }
    drop(intake);
    engine.join().expect("the engine thread");
  }

  #[tokio::test]
  async fn a_second_run_rewrites_the_row_rather_than_growing_the_table() {
    // The count is the whole assertion. `|roots| × |nodes|` is the size of this table and it is
    // ACTIVITY-INDEPENDENT: a media that comes back with more work still has one row per node,
    // because the entry is the LAST STATE and is replaced by its `(media, node)` key.
    //
    // An appending write would leave four rows here and every one of them would still look right on
    // its own — which is why this walk asserts a COUNT rather than a membership.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(
      &path,
      &[(1, 100, "one"), (2, 100, "two"), (3, 200, "three")],
    )
    .await;

    process(&path, 3).await;
    assert_eq!(journal_rows(&path).await, 2, "two medias, one node");
    assert_eq!(position(&path, "titles", "shot").await, Some(3));

    // The same two medias come back with more work, and the process runs again from its cursor.
    append(&path, &[(4, 100, "four"), (5, 200, "five")]).await;
    process(&path, 5).await;

    assert_eq!(journal_rows(&path).await, 2, "the same two rows, rewritten");
    assert_eq!(
      journal_of(&path).await,
      [
        (100, "titles".to_owned(), "persisted".to_owned()),
        (200, "titles".to_owned(), "persisted".to_owned()),
      ]
    );
    assert_eq!(title_rows(&path).await, 5);
    assert_eq!(position(&path, "titles", "shot").await, Some(5));
  }

  #[tokio::test]
  async fn a_channel_fed_unit_writes_its_completion_row_with_a_lone_upsert() {
    // A node with no durable position — its inputs came over a channel, so there is no cursor for
    // its row to be atomic WITH. The row is still the strong half: written before the ack goes out,
    // through the same contract, and never through a tap.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");

    let seen = Arc::new(Mutex::new(Vec::new()));
    let (feed, inbox) = channel::<ItemId, Title>(8);
    let resident = Resident::new("titles", Keeping, inbox)
      .land(TitleLane::open(&path).await)
      .attributing(Media { seen: seen.clone() })
      .recording_to(Control::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let (ack, answers) = ack_channel();
    let items = [
      Title {
        id: 1,
        media: 100,
        text: "ONE".to_owned(),
      },
      Title {
        id: 2,
        media: 100,
        text: "TWO".to_owned(),
      },
      Title {
        id: 3,
        media: 200,
        text: "THREE".to_owned(),
      },
    ]
    .into_iter()
    .zip(1u64..)
    .map(|(title, seq)| Item::new(ItemId::new(seq), title))
    .collect();
    feed
      .deliver(Delivery::new(Payload::Batch(items), ack))
      .expect("the resident is listening");

    let answer = loop {
      match answers.take() {
        Answer::Settled(settled) => break settled,
        Answer::HungUp => panic!("the node hung up"),
        Answer::Waiting => thread::sleep(Duration::from_millis(2)),
      }
    };
    assert_eq!(answer.observation().station(), Some(Station::Persisted));
    assert_eq!(answer.released().len(), 3);
    assert_eq!(answer.worker().as_str(), "titles");

    drop(feed);
    engine.join().expect("the engine thread");

    // The ack certifies the row, so by the time the answer was readable the row was on disk. Two
    // medias, one node, one row each — and the delivery of three records wrote two rows.
    assert_eq!(
      journal_of(&path).await,
      [
        (100, "titles".to_owned(), "persisted".to_owned()),
        (200, "titles".to_owned(), "persisted".to_owned()),
      ]
    );
    assert_eq!(
      position(&path, "titles", "shot").await,
      None,
      "a channel-fed node keeps no cursor"
    );
    assert_eq!(title_rows(&path).await, 3);
  }
  /// The DIAGNOSTIC half's lane: the same `ingraph_journal` table, reached through the ordinary write
  /// seam.
  ///
  /// One table and two writers, which is the design rather than an accident: the row is keyed, so a
  /// completion the control transaction wrote and an observation the queue carried are the same row
  /// when they are about the same `(media, node)` and different rows when they are not.
  struct JournalLane {
    conn: SqliteConnection,
  }

  impl AsyncLands<Journal> for JournalLane {
    type Error = ControlRefused;

    async fn land(&mut self, items: &[Journal]) -> Commit<Self::Error> {
      let mut committed = Vec::new();
      for (position, row) in items.iter().enumerate() {
        let written = sqlx::query(
          "INSERT INTO ingraph_journal (media, unit, station) VALUES (?, ?, ?) \
           ON CONFLICT (media, unit) DO UPDATE SET station = excluded.station",
        )
        .bind(row.media)
        .bind(row.unit.as_str())
        .bind(row.station.as_str())
        .execute(&mut self.conn)
        .await;
        match written {
          Ok(_) => committed.push(position),
          Err(error) => return Commit::only(committed, ControlRefused(error)),
        }
      }
      Commit::all()
    }
  }

  /// A pure operator that REFUSES one media — the failure the badge-red row is about.
  struct Shaky {
    broken: i64,
  }

  /// What [`Shaky`] answers with.
  #[derive(Debug, derive_more::Display)]
  #[display("the operator cannot read media {_0}")]
  struct Unreadable(i64);

  impl core::error::Error for Unreadable {}

  impl Operator for Shaky {
    type Error = Unreadable;
    type In = Shot;
    type Out = Title;

    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Title>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let shot = item.into_value();
        if shot.media == self.broken {
          return Err(Unreadable(shot.media));
        }
        emitter.emit(Title {
          id: shot.id,
          media: shot.media,
          text: shot.title.to_uppercase(),
        });
      }
      Ok(())
    }
  }

  #[tokio::test]
  async fn the_indexing_direction_writes_a_run_record_through_both_of_its_halves() {
    // THE WHOLE LINE, with every piece the shipped one: source rows, a change intake, a CHAINED
    // pure operator on its own thread, a bounded channel edge, a landing consumer whose durability
    // is its own SQLite write, the ack that write earns, the position it moves — and the journal
    // written twice over, once by each half, into one keyed table.
    //
    // The two halves are visible in what they wrote. The intake's control transaction holds the
    // COMPLETIONS of the node it feeds: `(media, shout, processed)`, in the same transaction as the
    // position. The pure node's own queue carries what its DOWNSTREAM answered:
    // `(media, titles, persisted)` — attributed to the media by a projection read off the record
    // `shout` emitted, and written by a writer on a thread that can never reach back into the loop.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(
      &path,
      &[(1, 100, "one"), (2, 100, "two"), (3, 200, "three")],
    )
    .await;
    // The tables have to exist before the writer opens its lane over them.
    drop(Control::open(&path).await);

    let (queue, drain) = journal_queue::<Journal>(64);
    let mut writer = JournalWriter::new(
      drain,
      JournalLane {
        conn: open(&path).await,
      },
    )
    .with_patience(Duration::from_millis(5));
    let scribe = thread::spawn(move || writer.run());

    let (to_store, store_inbox) = channel::<ItemId, Title>(8);
    let storing = Resident::new("titles", Keeping, store_inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let store_engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (to_pure, pure_inbox) = channel::<ItemId, Shot>(8);
    let pure = Resident::new("shout", Shouting, pure_inbox)
      .publish(to_store)
      .with_ack(AckMode::Chained)
      .attributing(JournalTap::<Title, i64, Journal>::new(
        |title| title.media,
        queue.clone(),
      ))
      .with_sweep(Duration::from_millis(5));
    let pure_engine = thread::spawn(move || {
      let mut pure = pure;
      pure.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(&path).await, "shot", "id", bell).expect("the feed");
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _, _>::new(
      Track::new("shout", "shot"),
      feed,
      Control::open(&path).await,
      to_pure,
    )
    .with_page(2)
    .attributing(JournalTap::<Shot, i64, Journal>::new(
      |shot| shot.media,
      queue.clone(),
    ));

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&3) {
      intake.drain().await.expect("the walk");
      assert!(
        Instant::now() < deadline,
        "the chain stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }

    drop(intake);
    pure_engine.join().expect("the pure engine");
    store_engine.join().expect("the storing engine");
    drop(queue);
    let scribed = scribe.join().expect("the writer thread");
    assert!(scribed.written() > 0, "the diagnostic half wrote nothing");

    assert_eq!(title_rows(&path).await, 3);
    assert_eq!(position(&path, "shout", "shot").await, Some(3));
    // Two medias, two nodes, FOUR rows — and the count is what says the two halves agreed about the
    // key rather than each keeping a table of its own.
    assert_eq!(journal_rows(&path).await, 4);
    assert_eq!(
      journal_of(&path).await,
      [
        (100, "shout".to_owned(), "processed".to_owned()),
        (100, "titles".to_owned(), "persisted".to_owned()),
        (200, "shout".to_owned(), "processed".to_owned()),
        (200, "titles".to_owned(), "persisted".to_owned()),
      ]
    );
  }

  #[tokio::test]
  async fn a_failure_at_the_pure_unit_lands_as_the_badge_red_row() {
    // The row a reader is actually looking for. The pure operator refuses media 200, so its answer
    // to the intake is `Failed` naming `shout` as the worker — and the root is projected out of the
    // ROW the intake pulled, which is the only place a media exists on this path.
    //
    // The strong half writes NOTHING for it, and that is the division: a failure holds the window
    // and will be tried again, so it is not a completion. The row is the diagnostic half's, which
    // is what makes it a row that may be lost — and the media's own completion, when it comes, is
    // the one that cannot be.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(&path, &[(1, 100, "one"), (2, 200, "two")]).await;
    drop(Control::open(&path).await);

    let (queue, drain) = journal_queue::<Journal>(64);
    let mut writer = JournalWriter::new(
      drain,
      JournalLane {
        conn: open(&path).await,
      },
    )
    .with_patience(Duration::from_millis(5));
    let scribe = thread::spawn(move || writer.run());

    let (to_store, store_inbox) = channel::<ItemId, Title>(8);
    let storing = Resident::new("titles", Keeping, store_inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let store_engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (to_pure, pure_inbox) = channel::<ItemId, Shot>(8);
    let pure = Resident::new("shout", Shaky { broken: 200 }, pure_inbox)
      .publish(to_store)
      .with_sweep(Duration::from_millis(5));
    let pure_engine = thread::spawn(move || {
      let mut pure = pure;
      pure.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(&path).await, "shot", "id", bell).expect("the feed");
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _, _>::new(
      Track::new("shout", "shot"),
      feed,
      Control::open(&path).await,
      to_pure,
    )
    .attributing(JournalTap::<Shot, i64, Journal>::new(
      |shot| shot.media,
      queue.clone(),
    ));

    // The failed item holds the window, so the position never passes it. Drain until the badge-red
    // row is on disk.
    let deadline = Instant::now() + Duration::from_secs(20);
    loop {
      intake.drain().await.expect("the walk");
      if journal_of(&path)
        .await
        .iter()
        .any(|(media, node, station)| *media == 200 && node == "shout" && station == "failed")
      {
        break;
      }
      assert!(Instant::now() < deadline, "the failure never reached a row");
      thread::sleep(Duration::from_millis(5));
    }

    drop(intake);
    pure_engine.join().expect("the pure engine");
    store_engine.join().expect("the storing engine");
    drop(queue);
    scribe.join().expect("the writer thread");

    let rows = journal_of(&path).await;
    assert!(
      rows.contains(&(200, "shout".to_owned(), "failed".to_owned())),
      "the badge-red row: {rows:?}"
    );
    // The healthy media's own work is untouched by its neighbour's failure.
    assert_eq!(title_rows(&path).await, 1);
  }

  #[tokio::test]
  async fn a_run_record_with_no_writer_at_all_still_has_every_final_state() {
    // THE PROOF THAT DIAGNOSTICS ARE ONLY EVER SUPPLEMENTARY. The queue's drain is dropped before
    // anything runs, so not one observation reaches a store through it — and the completions are
    // all there anyway, because the strong half wrote them in the transaction that moved the
    // position and never went near a queue.
    //
    // A design where the final state rode the queue would leave this table empty, and nothing about
    // the pipeline would look wrong: the content is durable, the position is right, and the record
    // would simply have lost the answer it exists to give.
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("shots.db");
    append(&path, &[(1, 100, "one"), (2, 200, "two")]).await;

    let (queue, drain) = journal_queue::<Journal>(4);
    drop(drain);

    let (out, inbox) = channel::<ItemId, Shot>(8);
    let storing = Resident::new("titles", Shouting, inbox)
      .land(TitleLane::open(&path).await)
      .with_sweep(Duration::from_millis(5));
    let engine = thread::spawn(move || {
      let mut storing = storing;
      storing.run()
    });

    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Shot> =
      SqliteFeed::new(open(&path).await, "shot", "id", bell).expect("the feed");
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _, _>::new(
      Track::new("titles", "shot"),
      feed,
      Control::open(&path).await,
      out,
    )
    .attributing(JournalTap::<Shot, i64, Journal>::new(
      |shot| shot.media,
      queue,
    ));

    let deadline = Instant::now() + Duration::from_secs(20);
    while intake.position() != Some(&2) {
      intake.drain().await.expect("the walk");
      assert!(
        Instant::now() < deadline,
        "stalled at {:?}",
        intake.position()
      );
      thread::sleep(Duration::from_millis(5));
    }
    drop(intake);
    engine.join().expect("the engine thread");

    assert_eq!(
      journal_of(&path).await,
      [
        (100, "titles".to_owned(), "persisted".to_owned()),
        (200, "titles".to_owned(), "persisted".to_owned()),
      ],
      "every final state, with no diagnostic writer in the process"
    );
    assert_eq!(position(&path, "titles", "shot").await, Some(2));
  }
}

/// The POLL mode against a REAL store: a reaper whose whole input is a clock, whose whole authority
/// is what its context lends it, and whose upstream this deployment never named.
///
/// Every other walk in this module is fed. This one is not: nothing produces for it, nothing acks
/// it, and the node it draws from is NOT PRESENT in this deployment — presence being enablement,
/// which is the case the mode exists for, because collecting a dead node's garbage is exactly the
/// work that outlives the node. What it proves that no unit test can is that the two halves meet
/// over a database: two entries on one node run at their own cadences, the one whose context lends
/// a writing handle deletes rows a third connection can see are gone, and the one lent a reading
/// handle can only look.
#[cfg(feature = "sqlite")]
mod reaper {
  use crate::{Context, drive::Drives};
  use core::time::Duration;

  use std::{
    path::Path,
    sync::{Arc, Mutex},
    thread,
    time::Instant,
  };

  use sqlx::{Row as _, sqlite::SqliteConnection};

  use super::{
    super::{
      AckMode, Drained, Enablement, ItemId, Listen, Plan, PollUpstream, RecordingTap, Resident,
      Schedule, Seats, Station, Swept, Taps, UpstreamWiring, channel,
    },
    durable::{Scene, open},
  };
  use crate::{
    ChannelGraph, Delivery, DriverKind, EdgeId, Emitter, FanoutKind, GraphBuilder, NodeId, Operator,
  };

  /// A connection taken out of the context for ONE call and put back when the call is over.
  ///
  /// The context is lent by reference, and a statement wants `&mut` — so the handle moves out and
  /// back rather than being borrowed through a guard held across the await. That is a fact about
  /// sqlx and this hand-made context, not about the seam: the emitted context will hand back a
  /// typed handle and do whatever its own backend needs behind it.
  struct Lent<'a> {
    slot: &'a Mutex<Option<SqliteConnection>>,
    conn: Option<SqliteConnection>,
  }

  impl core::ops::Deref for Lent<'_> {
    type Target = SqliteConnection;

    fn deref(&self) -> &SqliteConnection {
      self.conn.as_ref().expect("lent for the call")
    }
  }

  impl core::ops::DerefMut for Lent<'_> {
    fn deref_mut(&mut self) -> &mut SqliteConnection {
      self.conn.as_mut().expect("lent for the call")
    }
  }

  impl Drop for Lent<'_> {
    fn drop(&mut self) {
      *self.slot.lock().expect("the context's slot") = self.conn.take();
    }
  }

  /// The per-node context, one slot per upstream — a hand-made stand-in for the emitted one.
  ///
  /// The emitted one mints a `AsyncLands<Granted>` impl per `write` grant, keyed on the granted node's
  /// RECORD type and stated once for the whole node rather than per upstream. This context holds raw
  /// connections and implements nothing, so its split is by what each of its own methods does —
  /// `expired` deletes and `census` only counts — which is as much of that division as a hand-made
  /// stand-in can carry. What it stands in for is the LENDING, which is the part this walk is
  /// about.
  struct Granted {
    expired: Mutex<Option<SqliteConnection>>,
    census: Mutex<Option<SqliteConnection>>,
  }

  impl Granted {
    async fn open(path: &Path) -> Self {
      Self {
        expired: Mutex::new(Some(open(path).await)),
        census: Mutex::new(Some(open(path).await)),
      }
    }

    /// The writing handle this node's context lends, for the reaping entry.
    fn expired(&self) -> Lent<'_> {
      Lent {
        slot: &self.expired,
        conn: self.expired.lock().expect("the write slot").take(),
      }
    }

    /// The reading handle, for the entry that only looks.
    fn census(&self) -> Lent<'_> {
      Lent {
        slot: &self.census,
        conn: self.census.lock().expect("the read slot").take(),
      }
    }
  }

  #[derive(Debug, derive_more::Display)]
  #[display("the reaper's statement failed: {_0}")]
  struct Unreachable(sqlx::Error);

  impl core::error::Error for Unreachable {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
      Some(&self.0)
    }
  }

  /// The maintenance node. It holds its own state and nothing else — the handles arrive per tick.
  struct Reaping {
    looked: Arc<Mutex<Vec<PollUpstream>>>,
    counted: Arc<Mutex<Vec<i64>>>,
  }

  /// The two sources this node declares, by position: `poll#0` reaps and `poll#1` counts.
  const REAP: PollUpstream = PollUpstream::new(0);
  const COUNT: PollUpstream = PollUpstream::new(1);

  impl Operator for Reaping {
    type Error = core::convert::Infallible;
    type In = Scene;
    type Out = Scene;

    /// Never called in this walk: a poll edge carries no messages, and this node has no other
    /// source. It exists because a poll node is an ordinary declared node, which may also be fed.
    fn accept(
      &mut self,
      _ctx: &Context,
      delivery: Delivery<Self::In>,
      emitter: &mut Emitter<Scene>,
    ) -> Result<(), Self::Error> {
      for item in delivery.into_items() {
        let scene = item.into_value();
        emitter.emit(scene);
      }
      Ok(())
    }
  }

  /// The facts it states — the mount predicate is `O: Declared + Driven<O::Mode>`, so a hand-wired
  /// node says what it is too, in the mode a bare declaration has.
  impl crate::Declared for Reaping {
    const EFFECT: crate::Effect = crate::Effect::Pure;

    type Channels = crate::Unchanneled;
    type Mode = crate::Block;
    type Options = ();
    type Pair = crate::Buffered;
    type Wires<O> = crate::Downstream<O>;
    type Attribution<O> = ();
  }

  /// A hand-written lending, which is what a node with no `write` word has: no context is emitted,
  /// so the deployment's own value implements the seam and reads the position itself.
  impl Seats<Reaping> for Granted {
    type Error = Unreachable;
    /// Rows this look removed — the info the observation carries home.
    type Info = u64;

    async fn seat(
      &mut self,
      operator: &mut Reaping,
      source: PollUpstream,
    ) -> Result<Swept<u64>, Unreachable> {
      operator
        .looked
        .lock()
        .expect("the walk's record")
        .push(source);
      if source == REAP {
        let mut conn = self.expired();
        let done = sqlx::query("DELETE FROM scene WHERE title = ?")
          .bind("expired")
          .execute(&mut *conn)
          .await
          .map_err(Unreachable)?;
        return Ok(Swept::Ran(done.rows_affected()));
      }
      // The slot with no write behind it: this source's word granted a look and nothing more.
      let mut conn = self.census();
      let count: i64 = sqlx::query("SELECT COUNT(*) FROM scene")
        .fetch_one(&mut *conn)
        .await
        .map_err(Unreachable)?
        .get(0);
      operator
        .counted
        .lock()
        .expect("the walk's record")
        .push(count);
      Ok(Swept::Ran(0))
    }
  }

  /// `scene → reaper`, the one edge the reaper subscribes over.
  fn arrangement() -> ChannelGraph {
    let mut builder = GraphBuilder::new();
    let scenes = builder.source::<Reaping>("scene", DriverKind::Thread);
    let reaper = builder.node::<Reaping>("reaper", DriverKind::Thread);
    builder.edge(&scenes, &reaper, FanoutKind::Broadcast);
    builder.validate().expect("one edge validates")
  }

  /// Every title left in the table, read through a connection the reaper does not own.
  async fn titles(path: &Path) -> Vec<String> {
    let mut watcher = open(path).await;
    sqlx::query("SELECT title FROM scene ORDER BY id")
      .fetch_all(&mut watcher)
      .await
      .expect("the titles")
      .iter()
      .map(|row| row.get::<String, _>(0))
      .collect()
  }

  #[tokio::test]
  async fn a_reaper_over_a_disabled_upstream_runs_two_clocks_and_only_one_of_them_writes() {
    let dir = tempfile::tempdir().expect("a temporary directory");
    let path = dir.path().join("scenes.db");
    super::durable::append(
      &path,
      &[
        (1, "keep"),
        (2, "expired"),
        (3, "expired"),
        (4, "keep"),
        (5, "expired"),
      ],
    )
    .await;

    // The launch floor first, because it is half of what this walk is about. The deployment names
    // the REAPER and not its upstream — presence being enablement — and the reaper still starts: a
    // poll source over an unlaunched upstream is legal, and the reaper is exempt from the pure-leaf
    // refusal because its schedule and its grants are its observability.
    let wired = Plan::new(arrangement())
      .upstream(
        EdgeId::new(0),
        UpstreamWiring::new(Listen::Poll(Duration::from_millis(5)), AckMode::Local),
      )
      .with_enablement(Enablement::new().launching("reaper"))
      .validate()
      .expect("reaping does not need the dead alive");
    assert!(wired.is_enabled(NodeId::new(1)), "the reaper runs");
    assert!(!wired.is_enabled(NodeId::new(0)), "its upstream does not");

    let looked = Arc::new(Mutex::new(Vec::new()));
    let counted = Arc::new(Mutex::new(Vec::new()));
    let tap = Arc::new(RecordingTap::new());
    let (out, inbox) = channel::<ItemId, Scene>(8);
    let resident = Resident::new(
      "reaper",
      Reaping {
        looked: looked.clone(),
        counted: counted.clone(),
      },
      inbox,
    )
    .polling(
      // Coarse and far apart, with the assertions below stated as inequalities: nothing here waits
      // for a wall clock to be accurate, only for one hand to have gone round more often than the
      // other.
      Schedule::new()
        .every(Duration::from_millis(5))
        .every(Duration::from_millis(120)),
      Granted::open(&path).await,
    )
    .with_taps(Taps::new().with(tap.clone()))
    .with_sweep(Duration::from_secs(30));
    let engine = thread::spawn(move || {
      let mut resident = resident;
      resident.run()
    });

    let looks = |source: PollUpstream| {
      looked
        .lock()
        .expect("the walk's record")
        .iter()
        .filter(|&&seen| seen == source)
        .count()
    };
    let deadline = Instant::now() + Duration::from_secs(30);
    while looks(REAP) < 12 || looks(COUNT) < 1 {
      assert!(
        Instant::now() < deadline,
        "the two clocks never both ran: {} and {}",
        looks(REAP),
        looks(COUNT)
      );
      thread::sleep(Duration::from_millis(5));
    }

    // A poll-only node's outbox is its shutdown handle: no producer is holding its inbox open,
    // because the producer is exactly what this deployment turned off.
    drop(out);
    let report: Drained = engine.join().expect("the engine thread");

    let fast = looks(REAP);
    let slow = looks(COUNT);
    assert!(
      fast > slow,
      "each source keeps its own cadence: {fast} and {slow}"
    );
    assert_eq!(
      report.ticks(),
      fast + slow,
      "one look per upstream per pass"
    );
    assert_eq!(report.deliveries(), 0, "nothing was ever fed to it");

    // THE ASSERTION THIS WALK EXISTS FOR: the write went through the LENT handle and it is in the
    // database, seen from a connection neither the node nor its context owns.
    assert_eq!(titles(&path).await, ["keep", "keep"]);
    // And the read-only source's slot was exercised: every census it took saw the two survivors,
    // because the first reaping look ran before it.
    let census = counted.lock().expect("the walk's record").clone();
    assert!(!census.is_empty(), "the read-only slot was never used");
    assert!(census.iter().all(|&count| count == 2), "{census:?}");

    assert!(
      tap
        .seen()
        .iter()
        .all(|(node, station)| node == "reaper" && *station == Station::Processed),
      "{:?}",
      tap.seen()
    );
    assert_eq!(tap.len(), fast + slow, "every look was observed");
  }
}