zeppelin-embed 0.8.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
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
//! The lexical index: per-segment postings and store-wide statistics.
//!
//! # Global statistics are the whole point
//!
//! [`LexicalIndex`](crate::fts::index::LexicalIndex) owns every segment, and
//! every statistic the scorer needs
//! — `N`, `avgdl`, and per-term `df` — is derived across all of them. A
//! segment cannot answer a scoring question by itself and is not asked to.
//!
//! Segment-local IDF is a documented real-world failure (Milvus Lite) and
//! the prime suspect for the prior engine's ~30% nDCG@10 gap
//! (`research/02a:256`). The structure here makes it unconstructible: the
//! only public entry points that produce statistics hang off the store-wide
//! index, and `prop_engine_bm25_equals_model` randomizes seal boundaries so
//! any per-segment statistic diverges from the brute-force model on the
//! first multi-segment case.
//!
//! # Field handling (BM25F-lite)
//!
//! A document is a map from field id to text. Postings are keyed by
//! `(term, field)`, so the flat scorer sums a term's contribution across
//! fields with weight one — reproducing the "flat" BEIR column — and the
//! multifield scorer applies per-field weights to term frequencies and
//! lengths. Both run the same code path with a different weight table.
//!
//! # No truncation, ever
//!
//! Task 13's guardrail is absolute: documents are never truncated before
//! indexing, and no candidate cap exists outside task 14's bounds. An
//! oversized field is a typed rejection at the tokenizer boundary, not a
//! silent cut.

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use super::bm25::{Bm25Error, CorpusStats};
use super::postings::{Posting, PostingList, PostingsError};
use super::sealed::SealedSegment;
use super::tokenizer::{Analyzer, Token};
use crate::lifecycle::StoreError;
use crate::lifecycle::hash_table::allocation_bytes;
use crate::lifecycle::stats::{AccountedCounter, Accounting, AllocationComponent};
use crate::meta::DocBitmap;

/// A field identifier within a document schema.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct FieldId(pub u16);

/// The default field, used when a caller indexes plain text.
pub const DEFAULT_FIELD: FieldId = FieldId(0);

/// The key a posting list hangs off: term first, so prefix scans work.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TermKey {
    /// The analyzed term.
    pub term: Vec<u8>,
    /// The field the term occurred in.
    pub field: FieldId,
}

/// An index construction failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IndexError {
    /// The weighted cursor scheduler referenced an absent cursor slot.
    CursorSlotMissing {
        /// Invalid scheduler slot.
        slot: usize,
    },
    /// Exact live-frequency memoization refused inconsistent state or a
    /// poisoned lock. No cache failure is interpreted as a zero frequency.
    LiveFrequencyCache {
        /// Failed cache invariant or synchronization boundary.
        reason: &'static str,
    },
    /// A posting list rejected an append.
    Postings(PostingsError),
    /// The corpus had no documents or no tokens.
    Stats(Bm25Error),
    /// Documents were added out of row order.
    RowsNotAscending {
        /// The offending row.
        row: u32,
    },
    /// A live-row counter named a row outside its lexical segment.
    LiveRowOutOfRange {
        /// Lexical segment ordinal.
        segment: usize,
        /// Invalid row identifier.
        row: u32,
        /// Dense row count of the segment.
        row_count: u32,
    },
    /// A sealed segment's dense length counter omitted a valid live row.
    LiveLengthMissing {
        /// Lexical segment ordinal.
        segment: usize,
        /// Live row without a length counter.
        row: u32,
    },
    /// A replacement named a row the segment does not hold.
    ReplacedRowOutOfRange {
        /// Invalid row identifier.
        row: u32,
        /// Dense row count of the segment.
        row_count: u32,
    },
    /// A replaced row's previous document names a term the row has no
    /// posting for, so the index was not built from that document.
    ReplacedPostingMissing {
        /// The replaced row.
        row: u32,
    },
}

impl std::fmt::Display for IndexError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CursorSlotMissing { slot } => {
                write!(formatter, "weighted cursor slot {slot} is absent")
            }
            Self::LiveFrequencyCache { reason } => {
                write!(formatter, "live document frequency cache failed: {reason}")
            }
            Self::Postings(error) => write!(formatter, "postings rejected: {error}"),
            Self::Stats(error) => write!(formatter, "corpus statistics unavailable: {error}"),
            Self::RowsNotAscending { row } => {
                write!(formatter, "documents must arrive in row order; got {row}")
            }
            Self::LiveRowOutOfRange {
                segment,
                row,
                row_count,
            } => write!(
                formatter,
                "live lexical row {row} is outside segment {segment} row count {row_count}"
            ),
            Self::LiveLengthMissing { segment, row } => write!(
                formatter,
                "live lexical row {row} has no length counter in segment {segment}"
            ),
            Self::ReplacedRowOutOfRange { row, row_count } => write!(
                formatter,
                "replaced lexical row {row} is outside the segment's {row_count} rows"
            ),
            Self::ReplacedPostingMissing { row } => write!(
                formatter,
                "replaced lexical row {row} has no posting for a term of its previous document"
            ),
        }
    }
}

impl std::error::Error for IndexError {}

impl From<PostingsError> for IndexError {
    fn from(error: PostingsError) -> Self {
        Self::Postings(error)
    }
}

impl From<Bm25Error> for IndexError {
    fn from(error: Bm25Error) -> Self {
        Self::Stats(error)
    }
}

/// One document's text, by field.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Document {
    fields: BTreeMap<FieldId, String>,
}

impl Document {
    /// Creates an empty document.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a single-field document in [`DEFAULT_FIELD`].
    #[must_use]
    pub fn with_text(text: &str) -> Self {
        let mut document = Self::new();
        document.set(DEFAULT_FIELD, text);
        document
    }

    /// Sets one field's text, replacing any previous value.
    pub fn set(&mut self, field: FieldId, text: &str) -> &mut Self {
        self.fields.insert(field, text.to_owned());
        self
    }

    /// Returns the fields, ascending by id.
    pub fn fields(&self) -> impl Iterator<Item = (FieldId, &str)> {
        self.fields
            .iter()
            .map(|(field, text)| (*field, text.as_str()))
    }
}

/// One field's analyzed token counts, dense by row.
///
/// `lengths` is exactly `row_count` long at all times: a field absent from
/// a document still occupies its row, carrying zero. That invariant is what
/// lets the scorer borrow the array wholesale instead of rebuilding it.
#[derive(Clone, Debug)]
struct FieldLengths {
    field: FieldId,
    lengths: Vec<u32>,
}

/// Hashes term keys with xxh3, the one permitted hash family.
#[derive(Clone, Debug, Default)]
struct Xxh3State;

impl std::hash::BuildHasher for Xxh3State {
    type Hasher = xxhash_rust::xxh3::Xxh3;

    fn build_hasher(&self) -> Self::Hasher {
        xxhash_rust::xxh3::Xxh3::new()
    }
}

#[cfg(test)]
thread_local! {
    static TOKENS_INDEXED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// Tokens this thread has folded into or removed from any segment index.
///
/// A deterministic work counter: a gate compares deltas around one write to
/// prove the write's lexical cost does not depend on the rows beside it.
#[cfg(test)]
pub(crate) fn tokens_indexed() -> u64 {
    TOKENS_INDEXED.with(std::cell::Cell::get)
}

#[cfg_attr(not(test), allow(unused_variables))]
fn count_tokens_indexed(tokens: usize) {
    #[cfg(test)]
    TOKENS_INDEXED.with(|count| {
        count.set(
            count
                .get()
                .saturating_add(u64::try_from(tokens).unwrap_or(u64::MAX)),
        );
    });
}

/// One segment's postings and lengths, addressed by dense row id.
///
/// # Why lengths are dense arrays and not a map
///
/// Rows are dense and ascending by the task 07 invariant, so a
/// `BTreeMap<(row, field), u32>` spends a pointer-chasing descent — about
/// seventeen levels at 171,000 documents — on what an array answers with one
/// index. The scorer performs that lookup once per scored posting, so the
/// descent was among the largest per-posting costs in the engine.
///
/// # Why the term table is a hash map and not a tree
///
/// Accumulation looks a term up once per (document, term, field): tens of
/// millions of probes on a real corpus, against a table with millions of
/// entries. A B-tree descent is ~20 pointer-chasing key compares per
/// probe; an xxh3 probe is one hash and usually one compare. The sorted
/// view the seal needs is materialized ONCE, in [`Self::postings`],
/// instead of being maintained on every insert.
#[derive(Debug, Default)]
pub struct SegmentIndex {
    /// Term key to slot in `lists`.
    terms: HashMap<TermKey, usize, Xxh3State>,
    // Removals can lower HashMap::capacity without freeing any buckets.
    term_capacity: usize,
    /// Posting lists, in first-seen order; `terms` holds the slots.
    lists: Vec<PostingList>,
    /// Per-field analyzed token counts, ascending by field id.
    lengths: Vec<FieldLengths>,
    row_count: u32,
    /// Slots in `lists` whose term a replacement dropped; new terms reuse
    /// them before growing `lists`. Each holds an empty list no key names.
    free_slots: Vec<usize>,
    /// Heap owned by term keys and postings; updated only for touched terms.
    term_bytes: usize,
    posting_bytes: usize,
}

// Vec cloning can shrink capacities, so a copy measures its own allocations.
impl Clone for SegmentIndex {
    fn clone(&self) -> Self {
        self.clone_with_terms(self.terms.clone())
    }
}

impl SegmentIndex {
    fn clone_with_terms(&self, terms: HashMap<TermKey, usize, Xxh3State>) -> Self {
        let mut copy = Self {
            terms,
            term_capacity: self.term_capacity,
            lists: self.lists.clone(),
            lengths: self.lengths.clone(),
            row_count: self.row_count,
            free_slots: self.free_slots.clone(),
            term_bytes: 0,
            posting_bytes: 0,
        };
        copy.term_bytes = copy
            .terms
            .keys()
            .map(|key| key.term.capacity())
            .fold(0, usize::saturating_add);
        copy.posting_bytes = copy
            .lists
            .iter()
            .map(PostingList::resident_bytes)
            .fold(0, usize::saturating_add);
        copy
    }
}

/// Where [`SegmentIndex::accumulate`] places a row's postings.
#[derive(Clone, Copy)]
enum Placement {
    /// The row is the next dense row: append, refusing any lower row.
    Append,
    /// The row already exists: insert at its document-id position.
    Insert,
}

impl SegmentIndex {
    pub(crate) fn clone_accounted(
        &self,
        accounting: &Arc<Accounting>,
    ) -> Result<(Self, AccountedCounter), StoreError> {
        let mut counter = AccountedCounter::new(accounting, AllocationComponent::Active)?;
        counter.set(self.resident_bytes())?;
        let mut terms = HashMap::with_hasher(Xxh3State);
        terms
            .try_reserve(self.term_capacity)
            .map_err(|_| StoreError::AllocationFailed {
                needed: allocation_bytes::<(TermKey, usize)>(self.term_capacity)
                    .unwrap_or(usize::MAX) as u64,
                component: "lexical terms map",
            })?;
        terms.extend(self.terms.iter().map(|(key, slot)| (key.clone(), *slot)));
        let copy = self.clone_with_terms(terms);
        counter.set(copy.resident_bytes())?;
        Ok((copy, counter))
    }

    pub(crate) fn reserve_terms(
        &mut self,
        capacity: usize,
        counter: &mut AccountedCounter,
    ) -> Result<(), StoreError> {
        // Below half-full, hashbrown only clears deleted control tags in place.
        let allocation_capacity = if capacity <= self.term_capacity / 2 {
            0
        } else {
            capacity.max(
                self.term_capacity
                    .checked_add(1)
                    .ok_or(StoreError::ActiveRowOverflow)?,
            )
        };
        let needed = allocation_bytes::<(TermKey, usize)>(allocation_capacity)
            .ok_or(StoreError::ActiveRowOverflow)?;
        // Keep the old table charged until try_reserve releases it.
        counter.set(
            self.resident_bytes()
                .checked_add(needed)
                .ok_or(StoreError::ActiveRowOverflow)?,
        )?;
        self.terms
            .try_reserve(capacity.saturating_sub(self.terms.len()))
            .map_err(|_| StoreError::AllocationFailed {
                needed: needed as u64,
                component: "lexical terms map",
            })?;
        self.term_capacity = self.term_capacity.max(self.terms.capacity());
        counter.set(self.resident_bytes())
    }

    /// Creates an empty segment index.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the number of rows.
    #[must_use]
    pub const fn row_count(&self) -> u32 {
        self.row_count
    }

    /// Returns true when the segment holds no rows.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.row_count == 0
    }

    /// Returns the posting lists, ordered by term then field.
    ///
    /// The sorted view is built here, once per call, rather than being
    /// maintained on every insert; seal is its one hot caller.
    pub fn postings(&self) -> impl Iterator<Item = (&TermKey, &PostingList)> {
        let mut entries: Vec<(&TermKey, usize)> =
            self.terms.iter().map(|(key, slot)| (key, *slot)).collect();
        entries.sort_unstable_by(|left, right| left.0.cmp(right.0));
        entries
            .into_iter()
            .filter_map(|(key, slot)| self.lists.get(slot).map(|list| (key, list)))
    }

    /// Returns one term's posting list within one field.
    #[must_use]
    pub fn posting_list(&self, term: &[u8], field: FieldId) -> Option<&PostingList> {
        let slot = *self.terms.get(&TermKey {
            term: term.to_vec(),
            field,
        })?;
        self.lists.get(slot)
    }

    /// Returns the analyzed token count of one row's field.
    #[must_use]
    pub fn field_length(&self, row: u32, field: FieldId) -> u32 {
        self.field_lengths(field)
            .and_then(|lengths| {
                usize::try_from(row)
                    .ok()
                    .and_then(|slot| lengths.get(slot).copied())
            })
            .unwrap_or(0)
    }

    /// Returns the fields this segment recorded lengths for, ascending.
    pub fn fields(&self) -> impl Iterator<Item = FieldId> + '_ {
        self.lengths.iter().map(|entry| entry.field)
    }

    /// Returns one field's dense length array, if the field was ever set.
    ///
    /// The slice is exactly [`Self::row_count`] long, so a caller scoring a
    /// single unweighted field can borrow it rather than rebuild it. A
    /// linear scan over the field table is right here: a schema has a
    /// handful of fields, and a map would trade an index for a descent.
    #[must_use]
    pub fn field_lengths(&self, field: FieldId) -> Option<&[u32]> {
        self.lengths
            .iter()
            .find(|entry| entry.field == field)
            .map(|entry| entry.lengths.as_slice())
    }

    /// Returns the analyzed token count of one row across every field.
    #[must_use]
    pub fn document_length(&self, row: u32) -> u32 {
        let Ok(slot) = usize::try_from(row) else {
            return 0;
        };
        self.lengths
            .iter()
            .filter_map(|entry| entry.lengths.get(slot).copied())
            .fold(0_u32, u32::saturating_add)
    }

    /// Returns the segment's total analyzed token count.
    #[must_use]
    pub fn total_tokens(&self) -> u64 {
        self.lengths
            .iter()
            .flat_map(|entry| entry.lengths.iter())
            .map(|length| u64::from(*length))
            .sum()
    }

    pub(crate) fn resident_bytes(&self) -> usize {
        let term_slots =
            allocation_bytes::<(TermKey, usize)>(self.term_capacity).unwrap_or(usize::MAX);
        let term_bytes = self.term_bytes;
        let list_bytes = self
            .lists
            .capacity()
            .saturating_mul(std::mem::size_of::<PostingList>())
            .saturating_add(self.posting_bytes);
        let free_slot_bytes = self
            .free_slots
            .capacity()
            .saturating_mul(std::mem::size_of::<usize>());
        let length_bytes = self
            .lengths
            .capacity()
            .saturating_mul(std::mem::size_of::<FieldLengths>())
            .saturating_add(
                self.lengths
                    .iter()
                    .map(|entry| entry.lengths.capacity().saturating_mul(4))
                    .fold(0_usize, usize::saturating_add),
            );
        term_slots
            .saturating_add(term_bytes)
            .saturating_add(list_bytes)
            .saturating_add(length_bytes)
            .saturating_add(free_slot_bytes)
    }

    /// Independent full scan used to prove the incremental charge stays exact.
    #[cfg(test)]
    pub(crate) fn resident_bytes_rescan(&self) -> usize {
        let term_slots =
            allocation_bytes::<(TermKey, usize)>(self.term_capacity).unwrap_or(usize::MAX);
        let term_bytes = self
            .terms
            .keys()
            .map(|key| key.term.capacity())
            .fold(0_usize, usize::saturating_add);
        let list_bytes = self
            .lists
            .capacity()
            .saturating_mul(std::mem::size_of::<PostingList>())
            .saturating_add(
                self.lists
                    .iter()
                    .map(PostingList::resident_bytes)
                    .fold(0_usize, usize::saturating_add),
            );
        let free_slot_bytes = self
            .free_slots
            .capacity()
            .saturating_mul(std::mem::size_of::<usize>());
        let length_bytes = self
            .lengths
            .capacity()
            .saturating_mul(std::mem::size_of::<FieldLengths>())
            .saturating_add(
                self.lengths
                    .iter()
                    .map(|entry| entry.lengths.capacity().saturating_mul(4))
                    .fold(0_usize, usize::saturating_add),
            );
        term_slots
            .saturating_add(term_bytes)
            .saturating_add(list_bytes)
            .saturating_add(length_bytes)
            .saturating_add(free_slot_bytes)
    }

    /// Records one row's analyzed length for one field.
    ///
    /// Pads the field's array with zeros for any earlier row that did not
    /// carry the field, which is what keeps every array dense.
    fn set_field_length(&mut self, row: u32, field: FieldId, length: u32) {
        let Ok(slot) = usize::try_from(row) else {
            return;
        };
        let position = match self.lengths.iter().position(|entry| entry.field == field) {
            Some(position) => position,
            None => {
                // Fields stay ascending so the table has a stable order.
                let position = self
                    .lengths
                    .iter()
                    .position(|entry| entry.field > field)
                    .unwrap_or(self.lengths.len());
                self.lengths.insert(
                    position,
                    FieldLengths {
                        field,
                        lengths: Vec::new(),
                    },
                );
                position
            }
        };
        let Some(entry) = self.lengths.get_mut(position) else {
            return;
        };
        if let Some(existing) = entry.lengths.get_mut(slot) {
            *existing = length;
        } else {
            entry.lengths.resize(slot, 0);
            entry.lengths.push(length);
        }
    }

    /// Extends every field array to cover `rows` rows.
    fn pad_lengths_to(&mut self, rows: usize) {
        for entry in &mut self.lengths {
            entry.lengths.resize(rows, 0);
        }
    }

    /// Appends one analyzed document as the next dense row.
    ///
    /// # Errors
    ///
    /// Returns [`IndexError::Postings`] when the analyzer produces a token
    /// stream a posting list refuses, which would be a tokenizer contract
    /// violation rather than bad input.
    pub fn push_document(
        &mut self,
        analyzer: &Analyzer,
        document: &Document,
    ) -> Result<u32, IndexError> {
        self.push_document_controlled(analyzer, document, &mut |_, _| Ok(()))
    }

    pub(crate) fn push_document_controlled<E: From<IndexError>>(
        &mut self,
        analyzer: &Analyzer,
        document: &Document,
        reserve: &mut impl FnMut(&mut Self, usize) -> Result<(), E>,
    ) -> Result<u32, E> {
        let row = self.row_count;
        for (field, text) in document.fields() {
            let tokens = analyzer.analyze(text);
            self.accumulate(row, field, &tokens, Placement::Append, reserve)?;
        }
        self.finish_row();
        Ok(row)
    }

    /// Replaces one existing row's document in place.
    ///
    /// `previous` must be the document the row was indexed from. The row's
    /// postings for every term of `previous` are removed, a term left with
    /// no posting is dropped, the row's lengths are reset, and `replacement`
    /// is folded in at the same row. The result answers exactly as a
    /// segment rebuilt with the row's document swapped, and the cost is
    /// proportional to the two documents, not to the segment.
    ///
    /// # Errors
    ///
    /// Returns [`IndexError::ReplacedRowOutOfRange`] for a row the segment
    /// does not hold, [`IndexError::ReplacedPostingMissing`] when `previous`
    /// is not what the row was indexed from, and [`IndexError::Postings`]
    /// as [`Self::push_document`]. On an error the segment is partly
    /// updated; the caller discards it.
    pub fn replace_document(
        &mut self,
        analyzer: &Analyzer,
        row: u32,
        previous: &Document,
        replacement: &Document,
    ) -> Result<(), IndexError> {
        self.replace_document_controlled(analyzer, row, previous, replacement, &mut |_, _| Ok(()))
    }

    pub(crate) fn replace_document_controlled<E: From<IndexError>>(
        &mut self,
        analyzer: &Analyzer,
        row: u32,
        previous: &Document,
        replacement: &Document,
        reserve: &mut impl FnMut(&mut Self, usize) -> Result<(), E>,
    ) -> Result<(), E> {
        let out_of_range = IndexError::ReplacedRowOutOfRange {
            row,
            row_count: self.row_count,
        };
        if row >= self.row_count {
            return Err(out_of_range.into());
        }
        let slot = usize::try_from(row).map_err(|_| out_of_range)?;
        for (field, text) in previous.fields() {
            let tokens = analyzer.analyze(text);
            count_tokens_indexed(tokens.len());
            let mut terms: Vec<&str> = tokens.iter().map(|token| token.term.as_str()).collect();
            terms.sort_unstable();
            terms.dedup();
            let mut probe = TermKey {
                term: Vec::new(),
                field,
            };
            for term in terms {
                probe.term.clear();
                probe.term.extend_from_slice(term.as_bytes());
                let missing = IndexError::ReplacedPostingMissing { row };
                let list_slot = self.terms.get(&probe).copied().ok_or(missing.clone())?;
                let list = self.lists.get_mut(list_slot).ok_or(missing.clone())?;
                let posting_slot = list
                    .postings()
                    .binary_search_by_key(&row, |posting| posting.docid)
                    .map_err(|_| missing.clone())?;
                let position_bytes = list
                    .postings()
                    .get(posting_slot)
                    .ok_or(missing.clone())?
                    .positions
                    .capacity()
                    .saturating_mul(4);
                crate::fts::postings::count_accounting_visits(1);
                if !list.remove(row) {
                    return Err(missing.into());
                }
                self.posting_bytes = self.posting_bytes.saturating_sub(position_bytes);
                if list.is_empty() {
                    self.posting_bytes = self.posting_bytes.saturating_sub(list.allocation_bytes());
                    *list = PostingList::new();
                    if let Some((key, _)) = self.terms.remove_entry(&probe) {
                        self.term_bytes = self.term_bytes.saturating_sub(key.term.capacity());
                    }
                    self.free_slots.push(list_slot);
                }
            }
        }
        for entry in &mut self.lengths {
            if let Some(length) = entry.lengths.get_mut(slot) {
                *length = 0;
            }
        }
        for (field, text) in replacement.fields() {
            let tokens = analyzer.analyze(text);
            self.accumulate(row, field, &tokens, Placement::Insert, reserve)?;
        }
        // A field new to the segment must still cover every row.
        self.pad_lengths_to(usize::try_from(self.row_count).unwrap_or(usize::MAX));
        Ok(())
    }

    /// Appends many documents, analyzing them in parallel.
    ///
    /// The result is identical to pushing the same documents one at a time
    /// in slice order: analysis is independent per document and runs on
    /// explicit scoped threads, while accumulation happens strictly in row
    /// order on the calling thread — so nothing about the outcome depends
    /// on scheduling, and the single-writer invariant is untouched.
    ///
    /// `threads` is the caller's policy; one or fewer runs sequentially.
    /// Analysis is batched so the in-flight token working set stays
    /// proportional to the batch, never to the corpus.
    ///
    /// # Errors
    ///
    /// As [`Self::push_document`]. On an error, documents before the
    /// failing one remain indexed, exactly as a sequential loop would
    /// leave them.
    pub fn push_documents(
        &mut self,
        analyzer: &Analyzer,
        documents: &[Document],
        threads: usize,
    ) -> Result<(), IndexError> {
        let workers = threads.max(1).min(documents.len().max(1));
        if workers <= 1 {
            for document in documents {
                self.push_document(analyzer, document)?;
            }
            return Ok(());
        }
        let batch_size = workers.saturating_mul(32).max(1);
        for batch in documents.chunks(batch_size) {
            let mut analyzed: Vec<Vec<(FieldId, Vec<Token>)>> = Vec::new();
            analyzed.resize_with(batch.len(), Vec::new);
            let stride = batch.len().div_ceil(workers);
            std::thread::scope(|scope| {
                let mut rest = analyzed.as_mut_slice();
                let mut offset = 0_usize;
                while !rest.is_empty() {
                    let take = stride.min(rest.len());
                    let (mine, tail) = rest.split_at_mut(take);
                    rest = tail;
                    let end = offset.saturating_add(take);
                    let docs = batch.get(offset..end).unwrap_or(&[]);
                    offset = end;
                    scope.spawn(move || {
                        for (slot, document) in mine.iter_mut().zip(docs) {
                            *slot = document
                                .fields()
                                .map(|(field, text)| (field, analyzer.analyze(text)))
                                .collect();
                        }
                    });
                }
            });
            for fields in &analyzed {
                let row = self.row_count;
                for (field, tokens) in fields {
                    self.accumulate(row, *field, tokens, Placement::Append, &mut |_, _| {
                        Ok::<(), IndexError>(())
                    })?;
                }
                self.finish_row();
            }
        }
        Ok(())
    }

    /// Folds one field's analyzed tokens into the postings for one row.
    fn accumulate<E: From<IndexError>>(
        &mut self,
        row: u32,
        field: FieldId,
        tokens: &[Token],
        placement: Placement,
        reserve: &mut impl FnMut(&mut Self, usize) -> Result<(), E>,
    ) -> Result<(), E> {
        count_tokens_indexed(tokens.len());
        // Position count is the analyzed length: stacked variants share
        // a position and must not inflate the document length, or avgdl
        // stops matching the unit being scored.
        let length = tokens
            .iter()
            .map(|token| token.position)
            .max()
            .map_or(0, |highest| highest.saturating_add(1));
        self.set_field_length(row, field, length);

        // Sort-based grouping over borrowed terms replaces the per-document
        // `BTreeMap<Vec<u8>, Vec<u32>>`: no map to build and tear down per
        // document, no allocation per (document, term). `str` compares
        // byte-wise, so groups arrive in exactly the order the map's keys
        // did, and a group's positions arrive already sorted.
        let mut scratch: Vec<(&str, u32)> = tokens
            .iter()
            .map(|token| (token.term.as_str(), token.position))
            .collect();
        scratch.sort_unstable();

        // One reusable probe key per field: lookups borrow it, and only a
        // term new to the segment pays an owned copy.
        let mut probe = TermKey {
            term: Vec::new(),
            field,
        };
        let mut start = 0_usize;
        while let Some((term, _)) = scratch.get(start).copied() {
            let mut end = start.saturating_add(1);
            while scratch.get(end).is_some_and(|(next, _)| *next == term) {
                end = end.saturating_add(1);
            }
            let group = scratch.get(start..end).unwrap_or(&[]);
            let mut positions: Vec<u32> = Vec::with_capacity(group.len());
            for (_, position) in group {
                if positions.last() != Some(position) {
                    positions.push(*position);
                }
            }
            let tf = u32::try_from(positions.len()).unwrap_or(u32::MAX);
            probe.term.clear();
            probe.term.extend_from_slice(term.as_bytes());
            let posting = Posting {
                docid: row,
                tf,
                positions,
            };
            let position_bytes = posting.positions.capacity().saturating_mul(4);
            crate::fts::postings::count_accounting_visits(1);
            match self.terms.get(&probe).copied() {
                Some(slot) => {
                    // The map only ever hands out slots minted below, so
                    // the lookup cannot miss; the `if let` is the panic-free
                    // spelling of that impossibility.
                    if let Some(list) = self.lists.get_mut(slot) {
                        let previous = list.allocation_bytes();
                        match placement {
                            Placement::Append => list.push(posting).map_err(IndexError::from)?,
                            Placement::Insert => list.insert(posting).map_err(IndexError::from)?,
                        }
                        self.posting_bytes = self
                            .posting_bytes
                            .saturating_sub(previous)
                            .saturating_add(list.allocation_bytes())
                            .saturating_add(position_bytes);
                    }
                }
                None => {
                    let grows = self.terms.len() == self.terms.capacity();
                    if grows {
                        reserve(self, self.terms.len().saturating_add(1))?;
                    }
                    let mut list = PostingList::new();
                    list.push(posting).map_err(IndexError::from)?;
                    self.posting_bytes = self
                        .posting_bytes
                        .saturating_add(list.allocation_bytes())
                        .saturating_add(position_bytes);
                    let slot = if let Some(slot) = self.free_slots.pop()
                        && let Some(free) = self.lists.get_mut(slot)
                    {
                        *free = list;
                        slot
                    } else {
                        let slot = self.lists.len();
                        self.lists.push(list);
                        slot
                    };
                    let key = TermKey {
                        term: probe.term.clone(),
                        field,
                    };
                    self.term_bytes = self.term_bytes.saturating_add(key.term.capacity());
                    self.terms.insert(key, slot);
                    if grows {
                        self.term_capacity = self.term_capacity.max(self.terms.capacity());
                    }
                }
            }
            start = end;
        }
        Ok(())
    }

    /// Seals the row: every field array is padded to cover it.
    fn finish_row(&mut self) {
        self.row_count = self.row_count.saturating_add(1);
        self.pad_lengths_to(usize::try_from(self.row_count).unwrap_or(usize::MAX));
    }
}

/// The store-wide lexical index across every segment.
///
/// # Segments here are SEALED
///
/// [`push_segment`](Self::push_segment) encodes the active segment into the
/// persisted posting layout and keeps only that. There is therefore exactly
/// one scoring path in the engine — over bytes — rather than an in-memory
/// one that ships and a persisted one that is only ever tested.
#[derive(Clone, Debug, Default)]
pub struct LexicalIndex {
    segments: Vec<Arc<SealedSegment>>,
    statistics: Vec<Arc<LiveSegmentStatistics>>,
    has_frequency_cache: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct LiveSegmentCounters {
    documents: u64,
    tokens: u64,
}

/// Validated live membership and counters, independent of source ordinal.
#[derive(Clone, Debug)]
pub(crate) struct LiveSegmentStatistics {
    pub(crate) rows: DocBitmap,
    counters: LiveSegmentCounters,
    pub(crate) frequency_cache: Option<Arc<super::live_df::LiveFrequencyCache>>,
}

impl LiveSegmentStatistics {
    pub(crate) fn build_controlled<E: From<IndexError>>(
        ordinal: usize,
        segment: &SealedSegment,
        rows: &DocBitmap,
        work: &mut super::control::WorkCheck<impl FnMut() -> Result<(), E>>,
    ) -> Result<Self, E> {
        work.check_now()?;
        let value = Self {
            counters: live_segment_counters_controlled(ordinal, segment, rows, work)?,
            rows: rows.clone(),
            frequency_cache: None,
        };
        work.check_now()?;
        Ok(value)
    }

    pub(crate) fn build(
        ordinal: usize,
        segment: &SealedSegment,
        rows: &DocBitmap,
    ) -> Result<Self, IndexError> {
        Self::build_controlled(
            ordinal,
            segment,
            rows,
            &mut super::control::WorkCheck::new(|| Ok(())),
        )
    }

    pub(crate) fn allocation_bytes(rows: &DocBitmap) -> Option<usize> {
        std::mem::size_of::<Self>()
            .checked_add(2 * std::mem::size_of::<usize>())?
            .checked_add(rows.resident_bytes()?)
    }
}

impl LexicalIndex {
    /// Creates an empty index.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Seals one active segment and appends it.
    ///
    /// # Errors
    ///
    /// Returns [`IndexError::Postings`] when the encoder rejects the
    /// segment's geometry or refuses to read back what it just wrote. Both
    /// are broken-writer conditions, and they surface here rather than
    /// becoming a decode fault inside a later query.
    pub fn push_segment(&mut self, segment: SegmentIndex) -> Result<(), IndexError> {
        self.push_sealed(SealedSegment::seal(&segment)?);
        Ok(())
    }

    /// Appends an already-sealed segment.
    pub fn push_sealed(&mut self, segment: SealedSegment) {
        self.push_shared(Arc::new(segment));
    }

    fn push_shared(&mut self, segment: Arc<SealedSegment>) {
        self.statistics.push(Arc::new(LiveSegmentStatistics {
            rows: DocBitmap::full(segment.row_count()),
            frequency_cache: None,
            counters: LiveSegmentCounters {
                documents: u64::from(segment.row_count()),
                tokens: segment.total_tokens(),
            },
        }));
        self.segments.push(segment);
    }

    /// Appends an already-sealed segment with exact live-row counters.
    ///
    /// The row set is the segment tombstone state's live bitmap, not a query
    /// filter. Capturing it here keeps BM25 corpus statistics independent of
    /// later metadata allow-lists while avoiding any posting-list rewrite.
    ///
    /// # Errors
    ///
    /// Returns [`IndexError::LiveRowOutOfRange`] when the tombstone state
    /// names a row outside the sealed segment, or
    /// [`IndexError::LiveLengthMissing`] when a sealed length counter violates
    /// its dense-row invariant.
    pub fn push_sealed_with_live_rows(
        &mut self,
        segment: SealedSegment,
        live_rows: &DocBitmap,
    ) -> Result<(), IndexError> {
        self.push_shared_with_live_rows(Arc::new(segment), live_rows)
    }

    pub(crate) fn push_shared_with_live_rows(
        &mut self,
        segment: Arc<SealedSegment>,
        live_rows: &DocBitmap,
    ) -> Result<(), IndexError> {
        let statistics = Arc::new(LiveSegmentStatistics::build(
            self.segments.len(),
            &segment,
            live_rows,
        )?);
        self.push_shared_with_statistics(segment, statistics);
        Ok(())
    }

    /// Only a validated contribution can enter this path; callers cannot supply
    /// independent counters or change the membership behind the shared value.
    pub(crate) fn push_shared_with_statistics(
        &mut self,
        segment: Arc<SealedSegment>,
        statistics: Arc<LiveSegmentStatistics>,
    ) {
        self.has_frequency_cache |= statistics.frequency_cache.is_some();
        self.segments.push(segment);
        self.statistics.push(statistics);
    }

    /// Returns the segments in seal order.
    #[must_use]
    pub fn segments(&self) -> &[Arc<SealedSegment>] {
        &self.segments
    }

    /// Bytes for the index spines. Cached contributions own and account their
    /// shared membership/counters separately for the full Arc lifetime.
    pub(crate) fn resident_spine_bytes(&self) -> Option<usize> {
        self.segments
            .capacity()
            .checked_mul(std::mem::size_of::<Arc<SealedSegment>>())?
            .checked_add(
                self.statistics
                    .capacity()
                    .checked_mul(std::mem::size_of::<Arc<LiveSegmentStatistics>>())?,
            )
    }

    /// Iterates the analyzed vocabulary of every segment.
    ///
    /// Terms may repeat across segments; callers that expand a structured
    /// query must impose their own deterministic de-duplication.
    pub fn terms(&self) -> impl Iterator<Item = &[u8]> {
        self.segments.iter().flat_map(|segment| segment.terms())
    }

    pub(crate) fn vocabulary_terms(&self) -> impl Iterator<Item = (&[u8], FieldId)> + Clone {
        self.segments
            .iter()
            .flat_map(|segment| segment.vocabulary_terms())
    }

    /// Returns the store-wide document count.
    #[must_use]
    pub fn document_count(&self) -> u64 {
        self.statistics
            .iter()
            .map(|statistics| statistics.counters.documents)
            .fold(0_u64, u64::saturating_add)
    }

    /// Returns the store-wide analyzed token count.
    #[must_use]
    pub fn total_tokens(&self) -> u64 {
        self.statistics
            .iter()
            .map(|statistics| statistics.counters.tokens)
            .fold(0_u64, u64::saturating_add)
    }

    /// Returns the store-wide corpus statistics.
    ///
    /// This is the ONLY source of `N` and `avgdl` for scoring. There is
    /// deliberately no per-segment equivalent.
    ///
    /// # Errors
    ///
    /// Returns [`IndexError::Stats`] when the index holds no documents or
    /// no tokens, because `avgdl` is undefined then.
    pub fn corpus_stats(&self) -> Result<CorpusStats, IndexError> {
        #[cfg(any(test, feature = "test-seams"))]
        super::preparation_observer::corpus_statistics();
        Ok(CorpusStats::new(
            self.document_count(),
            self.total_tokens(),
        )?)
    }

    /// Returns the store-wide document frequency of one term.
    ///
    /// Summed across every segment and every requested field. A document
    /// containing the term in two fields counts once, which is what makes
    /// this a *document* frequency rather than a posting count. Segments
    /// without tombstones answer from their sealed dictionary.
    /// Segments with tombstones decode document identifiers and count only
    /// rows in the same live bitmap used for `N` and `avgdl`.
    #[must_use]
    pub fn document_frequency(&self, term: &[u8], fields: &[FieldId]) -> u32 {
        #[cfg(any(test, feature = "test-seams"))]
        super::preparation_observer::frequency();
        self.segments
            .iter()
            .zip(&self.statistics)
            .map(|(segment, statistics)| {
                let live_rows = &statistics.rows;
                if live_rows.cardinality() == u64::from(segment.row_count()) {
                    segment.document_frequency(term, fields)
                } else {
                    segment.live_document_frequency(term, fields, live_rows)
                }
            })
            .fold(0_u32, u32::saturating_add)
    }

    /// Scoring can report cache synchronization errors without changing the
    /// public infallible, uncached statistics inspection method. Callers pass
    /// the canonical field list from FieldWeights.
    #[inline]
    pub(crate) fn prepared_document_frequency(
        &self,
        term: &[u8],
        fields: &[FieldId],
    ) -> Result<u32, IndexError> {
        // Preserve the original dictionary/statistics loop when no contribution
        // owns a cache. Cache synchronization and fallible accumulation belong
        // only to snapshots that can actually use them.
        if !self.has_frequency_cache {
            return Ok(self.document_frequency(term, fields));
        }
        self.cached_document_frequency(term, fields)
    }

    pub(crate) fn prepared_document_frequency_controlled<E>(
        &self,
        term: &[u8],
        fields: &[FieldId],
        mut check: impl FnMut() -> Result<(), E>,
    ) -> Result<u32, super::search::ControlledSearchError<E>> {
        use super::search::ControlledSearchError;
        #[cfg(any(test, feature = "test-seams"))]
        super::preparation_observer::frequency();
        check().map_err(ControlledSearchError::Control)?;
        let mut total = 0_u32;
        for (segment, statistics) in self.segments.iter().zip(&self.statistics) {
            let live = &statistics.rows;
            let frequency = if live.cardinality() == u64::from(segment.row_count()) {
                segment
                    .document_frequency_controlled(term, fields, &mut check)
                    .map_err(ControlledSearchError::Control)?
            } else if let Some(cache) = &statistics.frequency_cache {
                cache.frequency_controlled(segment, live, term, fields, &mut check)?
            } else {
                segment
                    .live_document_frequency_controlled(term, fields, live, &mut check)
                    .map_err(ControlledSearchError::Control)?
            };
            total = total.saturating_add(frequency);
        }
        check().map_err(ControlledSearchError::Control)?;
        Ok(total)
    }

    fn cached_document_frequency(
        &self,
        term: &[u8],
        fields: &[FieldId],
    ) -> Result<u32, IndexError> {
        #[cfg(any(test, feature = "test-seams"))]
        super::preparation_observer::frequency();
        self.segments.iter().zip(&self.statistics).try_fold(
            0_u32,
            |total, (segment, statistics)| {
                let live = &statistics.rows;
                let frequency = if live.cardinality() == u64::from(segment.row_count()) {
                    segment.document_frequency(term, fields)
                } else if let Some(cache) = &statistics.frequency_cache {
                    cache.frequency(segment, live, term, fields)?
                } else {
                    segment.live_document_frequency(term, fields, live)
                };
                Ok(total.saturating_add(frequency))
            },
        )
    }
}

fn live_segment_counters_controlled<E: From<IndexError>>(
    ordinal: usize,
    segment: &SealedSegment,
    live_rows: &DocBitmap,
    work: &mut super::control::WorkCheck<impl FnMut() -> Result<(), E>>,
) -> Result<LiveSegmentCounters, E> {
    work.check_now()?;
    if let Some(row) = live_rows.first_at_or_after(segment.row_count()) {
        return Err(IndexError::LiveRowOutOfRange {
            segment: ordinal,
            row,
            row_count: segment.row_count(),
        }
        .into());
    }
    let tokens =
        live_rows.iter().try_fold(0_u64, |total, row| {
            work.step()?;
            #[cfg(any(test, feature = "test-seams"))]
            super::preparation_observer::live_statistics_row();
            let slot = usize::try_from(row).map_err(|_| IndexError::LiveLengthMissing {
                segment: ordinal,
                row,
            })?;
            let length = segment.total_lengths().get(slot).copied().ok_or(
                IndexError::LiveLengthMissing {
                    segment: ordinal,
                    row,
                },
            )?;
            Ok::<u64, E>(total.saturating_add(u64::from(length)))
        })?;
    work.check_now()?;
    Ok(LiveSegmentCounters {
        documents: live_rows.cardinality(),
        tokens,
    })
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic,
    clippy::unwrap_used
)]
mod tests {

    #[test]
    fn terms_table_charge_includes_empty_buckets_and_controls() {
        let mut index = SegmentIndex::new();
        index
            .push_document(&analyzer(), &Document::with_text("alpha"))
            .expect("index");
        let group = if cfg!(all(
            any(target_arch = "x86", target_arch = "x86_64"),
            target_feature = "sse2",
            not(miri)
        )) {
            16
        } else {
            8
        };
        let other = index.term_bytes
            + index.posting_bytes
            + index.lists.capacity() * std::mem::size_of::<PostingList>()
            + index.lengths.capacity() * std::mem::size_of::<FieldLengths>()
            + index
                .lengths
                .iter()
                .map(|entry| entry.lengths.capacity() * 4)
                .sum::<usize>();
        assert_eq!(
            index.resident_bytes() - other,
            4 * std::mem::size_of::<(TermKey, usize)>() + 4 + group
        );
    }

    #[test]
    fn parallel_analysis_is_identical_to_the_sequential_loop() {
        // push_documents claims scheduling independence; this holds it to
        // the sequential oracle exactly -- every posting, every position,
        // every length array -- across thread counts and a document count
        // chosen to leave a ragged final batch.
        let analyzer = analyzer();
        let documents: Vec<Document> = (0..97)
            .map(|index| {
                let mut document = Document::new();
                document.set(
                    FieldId(0),
                    &format!("alpha beta{} gamma-{index} 401k", index % 7),
                );
                document.set(FieldId(1), &format!("delta epsilon{} the quick", index % 5));
                document
            })
            .collect();
        let mut sequential = SegmentIndex::new();
        for document in &documents {
            sequential
                .push_document(&analyzer, document)
                .expect("indexable");
        }
        for threads in [1_usize, 3, 8] {
            let mut parallel = SegmentIndex::new();
            parallel
                .push_documents(&analyzer, &documents, threads)
                .expect("indexable");
            assert_eq!(parallel.row_count(), sequential.row_count());
            let ours: Vec<_> = parallel.postings().collect();
            let oracle: Vec<_> = sequential.postings().collect();
            assert_eq!(
                ours.len(),
                oracle.len(),
                "term count diverged at {threads} threads"
            );
            for ((key, list), (oracle_key, oracle_list)) in ours.iter().zip(&oracle) {
                assert_eq!(key, oracle_key);
                assert_eq!(
                    list.postings(),
                    oracle_list.postings(),
                    "postings diverged for {:?} at {threads} threads",
                    String::from_utf8_lossy(&key.term)
                );
            }
            for field in [FieldId(0), FieldId(1)] {
                assert_eq!(
                    parallel.field_lengths(field),
                    sequential.field_lengths(field),
                    "lengths diverged at {threads} threads"
                );
            }
        }
    }

    use super::*;
    use crate::fts::tokenizer::{Profile, TokenizerConfig};

    #[test]
    fn astra_18_live_statistics_cancel_inside_row_walk() {
        #[derive(Debug)]
        enum Error {
            Index(IndexError),
            Cancelled,
        }
        impl From<IndexError> for Error {
            fn from(error: IndexError) -> Self {
                Self::Index(error)
            }
        }
        let segment = SealedSegment::seal(&segment_of(&analyzer(), &vec!["alpha beta"; 4_097]))
            .expect("sealed row fixture");
        let live = DocBitmap::from_ids(0..4_096);
        super::super::preparation_observer::begin();
        let mut work = super::super::control::WorkCheck::new(|| {
            if super::super::preparation_observer::live_statistics_rows() >= 64 {
                Err(Error::Cancelled)
            } else {
                Ok(())
            }
        });
        let result = LiveSegmentStatistics::build_controlled(7, &segment, &live, &mut work);
        let visited = super::super::preparation_observer::live_statistics_rows();
        super::super::preparation_observer::take();
        println!("live statistics rows={visited}");
        assert!(matches!(result, Err(Error::Cancelled)));
        assert!((64..=128).contains(&visited));
        let mut clean = super::super::control::WorkCheck::new(|| Ok::<(), Error>(()));
        let value = LiveSegmentStatistics::build_controlled(7, &segment, &live, &mut clean)
            .expect("fresh control");
        assert_eq!(value.counters.documents, 4_096);
        assert_eq!(value.counters.tokens, 8_192);
        assert_eq!(value.rows, live);
        assert!(value.frequency_cache.is_none());
        assert!(matches!(
            LiveSegmentStatistics::build_controlled(
                7,
                &segment,
                &DocBitmap::from_ids([4_097]),
                &mut clean
            ),
            Err(Error::Index(IndexError::LiveRowOutOfRange {
                segment: 7,
                row: 4_097,
                row_count: 4_097
            }))
        ));
    }

    fn analyzer() -> Analyzer {
        Analyzer::new(TokenizerConfig::text_default()).expect("valid config")
    }

    #[test]
    fn replace_document_refuses_a_row_or_previous_text_the_index_does_not_hold() {
        let analyzer = analyzer();
        let mut index = SegmentIndex::new();
        index
            .push_document(&analyzer, &Document::with_text("alpha beta"))
            .expect("indexable");
        let replacement = Document::with_text("gamma");

        assert_eq!(
            index.replace_document(&analyzer, 1, &Document::with_text("alpha"), &replacement),
            Err(IndexError::ReplacedRowOutOfRange {
                row: 1,
                row_count: 1
            })
        );
        assert_eq!(
            index.replace_document(&analyzer, 0, &Document::with_text("delta"), &replacement),
            Err(IndexError::ReplacedPostingMissing { row: 0 })
        );
        // A term the index holds, but not for this row.
        index
            .push_document(&analyzer, &Document::with_text("epsilon"))
            .expect("indexable");
        assert_eq!(
            index.replace_document(&analyzer, 0, &Document::with_text("epsilon"), &replacement),
            Err(IndexError::ReplacedPostingMissing { row: 0 })
        );
        assert!(
            IndexError::ReplacedPostingMissing { row: 0 }
                .to_string()
                .contains("row 0")
        );
        assert!(
            IndexError::ReplacedRowOutOfRange {
                row: 1,
                row_count: 1
            }
            .to_string()
            .contains("1 rows")
        );
    }

    #[test]
    fn replace_document_reuses_a_dropped_term_slot_and_pads_a_new_field() {
        let analyzer = analyzer();
        let mut index = SegmentIndex::new();
        for text in ["alpha", "beta", "alpha delta"] {
            index
                .push_document(&analyzer, &Document::with_text(text))
                .expect("indexable");
        }
        let mut replacement = Document::with_text("alpha");
        replacement.set(FieldId(1), "gamma");
        index
            .replace_document(&analyzer, 1, &Document::with_text("beta"), &replacement)
            .expect("replace row 1");
        // "gamma" took the slot "beta" freed; no list was appended.
        assert_eq!(index.lists.len(), 3);
        assert!(index.posting_list(b"beta", DEFAULT_FIELD).is_none());
        assert!(index.free_slots.is_empty());
        assert_eq!(
            index.posting_list(b"alpha", DEFAULT_FIELD).map(|list| list
                .postings()
                .iter()
                .map(|p| p.docid)
                .collect::<Vec<_>>()),
            Some(vec![0, 1, 2])
        );
        assert_eq!(index.field_lengths(FieldId(1)), Some(&[0, 1, 0][..]));
        index
            .replace_document(
                &analyzer,
                2,
                &Document::with_text("alpha delta"),
                &Document::new(),
            )
            .expect("replace row 2");
        assert!(index.posting_list(b"delta", DEFAULT_FIELD).is_none());
        assert_eq!(index.free_slots.len(), 1);
        assert_eq!(index.total_tokens(), 3);
    }

    #[test]
    fn posting_list_insert_refuses_a_duplicate_row() {
        let mut list = PostingList::new();
        let posting = |docid| Posting {
            docid,
            tf: 1,
            positions: vec![0],
        };
        list.push(posting(0)).expect("append");
        list.push(posting(4)).expect("append");
        list.insert(posting(2)).expect("insert between");
        assert_eq!(
            list.insert(posting(2)),
            Err(PostingsError::DocidsNotAscending { docid: 2 })
        );
        assert_eq!(
            list.insert(Posting {
                docid: 3,
                tf: 0,
                positions: Vec::new()
            }),
            Err(PostingsError::ZeroTermFrequency)
        );
        assert_eq!(
            list.insert(Posting {
                docid: 3,
                tf: 2,
                positions: vec![1, 1]
            }),
            Err(PostingsError::PositionsNotAscending { position: 1 })
        );
        assert!(list.remove(2));
        assert!(!list.remove(2));
        assert_eq!(
            list.postings().iter().map(|p| p.docid).collect::<Vec<_>>(),
            vec![0, 4]
        );
    }

    fn code_analyzer() -> Analyzer {
        Analyzer::new(Profile::Code.config()).expect("valid config")
    }

    fn segment_of(analyzer: &Analyzer, texts: &[&str]) -> SegmentIndex {
        let mut segment = SegmentIndex::new();
        for text in texts {
            segment
                .push_document(analyzer, &Document::with_text(text))
                .expect("indexable");
        }
        segment
    }

    #[test]
    fn rows_are_dense_and_ascending() {
        let analyzer = analyzer();
        let mut segment = SegmentIndex::new();
        for (expected, text) in ["alpha", "beta", "gamma"].into_iter().enumerate() {
            let row = segment
                .push_document(&analyzer, &Document::with_text(text))
                .expect("indexable");
            assert_eq!(row, u32::try_from(expected).expect("small"));
        }
        assert_eq!(segment.row_count(), 3);
    }

    #[test]
    fn document_frequency_is_summed_across_segments_not_per_segment() {
        let analyzer = code_analyzer();
        let mut index = LexicalIndex::new();
        index
            .push_segment(segment_of(&analyzer, &["engine", "engine"]))
            .expect("seals");
        index
            .push_segment(segment_of(&analyzer, &["engine", "other"]))
            .expect("seals");
        assert_eq!(index.document_count(), 4);
        // Three of the four documents contain "engine", across two segments.
        assert_eq!(index.document_frequency(b"engine", &[DEFAULT_FIELD]), 3);
    }

    #[test]
    fn a_term_in_two_fields_of_one_document_counts_once() {
        let analyzer = code_analyzer();
        let mut segment = SegmentIndex::new();
        let mut document = Document::new();
        document.set(FieldId(0), "engine");
        document.set(FieldId(1), "engine");
        segment
            .push_document(&analyzer, &document)
            .expect("indexable");
        let mut index = LexicalIndex::new();
        index.push_segment(segment).expect("seals");
        assert_eq!(
            index.document_frequency(b"engine", &[FieldId(0), FieldId(1)]),
            1
        );
    }

    #[test]
    fn corpus_stats_span_every_segment() {
        let analyzer = code_analyzer();
        let mut index = LexicalIndex::new();
        index
            .push_segment(segment_of(&analyzer, &["a b c"]))
            .expect("seals");
        index
            .push_segment(segment_of(&analyzer, &["d e f g h"]))
            .expect("seals");
        let stats = index.corpus_stats().expect("two documents");
        assert_eq!(stats.document_count(), 2);
        assert_eq!(stats.total_tokens(), 8);
        assert!((stats.average_document_length() - 4.0).abs() < 1e-12);
    }

    #[test]
    fn live_row_counters_and_document_frequency_exclude_tombstones() {
        let analyzer = code_analyzer();
        let sealed = SealedSegment::seal(&segment_of(
            &analyzer,
            &["engine padding padding", "engine"],
        ))
        .expect("seal lexical segment");
        let live_rows = DocBitmap::from_ids([1]);
        let mut index = LexicalIndex::new();
        index
            .push_sealed_with_live_rows(sealed, &live_rows)
            .expect("valid live rows");

        let stats = index.corpus_stats().expect("one live document");
        assert_eq!(stats.document_count(), 1);
        assert_eq!(stats.total_tokens(), 1);
        assert_eq!(
            index.document_frequency(b"engine", &[DEFAULT_FIELD]),
            1,
            "document frequency must use the same live rows as corpus stats"
        );
    }

    #[test]
    fn an_empty_index_refuses_to_produce_statistics() {
        let index = LexicalIndex::new();
        assert!(index.corpus_stats().is_err());
    }

    #[test]
    fn document_length_counts_positions_not_tokens() {
        // Stacked variants share a position, so an identifier that emits
        // three tokens at one position must not count as three tokens of
        // length, or avgdl stops matching the unit being scored.
        let analyzer = code_analyzer();
        let mut segment = SegmentIndex::new();
        segment
            .push_document(&analyzer, &Document::with_text("put_if_match"))
            .expect("indexable");
        // Positions 0, 1, 2 for put / if / match.
        assert_eq!(segment.document_length(0), 3);
    }

    #[test]
    fn field_lengths_are_tracked_separately_and_summed() {
        let analyzer = code_analyzer();
        let mut segment = SegmentIndex::new();
        let mut document = Document::new();
        document.set(FieldId(0), "one two");
        document.set(FieldId(1), "three four five");
        segment
            .push_document(&analyzer, &document)
            .expect("indexable");
        assert_eq!(segment.field_length(0, FieldId(0)), 2);
        assert_eq!(segment.field_length(0, FieldId(1)), 3);
        assert_eq!(segment.document_length(0), 5);
        assert_eq!(segment.total_tokens(), 5);
        assert_eq!(segment.field_length(0, FieldId(9)), 0);
    }

    #[test]
    fn posting_lists_carry_positions() {
        let analyzer = code_analyzer();
        let segment = segment_of(&analyzer, &["alpha beta alpha"]);
        let list = segment
            .posting_list(b"alpha", DEFAULT_FIELD)
            .expect("alpha present");
        let posting = list.postings().first().expect("one posting");
        assert_eq!(posting.tf, 2);
        assert_eq!(posting.positions, vec![0, 2]);
    }

    #[test]
    fn an_absent_term_has_no_posting_list_and_zero_frequency() {
        let analyzer = code_analyzer();
        let segment = segment_of(&analyzer, &["alpha"]);
        assert!(segment.posting_list(b"omega", DEFAULT_FIELD).is_none());
        let mut index = LexicalIndex::new();
        index.push_segment(segment).expect("seals");
        assert_eq!(index.document_frequency(b"omega", &[DEFAULT_FIELD]), 0);
    }

    #[test]
    fn errors_render_useful_text() {
        assert!(
            IndexError::RowsNotAscending { row: 3 }
                .to_string()
                .contains("row order")
        );
        assert!(
            IndexError::Stats(Bm25Error::EmptyCorpus)
                .to_string()
                .contains("statistics")
        );
        assert!(
            IndexError::Postings(PostingsError::ZeroTermFrequency)
                .to_string()
                .contains("postings")
        );
    }
}