polyc-query 2026.9.0

Read layer over the event log: a DataFusion engine for SQL over replayed partitions, and a per-conversation Parquet projection for participation-scoped search.
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
#![allow(clippy::pedantic, clippy::nursery, missing_docs)]

use polyc_state::revision::PartitionIncarnation;
use std::sync::Arc;

use super::store::{Coverage, CoverageState, ExcisionScan, SearchProjection, StoreError};
use super::terms::TermKey;
use super::*;

fn key() -> TermKey {
    TermKey::new([3u8; 32])
}

fn key_id() -> String {
    key().key_id()
}

const PARTITION: &str = "conv-web:11111111-2222-3333-4444-555555555555";

/// [`PARTITION`] as storage spells it.
///
/// Derived, never written out: the contract is that the projection holds a
/// conversation under its ENCODED name, so a literal here would pin one
/// spelling of the codec rather than the contract.
fn encoded_partition() -> String {
    polyc_eventlog_host::encode_partition(PARTITION)
        .expect("the fixture partition encodes")
        .to_string()
}

/// A projection rooted in a test-unique temp dir, removed on drop.
struct Fixture {
    projection: SearchProjection,
    dir: std::path::PathBuf,
}

impl Fixture {
    fn open(name: &str) -> Self {
        let dir = std::env::temp_dir().join(format!(
            "polychrome-search-projection-{name}-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        Self {
            projection: SearchProjection::open(dir.clone()).expect("open"),
            dir,
        }
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

fn coverage(indexed_through: u64) -> Coverage {
    Coverage {
        indexed_through,
        source_incarnation: PartitionIncarnation::from_bytes([9; 32]),
        available: true,
        excision_scanned_through: indexed_through,
    }
}

/// The coverage an indexed conversation carries, naming the state it got
/// instead when it is not indexed.
fn indexed(state: CoverageState) -> Coverage {
    match state {
        CoverageState::Indexed(coverage) => coverage,
        other => panic!("expected an indexed conversation, got {other:?}"),
    }
}

fn message(position: u64, turn: &str, text: &str) -> IndexedMessage {
    IndexedMessage {
        position,
        turn_id: turn.to_owned(),
        term_hashes: key().hash_text(text),
    }
}

/// The projection's real contract: what is appended must read back
/// identically, or a search answers from a file that no longer says what it
/// was written to say.
#[tokio::test]
async fn append_then_read_returns_the_rows_and_coverage_unchanged() {
    let fx = Fixture::open("round-trip");
    let expected = vec![
        message(3, "turn-a", "where did we decide the timeout"),
        message(9, "turn-b", "the deploy failed"),
    ];

    fx.projection
        .append(PARTITION, &expected, &coverage(42), &key_id())
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read"),
        Some(PostingsRecord { messages: expected })
    );
    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::Indexed(coverage(42))
    );
}

/// The reason segments exist: a turn appends only its delta, and the union
/// still reads as one conversation. A single rewritten file would cost O(N)
/// per turn and O(N squared) over a conversation's life.
#[tokio::test]
async fn appending_a_delta_leaves_earlier_segments_readable() {
    let fx = Fixture::open("delta");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("first");
    fx.projection
        .append(
            PARTITION,
            &[message(4, "turn-b", "beta")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("second");

    let read = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(
        read.messages.len(),
        2,
        "both segments must be visible: {:?}",
        read.messages
    );
    assert_eq!(read.messages[0].position, 1);
    assert_eq!(read.messages[1].position, 4);
    assert_eq!(
        indexed(
            fx.projection
                .coverage(PARTITION, &key_id())
                .await
                .expect("read"),
        )
        .indexed_through,
        6,
        "coverage is the newest segment's watermark"
    );
}

/// Recovery is at-least-once, so re-appending a range already indexed must
/// change nothing a reader sees.
#[tokio::test]
async fn re_appending_the_same_positions_is_idempotent() {
    let fx = Fixture::open("idempotent");
    let batch = vec![message(1, "turn-a", "alpha")];

    fx.projection
        .append(PARTITION, &batch, &coverage(3), &key_id())
        .await
        .expect("first");
    fx.projection
        .append(PARTITION, &batch, &coverage(3), &key_id())
        .await
        .expect("second");

    let read = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(
        read.messages, batch,
        "a replayed range must not duplicate a position"
    );
}

/// Compaction folds segments without changing what they cover.
#[tokio::test]
async fn compaction_preserves_content_and_coverage() {
    let fx = Fixture::open("compact");
    for (position, watermark) in [(1u64, 3u64), (4, 6), (7, 9)] {
        fx.projection
            .append(
                PARTITION,
                &[message(position, "turn-a", "alpha")],
                &coverage(watermark),
                &key_id(),
            )
            .await
            .expect("append");
    }
    let before = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read");

    fx.projection
        .compact(PARTITION, &key_id())
        .await
        .expect("compact");

    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read"),
        before,
        "compaction must not change what is readable"
    );
    assert_eq!(
        indexed(
            fx.projection
                .coverage(PARTITION, &key_id())
                .await
                .expect("read"),
        )
        .indexed_through,
        9
    );
    let files = std::fs::read_dir(
        fx.projection
            .root()
            .join(format!("conversation_id={}", encoded_partition())),
    )
    .expect("list")
    .count();
    assert_eq!(files, 1, "compaction must leave exactly one segment");
}

/// A write answers with what the directory now holds, so the caller deciding
/// whether to fold never has to keep a counter beside the store.
///
/// A counter has to be bounded, and past its bound it stops counting — which
/// silently disables the trigger it feeds for the rest of the process's life.
/// These numbers come off the listing the write already performs.
#[tokio::test]
async fn a_write_reports_the_directory_it_produced() {
    let fx = Fixture::open("write-stats");

    // A rebuild is the base: one segment, and nothing above it to merge.
    let rebuilt = fx
        .projection
        .rebuild(
            PARTITION,
            &[message(1, "turn-a", "alpha beta")],
            &coverage(2),
            &key_id(),
        )
        .await
        .expect("rebuild");
    assert_eq!(rebuilt.segments, 1);
    assert_eq!(rebuilt.rows, 2, "two distinct terms on one message");
    assert_eq!(
        rebuilt.unmerged_rows, 0,
        "a rebuild leaves only the base, so a fold has nothing to merge"
    );

    let appended = fx
        .projection
        .append(
            PARTITION,
            &[message(4, "turn-b", "gamma delta")],
            &coverage(5),
            &key_id(),
        )
        .await
        .expect("append");
    assert_eq!(appended.stats.segments, 2);
    assert_eq!(appended.stats.rows, 4);
    assert_eq!(
        appended.stats.unmerged_rows, 2,
        "only the delta sits outside the base"
    );

    // And a fold returns both quantities to the base — the property that makes
    // each compaction trigger an edge rather than a level.
    fx.projection
        .compact(PARTITION, &key_id())
        .await
        .expect("compact");
    let folded = fx
        .projection
        .segment_stats(PARTITION, &key_id())
        .await
        .expect("stats");
    assert_eq!(folded.segments, 1);
    assert_eq!(folded.rows, 4, "a fold merges rows, it never drops them");
    assert_eq!(
        folded.unmerged_rows, 0,
        "which is exactly why the trigger reads this and not the total"
    );
}

/// The decodability probe, footer-only: an older segment that will not open
/// must surface even though the newest one — the only footer `coverage` reads —
/// is perfectly healthy.
///
/// Decoding the rows to learn the same thing costs O(rows) on every committed
/// turn, which is the O(N squared) the segment layout exists to remove.
#[tokio::test]
async fn segment_stats_catches_an_older_segment_that_will_not_open() {
    let fx = Fixture::open("stats-probe");
    for (position, watermark) in [(1u64, 2u64), (4, 5)] {
        fx.projection
            .append(
                PARTITION,
                &[message(position, "turn-a", "alpha beta")],
                &coverage(watermark),
                &key_id(),
            )
            .await
            .expect("append");
    }

    let dir = fx
        .projection
        .root()
        .join(format!("conversation_id={}", encoded_partition()));
    let mut paths: Vec<_> = std::fs::read_dir(&dir)
        .expect("list")
        .filter_map(Result::ok)
        .map(|entry| entry.path())
        .collect();
    paths.sort();
    std::fs::write(&paths[0], b"not parquet").expect("break the older segment");

    assert!(
        matches!(
            fx.projection.coverage(PARTITION, &key_id()).await,
            Ok(CoverageState::Indexed(_))
        ),
        "the newest footer must still read, or this proves nothing"
    );
    assert!(
        fx.projection
            .segment_stats(PARTITION, &key_id())
            .await
            .is_err_and(|err| err.is_unreadable()),
        "a prefix nothing can open must not be advanced over"
    );
}

/// Nothing on disk is a state, not a failure — the caller asks `coverage`
/// which state it is.
#[tokio::test]
async fn segment_stats_reports_zeroes_for_a_conversation_with_no_segments() {
    let fx = Fixture::open("stats-empty");

    let stats = fx
        .projection
        .segment_stats(PARTITION, &key_id())
        .await
        .expect("stats");

    assert_eq!(stats.segments, 0);
    assert_eq!(stats.rows, 0);
    assert_eq!(stats.unmerged_rows, 0);
}

/// A rebuild discards everything: a rewrite or repair compacts journal
/// positions, so the old segments describe a prefix that no longer exists.
#[tokio::test]
async fn a_rebuild_discards_every_earlier_segment() {
    let fx = Fixture::open("rebuild");
    fx.projection
        .append(
            PARTITION,
            &[message(99, "gone", "removed")],
            &coverage(100),
            &key_id(),
        )
        .await
        .expect("append");

    let survivor = vec![message(1, "turn-a", "survivor")];
    fx.projection
        .rebuild(PARTITION, &survivor, &coverage(3), &key_id())
        .await
        .expect("rebuild");

    let read = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(read.messages, survivor);
    assert!(
        !read
            .messages
            .iter()
            .any(|m| m.term_hashes.contains(&key().hash_term("removed"))),
        "nothing from the compacted-away prefix may survive"
    );
}

/// Excision removes messages, so a rebuild that SHRINKS is the invalidation
/// case this design is built around.
#[tokio::test]
async fn a_shrinking_rebuild_drops_the_excised_message() {
    let fx = Fixture::open("shrink");
    fx.projection
        .append(
            PARTITION,
            &[
                message(1, "turn-a", "kept"),
                message(2, "turn-a", "excised secret"),
            ],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");

    let shrunk = vec![message(1, "turn-a", "kept")];
    fx.projection
        .rebuild(PARTITION, &shrunk, &coverage(3), &key_id())
        .await
        .expect("rebuild");

    let read = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(read.messages, shrunk);
    assert!(
        !read
            .messages
            .iter()
            .any(|m| m.term_hashes.contains(&key().hash_term("secret"))),
        "an excised term must not survive a rebuild"
    );
}

/// A conversation nothing has indexed reads as absent, never as empty
/// coverage: empty coverage would claim a conversation nothing looked at.
#[tokio::test]
async fn an_unindexed_conversation_reads_as_absent() {
    let fx = Fixture::open("absent");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::NeverIndexed
    );
    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read"),
        None
    );
}

/// Marking unavailable is a coverage statement, not a deletion: the newest
/// segment says unavailable while every row survives for a rebuild to reuse.
#[tokio::test]
async fn mark_unavailable_flips_coverage_and_keeps_the_rows() {
    let fx = Fixture::open("unavailable");
    let published = vec![message(1, "turn-a", "timeout")];
    fx.projection
        .append(PARTITION, &published, &coverage(11), &key_id())
        .await
        .expect("append");

    fx.projection
        .mark_unavailable(PARTITION, &key_id())
        .await
        .expect("mark");

    let read = indexed(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
    );
    assert!(!read.available, "the flag must be cleared");
    assert_eq!(read.indexed_through, 11, "the watermark survives");
    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read")
            .expect("present")
            .messages,
        published,
        "the rows survive"
    );
}

/// A conversation with no segments is already unsearchable, so marking it must
/// not fabricate one claiming a watermark nothing established.
#[tokio::test]
async fn mark_unavailable_on_an_unindexed_conversation_writes_nothing() {
    let fx = Fixture::open("mark-absent");

    fx.projection
        .mark_unavailable(PARTITION, &key_id())
        .await
        .expect("mark");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::NeverIndexed
    );
}

/// The migration source leaves no journal to rebuild from, so its segments go
/// rather than sitting unavailable forever — and it must leave NO trace, since
/// the conversation is alive under its new id and its coverage resolves from
/// the destination.
#[tokio::test]
async fn remove_deletes_every_segment() {
    let fx = Fixture::open("remove");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");

    fx.projection.remove(PARTITION).await.expect("remove");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::NeverIndexed
    );
}

/// The distinction the tombstone exists for: a destroyed conversation and one
/// nothing ever indexed must not read the same, because the first must never be
/// rebuilt and the second must be. Before this, destroy removed the directory
/// and both answered "absent".
#[tokio::test]
async fn destroyed_and_never_indexed_are_distinguishable() {
    let fx = Fixture::open("destroy-distinct");
    let never = "conv-web_99999999-9999-4999-8999-999999999999";
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");

    fx.projection
        .destroy(PARTITION, &key_id())
        .await
        .expect("destroy");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::Destroyed,
        "the destroyed state must be recorded, not merely absent"
    );
    assert_eq!(
        fx.projection
            .coverage(never, &key_id())
            .await
            .expect("read"),
        CoverageState::NeverIndexed
    );
    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read"),
        None,
        "the rows must be gone, not merely unavailable"
    );
}

/// Destroy is terminal. A publish that read its range before the destroy landed
/// must be refused rather than written: its segment would sort AFTER the
/// tombstone and resurrect a conversation the deployment was told to forget.
#[tokio::test]
async fn a_destroyed_conversation_refuses_every_republish() {
    let fx = Fixture::open("destroy-terminal");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");
    fx.projection
        .destroy(PARTITION, &key_id())
        .await
        .expect("destroy");

    let late = vec![message(4, "turn-b", "beta")];
    assert!(
        matches!(
            fx.projection
                .append(PARTITION, &late, &coverage(6), &key_id())
                .await,
            Err(StoreError::Destroyed)
        ),
        "an append after a destroy must be refused"
    );
    assert!(
        matches!(
            fx.projection
                .rebuild(PARTITION, &late, &coverage(6), &key_id())
                .await,
            Err(StoreError::Destroyed)
        ),
        "a rebuild after a destroy must be refused"
    );
    fx.projection
        .mark_unavailable(PARTITION, &key_id())
        .await
        .expect("marking is a no-op");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::Destroyed,
        "the conversation stays destroyed"
    );
    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read"),
        None
    );
}

/// A destroy of a conversation nothing indexed still records the state: destroy
/// is a statement about the conversation, not about what happened to be
/// indexed for it, and the worker must not go looking for a journal that is
/// gone.
#[tokio::test]
async fn destroying_an_unindexed_conversation_still_records_the_state() {
    let fx = Fixture::open("destroy-unindexed");

    fx.projection
        .destroy(PARTITION, &key_id())
        .await
        .expect("destroy");

    assert_eq!(
        fx.projection
            .coverage(PARTITION, &key_id())
            .await
            .expect("read"),
        CoverageState::Destroyed
    );
}

/// The tombstone holds no rows, so a term-key rotation cannot make it
/// unreadable. Reporting `Corrupt` for it would route a destroyed conversation
/// straight into the rebuild the tombstone exists to forbid.
#[tokio::test]
async fn a_tombstone_survives_a_key_rotation() {
    let fx = Fixture::open("destroy-rotated");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");
    fx.projection
        .destroy(PARTITION, &key_id())
        .await
        .expect("destroy");

    let rotated = TermKey::new([77u8; 32]).key_id();
    assert_eq!(
        fx.projection
            .coverage(PARTITION, &rotated)
            .await
            .expect("read"),
        CoverageState::Destroyed
    );
}

/// A message whose text yields no searchable term must still survive. The
/// tokenizer drops punctuation-only text and every non-ASCII term, so a
/// CJK-only message or a bare reaction lands here — and losing it would make a
/// conversation held in a non-Latin script round trip to nothing.
#[tokio::test]
async fn a_message_with_no_searchable_terms_survives_the_round_trip() {
    let fx = Fixture::open("no-terms");
    let published = vec![
        message(1, "turn-a", "\u{4f60}\u{597d}"),
        message(2, "turn-a", "timeout"),
    ];
    assert!(
        published[0].term_hashes.is_empty(),
        "fixture must actually produce a term-less message"
    );

    fx.projection
        .append(PARTITION, &published, &coverage(3), &key_id())
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read")
            .expect("present")
            .messages,
        published,
        "a term-less message must not vanish"
    );
}

/// A file written under a different term key decodes perfectly and answers
/// every query with zero hits. That is the silent not-found the design exists
/// to prevent, so it must be refused as unreadable instead.
#[tokio::test]
async fn a_segment_written_under_another_key_is_refused() {
    let fx = Fixture::open("rotated-key");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "timeout")],
            &coverage(2),
            &key_id(),
        )
        .await
        .expect("append");

    let rotated = TermKey::new([99u8; 32]).key_id();

    assert!(
        matches!(
            fx.projection.coverage(PARTITION, &rotated).await,
            Err(StoreError::Corrupt)
        ),
        "a rotated key must be detected, not silently answered around"
    );
}

/// Format v1 stored a content-derived boundary hash in the same-width footer
/// field that v2 assigns to the exact physical source. Even a well-formed v1
/// segment must therefore be refused and rebuilt, never reinterpreted.
#[tokio::test]
async fn a_format_v1_segment_is_refused_and_rebuilt() {
    let fx = Fixture::open("format-v1-source-semantics");
    let old = vec![message(1, "turn-a", "legacy")];
    fx.projection
        .write_format_for_test(PARTITION, &old, &coverage(2), &key_id(), "1")
        .await
        .expect("write a structurally readable v1 segment");

    assert!(
        matches!(
            fx.projection.coverage(PARTITION, &key_id()).await,
            Err(StoreError::Corrupt)
        ),
        "v1's same-width boundary hash must not be accepted as a physical source"
    );

    let replacement = vec![message(1, "turn-a", "replacement")];
    fx.projection
        .rebuild(PARTITION, &replacement, &coverage(2), &key_id())
        .await
        .expect("rebuild replaces the rejected format");
    assert_eq!(
        fx.projection
            .postings(PARTITION, &key_id())
            .await
            .expect("read replacement")
            .expect("replacement exists")
            .messages,
        replacement
    );
}

/// A corrupt footer must return `Corrupt` so the conversation is rebuilt.
/// Aborting the reading thread is not that — and an even BYTE length does not
/// make a string safe to slice.
#[test]
fn a_non_ascii_incarnation_is_refused_rather_than_panicking() {
    assert!(matches!(
        super::store::unhex_for_test("a\u{e9}b"),
        Err(StoreError::Corrupt)
    ));
    assert!(matches!(
        super::store::unhex_for_test("zz"),
        Err(StoreError::Corrupt)
    ));
    assert_eq!(
        super::store::unhex_for_test("00ff").expect("valid hex"),
        vec![0x00, 0xff]
    );
}

/// The premise of the whole layout, and the thing nothing tested: can
/// `DataFusion` actually read what this writes?
///
/// Note what a `ListingTable` needs and does NOT get for free —
/// `ListingOptions::default()` declares no partition columns, so
/// `conversation_id` is absent from the schema unless it is named. Pinning
/// that here means the search port inherits a working recipe rather than
/// rediscovering it.
#[tokio::test]
async fn datafusion_reads_the_projection_and_prunes_by_conversation() {
    use datafusion::datasource::listing::{
        ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl,
    };
    use datafusion::prelude::SessionContext;

    let fx = Fixture::open("datafusion-read");
    fx.projection
        .append(
            "conv-a",
            &[message(1, "turn-a", "timeout deploy")],
            &coverage(2),
            &key_id(),
        )
        .await
        .expect("append a");
    fx.projection
        .append(
            "conv-b",
            &[message(5, "turn-b", "invoices billing")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("append b");

    let ctx = SessionContext::new();
    let url =
        ListingTableUrl::parse(format!("file://{}/", fx.projection.root().display())).expect("url");
    let options = ListingOptions::new(Arc::new(
        datafusion::datasource::file_format::parquet::ParquetFormat::default(),
    ))
    .with_file_extension(".parquet")
    .with_table_partition_cols(vec![(
        "conversation_id".to_owned(),
        arrow::datatypes::DataType::Utf8,
    )]);
    let resolved = options
        .infer_schema(&ctx.state(), &url)
        .await
        .expect("schema");
    let config = ListingTableConfig::new(url)
        .with_listing_options(options)
        .with_schema(resolved);
    ctx.register_table(
        "search_terms",
        Arc::new(ListingTable::try_new(config).expect("table")),
    )
    .expect("register");

    let hash = key().hash_term("timeout");
    let rows = ctx
        .sql(&format!(
            "SELECT conversation_id, turn_id, position FROM search_terms \
             WHERE term_hash = {hash}"
        ))
        .await
        .expect("plan")
        .collect()
        .await
        .expect("execute");

    let total: usize = rows.iter().map(arrow::array::RecordBatch::num_rows).sum();
    assert_eq!(
        total, 1,
        "exactly the one conversation holding the term must match"
    );
}

/// A namespaced conversation is readable, and its two former twins stay apart.
///
/// Storage escapes a namespaced id to hold it as one directory, so the Hive
/// partition column carries the ENCODED name (#1748). Two things have to hold
/// at once, and only a real scan proves them together: the column value is
/// something DataFusion can actually read back and prune on, and `web:cafe`
/// and `web_cafe` land in separate directories rather than one.
///
/// Before the codec, both ids wrote to `conv-web_cafe` and this query could
/// not have told them apart at all.
#[tokio::test]
async fn datafusion_reads_a_namespaced_conversation_and_keeps_its_twin_apart() {
    use datafusion::datasource::listing::{
        ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl,
    };
    use datafusion::prelude::SessionContext;

    let fx = Fixture::open("datafusion-namespaced");
    fx.projection
        .append(
            "conv-web:cafe",
            &[message(1, "turn-colon", "timeout deploy")],
            &coverage(2),
            &key_id(),
        )
        .await
        .expect("append the namespaced id");
    fx.projection
        .append(
            "conv-web_cafe",
            &[message(5, "turn-underscore", "timeout deploy")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("append its former twin");

    // Two directories, because the two ids are two conversations.
    let dirs: Vec<String> = std::fs::read_dir(fx.projection.root())
        .expect("read the projection root")
        .flatten()
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .filter(|name| name.starts_with("conversation_id="))
        .collect();
    assert_eq!(
        dirs.len(),
        2,
        "each conversation holds its own directory: {dirs:?}"
    );

    let ctx = SessionContext::new();
    let url =
        ListingTableUrl::parse(format!("file://{}/", fx.projection.root().display())).expect("url");
    let options = ListingOptions::new(Arc::new(
        datafusion::datasource::file_format::parquet::ParquetFormat::default(),
    ))
    .with_file_extension(".parquet")
    .with_table_partition_cols(vec![(
        "conversation_id".to_owned(),
        arrow::datatypes::DataType::Utf8,
    )]);
    let resolved = options
        .infer_schema(&ctx.state(), &url)
        .await
        .expect("schema");
    let config = ListingTableConfig::new(url)
        .with_listing_options(options)
        .with_schema(resolved);
    ctx.register_table(
        "search_terms",
        Arc::new(ListingTable::try_new(config).expect("table")),
    )
    .expect("register");

    // The column carries the ENCODED name, so that is what a predicate names.
    // A reader wanting the conversation id decodes it.
    let hash = key().hash_term("timeout");
    let rows_for = |partition: &str| {
        let encoded = polyc_eventlog_host::encode_partition(partition).expect("the name encodes");
        let sql = format!(
            "SELECT turn_id FROM search_terms \
             WHERE term_hash = {hash} AND conversation_id = '{encoded}'"
        );
        let ctx = &ctx;
        async move {
            ctx.sql(&sql)
                .await
                .expect("plan")
                .collect()
                .await
                .expect("execute")
                .iter()
                .map(arrow::array::RecordBatch::num_rows)
                .sum::<usize>()
        }
    };

    // Both conversations hold the same term. Each predicate reaches exactly its
    // own row, which is the whole point: one shared partition could not have
    // answered these two queries differently.
    assert_eq!(
        rows_for("conv-web:cafe").await,
        1,
        "the namespaced conversation holds its own row"
    );
    assert_eq!(
        rows_for("conv-web_cafe").await,
        1,
        "and its former twin holds a separate one"
    );

    let encoded = polyc_eventlog_host::encode_partition("conv-web:cafe").expect("the name encodes");
    assert_eq!(
        polyc_eventlog_host::decode_partition(encoded.as_str()).expect("the name decodes"),
        "conv-web:cafe",
        "and the id is recoverable from the column a reader scanned"
    );
}

/// The catalog boundary IS the authorization boundary, so the paths handed to
/// a session must be exactly the conversations it is authorized for.
#[tokio::test]
async fn authorized_paths_names_only_the_conversations_asked_for() {
    let fx = Fixture::open("authorized");
    for partition in ["conv-a", "conv-b", "conv-c"] {
        fx.projection
            .append(
                partition,
                &[message(1, "turn-a", "alpha")],
                &coverage(2),
                &key_id(),
            )
            .await
            .expect("append");
    }

    let paths = fx
        .projection
        .authorized_paths(vec!["conv-a".to_owned(), "conv-c".to_owned()])
        .await
        .expect("paths");

    assert_eq!(paths.len(), 2, "one segment each: {paths:?}");
    assert!(
        paths
            .iter()
            .all(|p| p.to_string_lossy().contains("conv-a")
                || p.to_string_lossy().contains("conv-c")),
        "an unauthorized conversation must never appear: {paths:?}"
    );
    assert!(
        !paths.iter().any(|p| p.to_string_lossy().contains("conv-b")),
        "conv-b was not authorized"
    );
}

/// Naming a conversation that was never indexed is not an error, and must not
/// invent a path.
#[tokio::test]
async fn authorized_paths_skips_conversations_with_no_segments() {
    let fx = Fixture::open("authorized-absent");

    assert!(
        fx.projection
            .authorized_paths(vec!["never-indexed".to_owned()])
            .await
            .expect("paths")
            .is_empty()
    );
}

#[test]
fn overlap_counts_each_distinct_query_term_once() {
    let key = key();
    let message = message(1, "turn-a", "timeout deploy");

    assert_eq!(message.overlap(&key.hash_text("timeout")), 1);
    assert_eq!(message.overlap(&key.hash_text("timeout deploy")), 2);
    assert_eq!(message.overlap(&key.hash_text("absent")), 0);
}

/// Defaults are starting points, not measured values — but they must at least
/// be usable: a zero-partition budget would refuse every search.
#[test]
fn the_default_bounds_permit_a_search_to_run() {
    let config = SearchIndexConfig::default();

    assert!(config.max_partitions_read > 0);
    assert!(config.max_term_document_frequency > 0.0);
    assert!(config.max_term_document_frequency <= 1.0);
}

/// The defect a whole class of data loss came from: the segment sequence used
/// to be a process-local counter written into a durable filename. A restart
/// rewound it to zero while the directory kept its old names, and `rename`
/// silently REPLACES a colliding destination — so a rebuild deleted the file
/// it had just written and left the conversation indistinguishable from never
/// indexed.
///
/// Reopening the projection is the restart: the sequence must come off disk.
#[tokio::test]
async fn the_segment_sequence_survives_a_restart() {
    let fx = Fixture::open("restart-sequence");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");

    // A fresh projection over the same directory — a restarted process.
    let restarted = SearchProjection::open(fx.dir.clone()).expect("reopen");
    restarted
        .append(
            PARTITION,
            &[message(4, "turn-b", "beta")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("append after restart");

    let read = restarted
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(
        read.messages.len(),
        2,
        "the pre-restart segment must survive: {:?}",
        read.messages
    );
}

/// The same defect, in the shape that destroyed data: a rebuild at the SAME
/// watermark after a restart would collide with the existing segment, replace
/// it, and then delete it.
#[tokio::test]
async fn a_rebuild_after_a_restart_does_not_erase_the_conversation() {
    let fx = Fixture::open("restart-rebuild");
    fx.projection
        .append(
            PARTITION,
            &[
                message(1, "turn-a", "kept"),
                message(2, "turn-a", "excised secret"),
            ],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");

    let restarted = SearchProjection::open(fx.dir.clone()).expect("reopen");
    let shrunk = vec![message(1, "turn-a", "kept")];
    restarted
        .rebuild(PARTITION, &shrunk, &coverage(3), &key_id())
        .await
        .expect("rebuild");

    assert_eq!(
        restarted
            .postings(PARTITION, &key_id())
            .await
            .expect("read")
            .expect("the conversation must still exist")
            .messages,
        shrunk
    );
}

/// A later segment must SUPERSEDE an earlier one at the same position, not
/// union with it. Re-indexing a position with fewer terms — a redaction, or
/// text edited until every term is non-ASCII — must actually lose the terms it
/// no longer has.
#[tokio::test]
async fn a_later_segment_replaces_an_earlier_positions_terms() {
    let fx = Fixture::open("supersede");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha secret")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("first");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(4),
            &key_id(),
        )
        .await
        .expect("second");

    let read = fx
        .projection
        .postings(PARTITION, &key_id())
        .await
        .expect("read")
        .expect("present");
    assert_eq!(read.messages.len(), 1);
    assert!(
        !read.messages[0]
            .term_hashes
            .contains(&key().hash_term("secret")),
        "a term removed by a later segment must not survive as a union"
    );
    assert!(
        read.messages[0]
            .term_hashes
            .contains(&key().hash_term("alpha"))
    );
}

/// An append must never restore availability. The design is explicit: an
/// append while unavailable stays unavailable and enqueues a rebuild. Without
/// this a routine turn landing after an excision marker made the conversation
/// searchable again, excised terms included.
#[tokio::test]
async fn an_append_after_mark_unavailable_does_not_restore_availability() {
    let fx = Fixture::open("stay-unavailable");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");
    fx.projection
        .mark_unavailable(PARTITION, &key_id())
        .await
        .expect("mark");

    // A later turn commits at a HIGHER watermark, so its segment sorts last.
    fx.projection
        .append(
            PARTITION,
            &[message(4, "turn-b", "beta")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("append after mark");

    assert!(
        !indexed(
            fx.projection
                .coverage(PARTITION, &key_id())
                .await
                .expect("read")
        )
        .available,
        "only a rebuild may clear unavailability"
    );
}

/// A rebuild is what clears unavailability — otherwise the conversation could
/// never recover.
#[tokio::test]
async fn a_rebuild_clears_unavailability() {
    let fx = Fixture::open("rebuild-clears");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("append");
    fx.projection
        .mark_unavailable(PARTITION, &key_id())
        .await
        .expect("mark");

    fx.projection
        .rebuild(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("rebuild");

    assert!(
        indexed(
            fx.projection
                .coverage(PARTITION, &key_id())
                .await
                .expect("read")
        )
        .available
    );
}

/// A rebuild must clear segments written under a rotated key — that is the
/// state it exists to repair, and swallowing the listing error made it a
/// permanent no-op against exactly that case.
#[tokio::test]
async fn a_rebuild_repairs_a_conversation_written_under_a_rotated_key() {
    let fx = Fixture::open("rotate-repair");
    let old_key = TermKey::new([42u8; 32]);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &old_key.key_id(),
        )
        .await
        .expect("append under the old key");

    assert!(
        matches!(
            fx.projection.coverage(PARTITION, &key_id()).await,
            Err(StoreError::Corrupt)
        ),
        "the rotated key must be detected first"
    );

    fx.projection
        .rebuild(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &coverage(3),
            &key_id(),
        )
        .await
        .expect("rebuild must be able to repair a rotated-key conversation");

    assert!(
        matches!(
            fx.projection.coverage(PARTITION, &key_id()).await,
            Ok(CoverageState::Indexed(_))
        ),
        "the conversation must be readable again"
    );
}

/// A readable journal with one exact durable physical lineage.
struct Journal {
    incarnation: PartitionIncarnation,
}

impl Journal {
    fn of(_payloads: &[&str]) -> Self {
        Self {
            incarnation: PartitionIncarnation::from_bytes([9; 32]),
        }
    }

    fn with_incarnation(mut self, byte: u8) -> Self {
        self.incarnation = PartitionIncarnation::from_bytes([byte; 32]);
        self
    }
}

impl super::store::JournalState for Journal {
    async fn source_incarnation(&self, _partition: &str) -> Option<PartitionIncarnation> {
        Some(self.incarnation)
    }

    async fn excision_since(&self, _partition: &str, _scanned_through: u64) -> ExcisionScan {
        ExcisionScan::Clear
    }
}

/// A journal that still holds an excision marker the stored footer never
/// accounted for.
struct ExcisedJournal(Journal);

impl super::store::JournalState for ExcisedJournal {
    async fn source_incarnation(&self, partition: &str) -> Option<PartitionIncarnation> {
        self.0.source_incarnation(partition).await
    }

    async fn excision_since(&self, _partition: &str, _scanned_through: u64) -> ExcisionScan {
        ExcisionScan::Pending
    }
}

/// A journal that cannot answer the excision question at all.
struct UnknownExcisionJournal(Journal);

impl super::store::JournalState for UnknownExcisionJournal {
    async fn source_incarnation(&self, partition: &str) -> Option<PartitionIncarnation> {
        self.0.source_incarnation(partition).await
    }

    async fn excision_since(&self, _partition: &str, _scanned_through: u64) -> ExcisionScan {
        ExcisionScan::Unknown
    }
}

/// A source that rotates while the read-side excision check is in flight.
struct RotatingVerificationJournal {
    reads: std::sync::atomic::AtomicUsize,
    before: PartitionIncarnation,
    after: Option<PartitionIncarnation>,
}

impl super::store::JournalState for RotatingVerificationJournal {
    async fn source_incarnation(&self, _partition: &str) -> Option<PartitionIncarnation> {
        if self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
            Some(self.before)
        } else {
            self.after
        }
    }

    async fn excision_since(&self, _partition: &str, _scanned_through: u64) -> ExcisionScan {
        ExcisionScan::Clear
    }
}

/// A journal that cannot answer — the partition is gone, or the replay failed.
/// It also counts, so a test can assert it was never asked.
#[derive(Default)]
struct SilentJournal(std::sync::atomic::AtomicUsize);

impl SilentJournal {
    fn asked(&self) -> usize {
        self.0.load(std::sync::atomic::Ordering::Relaxed)
    }
}

impl super::store::JournalState for SilentJournal {
    async fn source_incarnation(&self, _partition: &str) -> Option<PartitionIncarnation> {
        self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        None
    }

    async fn excision_since(&self, _partition: &str, _scanned_through: u64) -> ExcisionScan {
        self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        ExcisionScan::Unknown
    }
}

fn covering(indexed_through: u64, source_incarnation: PartitionIncarnation) -> Coverage {
    Coverage {
        indexed_through,
        source_incarnation,
        available: true,
        excision_scanned_through: indexed_through,
    }
}

/// The gap the incarnation cannot close, and the reason a dropped excision
/// rebuild is recoverable at all.
///
/// A taint-excision marker is a pure APPEND. It preserves the exact physical
/// source. The source check therefore passes over a conversation whose segments
/// still hold the removed text. The only record that a rebuild was owed lived
/// in an in-memory dirty set that a restart discards — so this read had to
/// learn to ask the journal instead.
#[tokio::test]
async fn an_excision_the_index_never_applied_reads_as_stale() {
    let fx = Fixture::open("verify-excision-pending");
    let journal = Journal::of(&["one", "two", "three"]);
    let published = covering(3, journal.incarnation);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &published,
            &key_id(),
        )
        .await
        .expect("append");

    // The identity side is unchanged and still agrees — that is the point.
    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &journal)
            .await
            .expect("verify"),
        CoverageState::Indexed(published)
    );
    assert_eq!(
        fx.projection
            .verified_coverage(
                PARTITION,
                &key_id(),
                &ExcisedJournal(Journal::of(&["one", "two", "three"]))
            )
            .await
            .expect("verify"),
        CoverageState::Stale,
        "a marker past the stored frontier means the segments may still hold removed text"
    );
}

/// "Cannot prove there is no excision" and "there is an excision" call for the
/// same refusal. A scan that ran out of budget, or a journal that would not
/// answer, must not be read as a clean bill of health.
#[tokio::test]
async fn an_unprovable_excision_scan_reads_as_stale() {
    let fx = Fixture::open("verify-excision-unknown");
    let journal = Journal::of(&["one", "two", "three"]);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &covering(3, journal.incarnation),
            &key_id(),
        )
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .verified_coverage(
                PARTITION,
                &key_id(),
                &UnknownExcisionJournal(Journal::of(&["one", "two", "three"]))
            )
            .await
            .expect("verify"),
        CoverageState::Stale
    );
}

/// The excision frontier is a property of the whole directory, so a later
/// append may not retract a scan an earlier one already performed. If it
/// could, an ordinary short window would reopen a question a rebuild had
/// already settled — and every read would then refuse a conversation that is
/// in fact clean.
#[tokio::test]
async fn the_excision_frontier_never_rewinds() {
    let fx = Fixture::open("frontier-monotonic");
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &Coverage {
                indexed_through: 3,
                source_incarnation: PartitionIncarnation::from_bytes([9; 32]),
                available: true,
                excision_scanned_through: 99,
            },
            &key_id(),
        )
        .await
        .expect("append");
    fx.projection
        .append(
            PARTITION,
            &[message(4, "turn-b", "beta")],
            &coverage(6),
            &key_id(),
        )
        .await
        .expect("append");

    assert_eq!(
        indexed(
            fx.projection
                .coverage(PARTITION, &key_id())
                .await
                .expect("read")
        )
        .excision_scanned_through,
        99,
        "the newest segment must carry the highest frontier the directory has reached"
    );
}

/// The ordinary case: the journal still holds what was indexed, so the stored
/// coverage stands.
#[tokio::test]
async fn a_matching_incarnation_verifies() {
    let fx = Fixture::open("verify-match");
    let journal = Journal::of(&["one", "two", "three"]);
    let published = covering(3, journal.incarnation);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &published,
            &key_id(),
        )
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &journal)
            .await
            .expect("verify"),
        CoverageState::Indexed(published)
    );
}

#[tokio::test]
async fn a_source_rotation_during_read_verification_refuses_stale_rows() {
    for (name, after) in [
        (
            "verify-race-replacement",
            Some(PartitionIncarnation::from_bytes([8; 32])),
        ),
        ("verify-race-removal", None),
    ] {
        let fx = Fixture::open(name);
        let before = PartitionIncarnation::from_bytes([9; 32]);
        fx.projection
            .append(
                PARTITION,
                &[message(1, "turn-a", "secret")],
                &covering(3, before),
                &key_id(),
            )
            .await
            .expect("append stale source rows");
        let journal = RotatingVerificationJournal {
            reads: std::sync::atomic::AtomicUsize::new(0),
            before,
            after,
        };

        assert_eq!(
            fx.projection
                .verified_coverage(PARTITION, &key_id(), &journal)
                .await
                .expect("verify"),
            CoverageState::Stale,
            "a replacement or removal between source validation and the scan must refuse"
        );
    }
}

/// The hole this closes. A rewrite commits durably and the process dies before
/// its notification: the segment still decodes, still reports a watermark, and
/// still says available, while describing a journal that no longer exists.
/// Nothing computed the incarnation and nothing compared it, so nothing caught
/// this.
#[tokio::test]
async fn a_rewritten_journal_makes_the_conversation_uncovered() {
    let fx = Fixture::open("verify-rewrite");
    let indexed = Journal::of(&["one", "two", "three"]);
    let published = covering(3, indexed.incarnation);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &published,
            &key_id(),
        )
        .await
        .expect("append");

    // A repair replayed, dropped an event, and re-appended the survivors, so
    // the event AT the watermark is a different one.
    let rewritten = Journal::of(&["one", "three", "four"]).with_incarnation(8);

    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &rewritten)
            .await
            .expect("verify"),
        CoverageState::Stale,
        "an index describing a journal that no longer exists must not be searched"
    );
}

/// A journal that cannot answer at all — destroyed partition, failed replay —
/// is a mismatch, not a pass. Failing closed is the whole point of verifying.
#[tokio::test]
async fn a_journal_that_cannot_answer_makes_the_conversation_uncovered() {
    let fx = Fixture::open("verify-silent");
    let journal = Journal::of(&["one", "two", "three"]);
    fx.projection
        .append(
            PARTITION,
            &[message(1, "turn-a", "alpha")],
            &covering(3, journal.incarnation),
            &key_id(),
        )
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &SilentJournal::default())
            .await
            .expect("verify"),
        CoverageState::Stale
    );
}

/// Watermark zero still belongs to one exact physical source.
#[tokio::test]
async fn a_zero_watermark_verifies_only_against_its_exact_source() {
    let fx = Fixture::open("verify-zero");
    let source = Journal::of(&[]);
    let published = covering(0, source.incarnation);
    fx.projection
        .append(PARTITION, &[], &published, &key_id())
        .await
        .expect("append");

    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &source)
            .await
            .expect("verify"),
        CoverageState::Indexed(published),
        "an empty index still names the live physical lineage"
    );
    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &Journal::of(&[]).with_incarnation(7),)
            .await
            .expect("verify"),
        CoverageState::Stale
    );
}

/// Neither a never-indexed nor a destroyed conversation claims a prefix, so
/// neither has one to check — and asking the journal for a destroyed partition
/// is a replay that can only fail. Verification must pass those through
/// untouched, which is also what keeps the per-search cost at one journal read
/// per conversation that actually has coverage.
#[tokio::test]
async fn verification_never_asks_the_journal_about_a_conversation_with_no_prefix() {
    let fx = Fixture::open("verify-passthrough");
    let journal = SilentJournal::default();

    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &journal)
            .await
            .expect("verify"),
        CoverageState::NeverIndexed
    );

    fx.projection
        .destroy(PARTITION, &key_id())
        .await
        .expect("destroy");
    assert_eq!(
        fx.projection
            .verified_coverage(PARTITION, &key_id(), &journal)
            .await
            .expect("verify"),
        CoverageState::Destroyed
    );
    assert_eq!(journal.asked(), 0, "neither state has a prefix to verify");
}

/// The Container-facing wiring: one [`SearchIndex`] hands out an observer and
/// owns a worker over the SAME dirty set, so registering the one and
/// supervising the other cannot be done to different sets.
///
/// This is the end-to-end proof of the invariant the whole change exists for —
/// an observer registered without a running worker fills a set nothing drains,
/// and the read path then refuses forever.
mod wiring {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use std::sync::Arc;
    use std::time::Duration;

    use polyc_crypto::approval::ApprovalSigner;
    use polyc_eventlog::Event;
    use polyc_eventlog_host::EventLogHost;
    use polyc_proto::kinds;
    use polyc_state::{
        journal::{INCARNATION_MARKER_KIND, incarnation_marker_payload},
        revision::PartitionIncarnation,
    };
    use tokio_util::sync::CancellationToken;

    use super::super::store::{CoverageState, SearchProjection};
    use super::super::terms::TermKey;
    use super::super::{SearchIndex, TermKeyOrigin};

    const PARTITION: &str = "conv-web_99999999-8888-7777-6666-555555555555";
    const TURN: &str = "01950000-0000-7000-8000-0000000000ff";
    const TERM_KEY: [u8; 32] = [23u8; 32];

    /// One fully committed turn carrying a single searchable text block.
    fn committed_turn(text: &str) -> Vec<Event> {
        use buffa::Message as _;
        use polyc_proto::proto::polychrome::agent::v1::{Content, Message, TextContent, content};

        let message = Message {
            role: "user".to_owned(),
            content: buffa::MessageField::some(Content {
                r#type: Some(content::Type::Text(Box::new(TextContent {
                    text: text.to_owned(),
                    ..Default::default()
                }))),
                ..Default::default()
            }),
            ..Default::default()
        };
        vec![
            Event::new(format!("{}:{TURN}", kinds::TURN_START), Vec::new()),
            Event::new(
                format!("{}:{TURN}", kinds::USER_MSG),
                message.encode_to_vec(),
            ),
            Event::new(format!("{}:{TURN}", kinds::TURN_COMPLETE), Vec::new()),
        ]
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_driven_marks_handle_and_a_supervised_worker_index_a_committed_turn() {
        let dir = std::env::temp_dir().join(format!(
            "polychrome-search-wiring-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let shutdown = CancellationToken::new();
        let eventlog = Arc::new(
            EventLogHost::spawn(
                dir.join("journal"),
                shutdown.clone(),
                ApprovalSigner::from_seed(9).relabel_for_test(),
            )
            .expect("spawn eventlog host"),
        );

        let root = dir.join("search-index");
        let index = SearchIndex::open(
            root.clone(),
            TERM_KEY,
            TermKeyOrigin::Stored,
            crate::journal::over_host(Arc::clone(&eventlog)),
        )
        .expect("open index");
        // Exactly the Container's ordering: take the marks handle, then
        // supervise.
        let marks = index.marks();
        let worker = tokio::spawn(index.run(shutdown.clone()));

        eventlog
            .append_batch(
                PARTITION.to_owned(),
                vec![Event::new(
                    INCARNATION_MARKER_KIND,
                    incarnation_marker_payload(PartitionIncarnation::from_bytes([9; 32])),
                )],
            )
            .await
            .expect("seed exact fixture source");
        let events = committed_turn("timeout decision");
        let positions = eventlog
            .append_batch(PARTITION.to_owned(), events.clone())
            .await
            .expect("append");
        let boundary = positions.last().copied().expect("positions") + 1;
        marks.note_commit(
            PARTITION,
            &[crate::feed::test_commit(PARTITION, &events, &positions)],
        );

        // A second, read-only handle over the same directory — the worker owns
        // the writing one.
        let reader = SearchProjection::open(root).expect("open reader");
        let key_id = TermKey::new(TERM_KEY).key_id();
        let mut indexed = None;
        for _ in 0..60 {
            if let CoverageState::Indexed(coverage) = reader
                .coverage(PARTITION, &key_id)
                .await
                .expect("read coverage")
            {
                indexed = Some(coverage);
                break;
            }
            tokio::time::sleep(Duration::from_millis(250)).await;
        }
        let coverage = indexed.expect("the supervised worker never published a segment");
        assert!(
            coverage.available,
            "a committed turn must leave the conversation searchable"
        );
        assert_eq!(
            coverage.indexed_through, boundary,
            "coverage must reach the committed turn boundary the feed marked"
        );

        shutdown.cancel();
        worker.await.expect("the worker must return on shutdown");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A minted term key orphans every segment already on disk: they decode,
    /// they report a watermark, and every query against them returns zero hits
    /// for text they demonstrably hold. Detection alone never repaired that —
    /// nothing sweeps on a key change, so a conversation that never commits
    /// another turn keeps its orphaned segments and its participants' search
    /// refuses forever. Opening degraded is what schedules the sweep.
    #[test]
    fn a_minted_term_key_opens_the_index_degraded() {
        let dir = std::env::temp_dir().join(format!(
            "polychrome-search-minted-key-{}-{}",
            std::process::id(),
            uuid::Uuid::now_v7().as_simple()
        ));
        let shutdown = CancellationToken::new();
        let eventlog = Arc::new(
            EventLogHost::spawn(
                dir.join("journal"),
                shutdown.clone(),
                ApprovalSigner::from_seed(11).relabel_for_test(),
            )
            .expect("spawn eventlog host"),
        );

        let stored = SearchIndex::open(
            dir.join("stored"),
            TERM_KEY,
            TermKeyOrigin::Stored,
            crate::journal::over_host(Arc::clone(&eventlog)),
        )
        .expect("open");
        assert!(
            !stored.dirty.degraded(),
            "a key read back from custody describes the segments already on disk, so degrading \
             on it would rebuild the whole deployment on every restart"
        );

        let minted = SearchIndex::open(
            dir.join("minted"),
            TERM_KEY,
            TermKeyOrigin::Minted,
            crate::journal::over_host(Arc::clone(&eventlog)),
        )
        .expect("open");
        assert!(
            minted.dirty.degraded(),
            "a minted key must open degraded, or the orphaned segments refuse forever with \
             nothing scheduled to replace them"
        );

        shutdown.cancel();
        let _ = std::fs::remove_dir_all(&dir);
    }
}

/// The write layout the read side is being built against, pinned against the
/// file itself rather than against the builder call that requested it.
///
/// Every pruning claim this module makes depends on three physical facts: a
/// Bloom filter on `term_hash`, rows actually sorted by it, and the declared
/// `SortingColumn` naming that column's LEAF index. A `WriterProperties`
/// builder call proves none of them -- a filter can be silently dropped, and
/// `column_idx` is an ordinal into the row group's leaf columns, so a schema
/// gaining a field ahead of `term_hash` would leave the declaration pointing
/// at the wrong column while still compiling.
#[tokio::test]
async fn the_segment_carries_the_bloom_filter_and_sort_the_read_side_needs() {
    let fx = Fixture::open("write-layout");
    fx.projection
        .append(
            PARTITION,
            &[
                message(3, "turn-a", "where did we decide the timeout"),
                message(9, "turn-b", "the deploy failed again today"),
            ],
            &coverage(42),
            &key_id(),
        )
        .await
        .expect("append");

    let segment = std::fs::read_dir(
        fx.dir
            .join(format!("conversation_id={}", encoded_partition())),
    )
    .expect("the partition directory")
    .filter_map(Result::ok)
    .map(|entry| entry.path())
    .find(|path| path.extension().is_some_and(|ext| ext == "parquet"))
    .expect("a published segment");

    let reader = parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder::try_new(
        std::fs::File::open(&segment).expect("open the segment"),
    )
    .expect("parse the footer");
    let metadata = reader.metadata();

    let term_hash_leaf = metadata
        .file_metadata()
        .schema_descr()
        .columns()
        .iter()
        .position(|column| column.name() == "term_hash")
        .expect("a term_hash leaf column");

    for index in 0..metadata.num_row_groups() {
        let group = metadata.row_group(index);
        assert_eq!(
            group.sorting_columns().map(Vec::as_slice),
            Some(
                [parquet::file::metadata::SortingColumn {
                    column_idx: i32::try_from(term_hash_leaf).expect("a small leaf index"),
                    descending: false,
                    nulls_first: false,
                }]
                .as_slice()
            ),
            "the declared sort must name term_hash's leaf ordinal",
        );
        for column in 0..group.num_columns() {
            let chunk = group.column(column);
            let is_term_hash = chunk.column_path().string() == "term_hash";
            assert_eq!(
                chunk.bloom_filter_offset().is_some(),
                is_term_hash,
                "a Bloom filter belongs on term_hash and nowhere else, found on {}",
                chunk.column_path(),
            );
        }
    }

    // The declaration above is only true if the rows honour it.
    let hashes: Vec<u32> = reader
        .build()
        .expect("build the reader")
        .map(|batch| batch.expect("decode a batch"))
        .flat_map(|batch| {
            batch
                .column(term_hash_leaf)
                .as_any()
                .downcast_ref::<arrow::array::UInt32Array>()
                .expect("term_hash is UInt32")
                .values()
                .to_vec()
        })
        .collect();
    assert!(
        hashes.windows(2).all(|pair| pair[0] <= pair[1]),
        "rows must be written in term_hash order: {hashes:?}",
    );
}