reflex-search 2.3.0

A local-first, structure-aware code search engine for AI agents
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
//! The index snapshot: which store files make up the index, and one reader over them.
//!
//! A snapshot is named by `.reflex/manifest.json`, the single commit point of an
//! index run. It is:
//!
//! - a **base**: `content.<g>.bin` + `trigrams.<g>.bin` (+ planning sizes) from the
//!   last full build, file ids `0..N-1`;
//! - optionally a **delta**: the same pair for files added or modified since, with
//!   their own ids `0..k-1`, seen through the snapshot as `N..N+k-1`;
//! - optionally a **recent** segment on top of the delta, ids after the delta's: the
//!   files of the latest updates. An update rebuilds only this small segment; when
//!   it passes its limits it is folded into a new delta (two tiers, so an update
//!   near the merge limit does not rebuild the whole delta);
//! - **tombstones**: base and delta ids that are deleted or superseded.
//!
//! Every file a manifest names is generation-suffixed and never modified once
//! written: a new run writes new files, then renames a new manifest into place. A
//! reader that opened one generation keeps reading it; one that opens after the
//! rename sees the next. No reader can pair files from two runs, which the
//! two-rename publish before the manifest allowed.
//!
//! `content.bin` and `trigrams.bin` exist as hard links to the base only while the
//! base alone is the snapshot (no delta, no tombstones), for older Reflex binaries
//! (which read only those names) and for tools. While a delta holds changes they
//! are absent, so an older binary stops instead of answering from the base alone.
//!
//! Without a manifest (a cache written before it existed) the fixed names are the
//! snapshot, as before.

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::content_store::ContentReader;
use crate::errors::ReflexError;
use crate::trigram::{
    EXOTIC_LONG_S_RANGE, FileLocation, ListPart, Trigram, TrigramIndex, TrigramList,
    exotic_singles, fold_windows, pattern_trigrams, plan_fold_intersection, plan_intersection,
    union_lists,
};

/// File name of the manifest in the cache directory.
pub const MANIFEST: &str = "manifest.json";
/// The names older binaries read; hard links to the base while it is the snapshot.
pub const FIXED_CONTENT: &str = "content.bin";
pub const FIXED_TRIGRAMS: &str = "trigrams.bin";

/// Manifest format this binary writes and reads.
const MANIFEST_FORMAT: u32 = 2;

/// One pair of stores (content + trigrams) named by a manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SegmentFiles {
    /// `content.bin`-format file name, relative to the cache directory.
    pub content: String,
    /// `trigrams.bin`-format file name.
    pub trigrams: String,
    /// Planning sizes of `trigrams` (see `trigram::plan_size`), when written.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan: Option<String>,
    /// Files in the segment (both stores hold this many).
    pub files: u64,
    /// Byte sizes of the two files, checked at open.
    pub content_bytes: u64,
    pub trigrams_bytes: u64,
}

impl SegmentFiles {
    fn names(&self) -> Vec<&str> {
        let mut out = vec![self.content.as_str(), self.trigrams.as_str()];
        out.extend(self.plan.as_deref());
        out
    }
}

/// The commit point of an index run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
    pub format: u32,
    /// Bumped at every publish; every file this manifest names carries it or an
    /// earlier generation's number.
    pub generation: u64,
    pub base: SegmentFiles,
    /// Files added or modified since the base was built.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delta: Option<SegmentFiles>,
    /// Files of the latest updates, above the delta (ids after the delta's).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub recent: Option<SegmentFiles>,
    /// Base and delta ids that are deleted or superseded, ascending.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tombstones: Vec<u32>,
    /// `(trigram, planning size)` of the tombstoned base files' postings: what the
    /// base's planning sizes over-count (see [`TombPlan`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tomb: Option<String>,
    /// The same for the tombstoned delta files' postings.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tomb_delta: Option<String>,
    /// Distinct trigrams with at least one posting in a live file.
    pub live_trigrams: u64,
    /// Unique per publish (random): what in-process caches of a publish's state
    /// key on, since a generation number repeats after the cache is cleared.
    #[serde(default)]
    pub publish_id: u64,
    /// Bytes of text of the live files (what `content.bin` of a full build of the
    /// same tree holds).
    pub live_corpus_bytes: u64,
    /// blake3 of this manifest serialized with an empty `checksum`.
    #[serde(default)]
    pub checksum: String,
}

impl Manifest {
    /// A manifest for a freshly built base.
    pub fn for_base(
        generation: u64,
        base: SegmentFiles,
        live_trigrams: u64,
        live_corpus_bytes: u64,
    ) -> Self {
        Self {
            format: MANIFEST_FORMAT,
            generation,
            base,
            delta: None,
            recent: None,
            tombstones: Vec::new(),
            tomb: None,
            tomb_delta: None,
            live_trigrams,
            publish_id: 0,
            live_corpus_bytes,
            checksum: String::new(),
        }
        .sealed()
    }

    /// This manifest with the current format and its checksum (after any field
    /// was set).
    pub fn sealed(mut self) -> Self {
        self.format = MANIFEST_FORMAT;
        self.publish_id = new_publish_id();
        self.checksum = self.compute_checksum();
        self
    }

    fn compute_checksum(&self) -> String {
        let mut unsigned = self.clone();
        unsigned.checksum = String::new();
        let body = serde_json::to_vec(&unsigned).expect("manifest serializes");
        blake3::hash(&body).to_hex().to_string()
    }

    /// Every file name this manifest refers to.
    pub fn files(&self) -> Vec<&str> {
        let mut out = self.base.names();
        for segment in [&self.delta, &self.recent].into_iter().flatten() {
            out.extend(segment.names());
        }
        out.extend(self.tomb.as_deref());
        out.extend(self.tomb_delta.as_deref());
        out
    }

    /// Whether the base alone is the snapshot (no delta, nothing tombstoned).
    pub fn base_only(&self) -> bool {
        self.delta.is_none() && self.recent.is_none() && self.tombstones.is_empty()
    }

    /// Files of the snapshot: what a full build of the same tree holds.
    pub fn live_files(&self) -> u64 {
        self.base.files - self.tombstones.len() as u64
            + self.delta.as_ref().map_or(0, |d| d.files)
            + self.recent.as_ref().map_or(0, |d| d.files)
    }
}

/// A random nonzero id: the clock, the process id and a counter, mixed by blake3.
fn new_publish_id() -> u64 {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let mut h = blake3::Hasher::new();
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    h.update(&nanos.to_le_bytes());
    h.update(&std::process::id().to_le_bytes());
    h.update(
        &COUNTER
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            .to_le_bytes(),
    );
    let bytes = h.finalize();
    u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes")).max(1)
}

/// `content.<g>.bin` / `trigrams.<g>.bin` / `trigrams.<g>.plan` of a base built
/// at generation `g`.
pub fn base_file_names(generation: u64) -> (String, String, String) {
    (
        format!("content.{generation}.bin"),
        format!("trigrams.{generation}.bin"),
        format!("trigrams.{generation}.plan"),
    )
}

/// The files of a delta built at generation `g`: content, trigrams, planning
/// sizes, tombstoned planning sizes.
pub fn delta_file_names(generation: u64) -> (String, String, String, String) {
    (
        format!("delta.{generation}.content.bin"),
        format!("delta.{generation}.trigrams.bin"),
        format!("delta.{generation}.plan"),
        format!("delta.{generation}.tomb"),
    )
}

/// The files of a recent segment built at generation `g` (content, trigrams,
/// planning sizes), and of the delta's tombstoned planning sizes.
pub fn recent_file_names(generation: u64) -> (String, String, String, String) {
    (
        format!("recent.{generation}.content.bin"),
        format!("recent.{generation}.trigrams.bin"),
        format!("recent.{generation}.plan"),
        format!("delta.{generation}.dtomb"),
    )
}

/// Whether `name` is a generation file this module writes (so cleanup may delete
/// it when no manifest names it).
pub fn is_generation_file(name: &str) -> bool {
    let parts: Vec<&str> = name.split('.').collect();
    let digits = |g: &str| !g.is_empty() && g.bytes().all(|b| b.is_ascii_digit());
    match parts.as_slice() {
        ["content" | "trigrams", g, "bin"] => digits(g),
        ["trigrams", g, "plan"] => digits(g),
        ["delta" | "recent", g, "content" | "trigrams", "bin"] => digits(g),
        ["delta" | "recent", g, "plan"] => digits(g),
        ["delta", g, "tomb" | "dtomb"] => digits(g),
        _ => false,
    }
}

/// Read the manifest; `Ok(None)` when there is none (a cache from before it).
pub fn read_manifest(cache_dir: &Path) -> Result<Option<Manifest>> {
    let path = cache_dir.join(MANIFEST);
    let bytes = match std::fs::read(&path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e).with_context(|| format!("Failed to read {}", path.display())),
    };
    let manifest: Manifest = serde_json::from_slice(&bytes)
        .with_context(|| format!("{} is not a valid manifest", path.display()))?;
    if manifest.format != MANIFEST_FORMAT {
        anyhow::bail!(
            "{} has format {}, this binary reads {}",
            path.display(),
            manifest.format,
            MANIFEST_FORMAT
        );
    }
    if manifest.checksum != manifest.compute_checksum() {
        anyhow::bail!("{} failed its checksum", path.display());
    }
    Ok(Some(manifest))
}

/// Publish `manifest`: tmp + fsync + rename + directory fsync. After this returns,
/// every new reader sees the snapshot it names.
pub fn write_manifest(cache_dir: &Path, manifest: &Manifest) -> Result<()> {
    use std::io::Write;
    let path = cache_dir.join(MANIFEST);
    let tmp = crate::atomic_write::tmp_path_for(&path);
    let body = serde_json::to_vec_pretty(manifest).context("Failed to serialize the manifest")?;
    {
        let mut f = std::fs::File::create(&tmp)
            .with_context(|| format!("Failed to create {}", tmp.display()))?;
        f.write_all(&body)?;
        f.sync_all()?;
    }
    crate::atomic_write::atomic_replace(&tmp, &path)
        .with_context(|| format!("Failed to move {} into place", path.display()))?;
    sync_dir(cache_dir);
    Ok(())
}

/// fsync a directory so a rename in it is durable (best effort; not on Windows).
pub fn sync_dir(dir: &Path) {
    #[cfg(unix)]
    if let Ok(d) = std::fs::File::open(dir) {
        let _ = d.sync_all();
    }
    #[cfg(not(unix))]
    let _ = dir;
}

/// Point `content.bin` / `trigrams.bin` at the manifest's base (hard links), for
/// older binaries, when the base alone is the snapshot. Otherwise, or where hard
/// links are not supported, the fixed names are removed: an older binary then
/// stops rather than answering from a base that lacks the delta.
pub fn link_fixed_names(cache_dir: &Path, manifest: &Manifest) {
    if !manifest.base_only() {
        unlink_fixed_names(cache_dir);
        return;
    }
    for (generation_file, fixed) in [
        (&manifest.base.content, FIXED_CONTENT),
        (&manifest.base.trigrams, FIXED_TRIGRAMS),
    ] {
        let target = cache_dir.join(fixed);
        let tmp = crate::atomic_write::tmp_path_for(&target);
        let _ = std::fs::remove_file(&tmp);
        let linked = std::fs::hard_link(cache_dir.join(generation_file), &tmp)
            .and_then(|_| crate::atomic_write::atomic_replace(&tmp, &target));
        if let Err(e) = linked {
            log::debug!(
                "Cannot link {} to {}: {}; removing it",
                fixed,
                generation_file,
                e
            );
            let _ = std::fs::remove_file(&tmp);
            let _ = std::fs::remove_file(&target);
        }
    }
}

/// Remove `content.bin` / `trigrams.bin` (before a manifest with a delta is
/// published, so no older binary reads the base alone once it is incomplete).
pub fn unlink_fixed_names(cache_dir: &Path) {
    let mut removed = false;
    for fixed in [FIXED_CONTENT, FIXED_TRIGRAMS] {
        match std::fs::remove_file(cache_dir.join(fixed)) {
            Ok(()) => removed = true,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => log::warn!("Could not remove {}: {}", fixed, e),
        }
    }
    // Already absent (a delta was live): nothing to make durable.
    if removed {
        sync_dir(cache_dir);
    }
}

/// Delete generation files that neither `current` nor `previous` names. A reader
/// that read the previous manifest a moment ago can still open its files; older
/// ones are gone. Failures (a file still mapped on Windows) are retried next run.
pub fn remove_unreferenced(cache_dir: &Path, current: &Manifest, previous: Option<&Manifest>) {
    let mut keep: std::collections::HashSet<&str> = current.files().into_iter().collect();
    if let Some(prev) = previous {
        keep.extend(prev.files());
    }
    let Ok(entries) = std::fs::read_dir(cache_dir) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if is_generation_file(name)
            && !keep.contains(name)
            && let Err(e) = std::fs::remove_file(entry.path())
        {
            log::debug!("Could not remove {}: {}", name, e);
        }
    }
}

const TOMB_MAGIC: &[u8; 4] = b"RFTB";
const TOMB_VERSION: u32 = 1;
const TOMB_HEADER: usize = 16;

/// `delta.<g>.tomb`: for each trigram with postings in tombstoned base files, the
/// planning size of those postings. The base's planning size minus this, plus the
/// delta's, is the planning size a full build of the same tree has. Header: magic
/// `RFTB`, version u32, entry count u64; then `(trigram u32, size u32)` sorted.
pub struct TombPlan {
    mmap: Option<memmap2::Mmap>,
    count: usize,
}

impl TombPlan {
    fn load(path: &Path) -> Result<Self> {
        let file = std::fs::File::open(path)
            .with_context(|| format!("Failed to open {}", path.display()))?;
        let len = file.metadata()?.len() as usize;
        if len == TOMB_HEADER {
            // An empty map cannot be mapped on every platform.
            return Ok(Self {
                mmap: None,
                count: 0,
            });
        }
        let mmap = unsafe {
            memmap2::Mmap::map(&file)
                .with_context(|| format!("Failed to mmap {}", path.display()))?
        };
        if mmap.len() < TOMB_HEADER || &mmap[0..4] != TOMB_MAGIC {
            anyhow::bail!("{} is not a tombstone planning file", path.display());
        }
        if u32::from_le_bytes(mmap[4..8].try_into().unwrap()) != TOMB_VERSION {
            anyhow::bail!("{} has an unsupported version", path.display());
        }
        let count = u64::from_le_bytes(mmap[8..16].try_into().unwrap()) as usize;
        if mmap.len() != TOMB_HEADER + count * 8 {
            anyhow::bail!("{} is truncated", path.display());
        }
        Ok(Self {
            mmap: Some(mmap),
            count,
        })
    }

    #[inline]
    fn entry(&self, i: usize) -> (Trigram, u32) {
        let mmap = self.mmap.as_ref().expect("non-empty");
        let off = TOMB_HEADER + i * 8;
        (
            u32::from_le_bytes(mmap[off..off + 4].try_into().unwrap()),
            u32::from_le_bytes(mmap[off + 4..off + 8].try_into().unwrap()),
        )
    }

    /// The tombstoned planning size of `trigram` (0 when none).
    pub fn get(&self, trigram: Trigram) -> u32 {
        let (mut lo, mut hi) = (0usize, self.count);
        while lo < hi {
            let mid = lo + (hi - lo) / 2;
            let (t, size) = self.entry(mid);
            match t.cmp(&trigram) {
                std::cmp::Ordering::Less => lo = mid + 1,
                std::cmp::Ordering::Greater => hi = mid,
                std::cmp::Ordering::Equal => return size,
            }
        }
        0
    }

    /// Every `(trigram, size)`, ascending.
    pub fn entries(&self) -> impl Iterator<Item = (Trigram, u32)> + '_ {
        (0..self.count).map(|i| self.entry(i))
    }
}

/// Write a tombstone planning file (`entries` sorted by trigram; tmp + fsync + rename).
pub fn write_tomb_file(path: &Path, entries: &[(Trigram, u32)]) -> Result<()> {
    use std::io::Write;
    let tmp = crate::atomic_write::tmp_path_for(path);
    {
        let mut w = std::io::BufWriter::new(
            std::fs::File::create(&tmp)
                .with_context(|| format!("Failed to create {}", tmp.display()))?,
        );
        w.write_all(TOMB_MAGIC)?;
        w.write_all(&TOMB_VERSION.to_le_bytes())?;
        w.write_all(&(entries.len() as u64).to_le_bytes())?;
        for (t, size) in entries {
            w.write_all(&t.to_le_bytes())?;
            w.write_all(&size.to_le_bytes())?;
        }
        w.flush()?;
        w.get_ref().sync_all()?;
    }
    crate::atomic_write::atomic_replace(&tmp, path)
        .with_context(|| format!("Failed to move {} into place", path.display()))
}

/// The first 32 bytes of a store file (both store formats have a 32-byte header).
fn read_header(cache_dir: &Path, logical: &str, name: &str) -> Result<[u8; 32]> {
    use std::io::Read;
    let mut header = [0u8; 32];
    std::fs::File::open(cache_dir.join(name))
        .and_then(|mut f| f.read_exact(&mut header))
        .map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                missing(logical, name)
            } else {
                ReflexError::CacheCorrupted(format!("{logical}: {name}: {e}")).into()
            }
        })?;
    Ok(header)
}

/// Whether the snapshot the manifest names is complete, without opening it: every
/// named file exists at the size the manifest recorded, each store's header has its
/// magic, version and the manifest's file count, and every tombstone is in range.
/// Reads one header per store, where [`IndexSnapshot::open`] maps the stores and
/// walks their path tables (an index run that changes nothing only needs this).
/// `Ok(None)` without a manifest.
pub fn check_published(cache_dir: &Path) -> Result<Option<Manifest>> {
    let Some(m) = read_manifest(cache_dir)? else {
        return Ok(None);
    };
    let u32_at = |h: &[u8; 32], at: usize| u32::from_le_bytes(h[at..at + 4].try_into().unwrap());
    let u64_at = |h: &[u8; 32], at: usize| u64::from_le_bytes(h[at..at + 8].try_into().unwrap());
    for segment in [Some(&m.base), m.delta.as_ref(), m.recent.as_ref()]
        .into_iter()
        .flatten()
    {
        check_size(
            cache_dir,
            "content.bin",
            &segment.content,
            segment.content_bytes,
        )?;
        check_size(
            cache_dir,
            "trigrams.bin",
            &segment.trigrams,
            segment.trigrams_bytes,
        )?;
        let content = read_header(cache_dir, "content.bin", &segment.content)?;
        if &content[0..4] != b"RFCT"
            || u32_at(&content, 4) != 2
            || u64_at(&content, 8) != segment.files
        {
            return Err(ReflexError::CacheCorrupted(format!(
                "content.bin: {} does not hold the manifest's {} files",
                segment.content, segment.files
            ))
            .into());
        }
        let trigrams = read_header(cache_dir, "trigrams.bin", &segment.trigrams)?;
        if &trigrams[0..4] != crate::trigram::MAGIC
            || u32_at(&trigrams, 4) != crate::trigram::VERSION
            || u64_at(&trigrams, 16) != segment.files
        {
            return Err(ReflexError::CacheCorrupted(format!(
                "trigrams.bin: {} does not hold the manifest's {} files",
                segment.trigrams, segment.files
            ))
            .into());
        }
        if let Some(plan) = &segment.plan
            && !cache_dir.join(plan).exists()
        {
            return Err(missing("trigrams.bin", plan));
        }
    }
    for tomb in [&m.tomb, &m.tomb_delta].into_iter().flatten() {
        if !cache_dir.join(tomb).exists() {
            return Err(missing("trigrams.bin", tomb));
        }
    }
    let bound = m.base.files + m.delta.as_ref().map_or(0, |d| d.files);
    if m.tombstones.iter().any(|&id| id as u64 >= bound) {
        return Err(ReflexError::CacheCorrupted(
            "content.bin: a tombstone is past the base and delta's files".to_string(),
        )
        .into());
    }
    Ok(Some(m))
}

/// One pair of opened stores.
pub struct Segment {
    pub content: ContentReader,
    pub trigrams: TrigramIndex,
}

/// Every reader of the stores goes through this: file ids, content, paths and
/// candidate lookups over the snapshot a manifest (or the legacy fixed names) names.
pub struct IndexSnapshot {
    base: Segment,
    delta: Option<Segment>,
    recent: Option<Segment>,
    /// Tombstoned base and delta ids, one bit each.
    dead: Vec<u64>,
    dead_count: usize,
    tomb: Option<TombPlan>,
    tomb_delta: Option<TombPlan>,
    /// Files in the base: the delta's ids start here.
    base_len: u32,
    /// Files in the delta: the recent segment's ids start at `base_len + delta_len`.
    delta_len: u32,
    /// The manifest this snapshot was opened from; `None` for a legacy cache.
    manifest: Option<Manifest>,
}

impl std::fmt::Debug for IndexSnapshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IndexSnapshot")
            .field("files", &self.live_file_count())
            .field("generation", &self.generation())
            .finish()
    }
}

/// Whether an error chain carries an `io::ErrorKind::NotFound`.
fn is_not_found(err: &anyhow::Error) -> bool {
    err.chain().any(|c| {
        c.downcast_ref::<std::io::Error>()
            .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound)
    })
}

/// A missing manifest-named file: a publish race (retried) or a damaged cache.
/// `logical` is the name an error shows (`content.bin` / `trigrams.bin`).
fn missing(logical: &str, name: &str) -> anyhow::Error {
    anyhow::Error::new(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        format!("{} is missing", name),
    ))
    .context(ReflexError::CacheCorrupted(format!(
        "{}: {} is missing",
        logical, name
    )))
}

/// Check a manifest-named file's size (a truncated or replaced file is corruption).
fn check_size(cache_dir: &Path, logical: &str, name: &str, expected: u64) -> Result<()> {
    match std::fs::metadata(cache_dir.join(name)) {
        Ok(md) if md.len() == expected => Ok(()),
        Ok(md) => Err(ReflexError::CacheCorrupted(format!(
            "{}: {} is {} bytes, the manifest says {}",
            logical,
            name,
            md.len(),
            expected
        ))
        .into()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(missing(logical, name)),
        Err(e) => Err(e).with_context(|| format!("Failed to stat {}", name)),
    }
}

/// Open one manifest-named segment.
fn open_segment(cache_dir: &Path, files: &SegmentFiles) -> Result<Segment> {
    check_size(
        cache_dir,
        "content.bin",
        &files.content,
        files.content_bytes,
    )?;
    check_size(
        cache_dir,
        "trigrams.bin",
        &files.trigrams,
        files.trigrams_bytes,
    )?;
    let content = ContentReader::open(cache_dir.join(&files.content))
        .map_err(|e| ReflexError::CacheCorrupted(format!("content.bin: {e:#}")))?;
    let mut trigrams = TrigramIndex::load(cache_dir.join(&files.trigrams))
        .map_err(|e| ReflexError::CacheCorrupted(format!("trigrams.bin: {e:#}")))?;
    // Planning sizes: the early-stop planner reads them instead of on-disk
    // bytes (an index without them plans by bytes, as before).
    if let Some(plan) = &files.plan {
        let plan_path = cache_dir.join(plan);
        if !plan_path.exists() {
            return Err(missing("trigrams.bin", plan));
        }
        trigrams
            .attach_plan(&plan_path)
            .map_err(|e| ReflexError::CacheCorrupted(format!("trigrams.bin: {e:#}")))?;
    }
    check_counts(&content, &trigrams)?;
    if content.file_count() as u64 != files.files {
        return Err(ReflexError::CacheCorrupted(format!(
            "content.bin holds {} files but the manifest lists {}",
            content.file_count(),
            files.files
        ))
        .into());
    }
    Ok(Segment { content, trigrams })
}

fn check_counts(content: &ContentReader, trigrams: &TrigramIndex) -> Result<()> {
    if trigrams.file_count() != content.file_count() {
        return Err(ReflexError::CacheCorrupted(format!(
            "trigrams.bin lists {} files but content.bin holds {} (index written by two runs?)",
            trigrams.file_count(),
            content.file_count()
        ))
        .into());
    }
    Ok(())
}

impl IndexSnapshot {
    /// Open the snapshot the manifest names (retrying when a concurrent publish
    /// removed a file between reading the manifest and opening it), or the legacy
    /// fixed names when there is no manifest.
    pub fn open(cache_dir: &Path) -> Result<Self> {
        Self::open_reading(cache_dir, || read_manifest(cache_dir))
    }

    /// [`Self::open`] with the manifest read by `read` (each attempt reads it again).
    fn open_reading(
        cache_dir: &Path,
        mut read: impl FnMut() -> Result<Option<Manifest>>,
    ) -> Result<Self> {
        let mut last: Option<anyhow::Error> = None;
        for attempt in 0..5u64 {
            let manifest =
                read().map_err(|e| ReflexError::CacheCorrupted(format!("content.bin: {e:#}")))?;
            let result = match manifest {
                None => return Self::open_legacy(cache_dir),
                Some(m) => Self::open_manifest(cache_dir, m),
            };
            match result {
                Ok(s) => return Ok(s),
                Err(e) if is_not_found(&e) => {
                    last = Some(e);
                    std::thread::sleep(std::time::Duration::from_millis(10 * (attempt + 1)));
                }
                Err(e) => return Err(e),
            }
        }
        Err(last.expect("at least one attempt"))
    }

    fn open_manifest(cache_dir: &Path, manifest: Manifest) -> Result<Self> {
        let base = open_segment(cache_dir, &manifest.base)?;
        let base_len = base.content.file_count() as u32;
        let delta = match &manifest.delta {
            Some(d) => Some(open_segment(cache_dir, d)?),
            None => None,
        };
        let delta_len = delta.as_ref().map_or(0, |d| d.content.file_count() as u32);
        let recent = match &manifest.recent {
            Some(d) => Some(open_segment(cache_dir, d)?),
            None => None,
        };
        let load_tomb = |name: &Option<String>| -> Result<Option<TombPlan>> {
            let Some(name) = name else { return Ok(None) };
            let tomb_path = cache_dir.join(name);
            if !tomb_path.exists() {
                return Err(missing("trigrams.bin", name));
            }
            Ok(Some(TombPlan::load(&tomb_path).map_err(|e| {
                ReflexError::CacheCorrupted(format!("trigrams.bin: {e:#}"))
            })?))
        };
        let tomb = load_tomb(&manifest.tomb)?;
        let tomb_delta = load_tomb(&manifest.tomb_delta)?;
        let dead_bound = base_len + delta_len;
        let mut dead = vec![0u64; (dead_bound as usize).div_ceil(64)];
        for &id in &manifest.tombstones {
            if id >= dead_bound {
                return Err(ReflexError::CacheCorrupted(format!(
                    "content.bin: tombstone {} is past the base and delta's {} files",
                    id, dead_bound
                ))
                .into());
            }
            dead[(id / 64) as usize] |= 1u64 << (id % 64);
        }
        Ok(Self {
            base,
            delta,
            recent,
            dead,
            dead_count: manifest.tombstones.len(),
            tomb,
            tomb_delta,
            base_len,
            delta_len,
            manifest: Some(manifest),
        })
    }

    fn open_legacy(cache_dir: &Path) -> Result<Self> {
        let content = ContentReader::open(cache_dir.join(FIXED_CONTENT))
            .map_err(|e| ReflexError::CacheCorrupted(format!("content.bin: {e:#}")))?;
        let trigrams_path = cache_dir.join(FIXED_TRIGRAMS);
        let trigrams = if trigrams_path.exists() {
            match TrigramIndex::load(&trigrams_path) {
                Ok(index) => index,
                // A format from another Reflex version is not corruption (see
                // `ReflexError::CacheVersionMismatch`): serve from an in-memory
                // rebuild, and let the schema-hash check report the index stale
                // so the caller re-indexes.
                Err(e) if e.to_string().contains("Unsupported trigrams.bin version") => {
                    log::warn!("{}; rebuilding trigram index in memory for this process", e);
                    crate::query::result::rebuild_trigram_index(&content)?
                }
                Err(e) => {
                    return Err(ReflexError::CacheCorrupted(format!("trigrams.bin: {e:#}")).into());
                }
            }
        } else {
            log::debug!("trigrams.bin not found, rebuilding from content store");
            crate::query::result::rebuild_trigram_index(&content)?
        };
        check_counts(&content, &trigrams)?;
        let base_len = content.file_count() as u32;
        Ok(Self {
            base: Segment { content, trigrams },
            delta: None,
            recent: None,
            dead: Vec::new(),
            dead_count: 0,
            tomb: None,
            tomb_delta: None,
            base_len,
            delta_len: 0,
            manifest: None,
        })
    }

    /// The generation of the manifest this snapshot was opened from.
    pub fn generation(&self) -> Option<u64> {
        self.manifest.as_ref().map(|m| m.generation)
    }

    /// The manifest this snapshot was opened from (`None` for a legacy cache).
    pub fn manifest(&self) -> Option<&Manifest> {
        self.manifest.as_ref()
    }

    /// The base segment.
    pub fn base(&self) -> &Segment {
        &self.base
    }

    /// The delta segment, if any.
    pub fn delta(&self) -> Option<&Segment> {
        self.delta.as_ref()
    }

    /// The recent segment, if any.
    pub fn recent(&self) -> Option<&Segment> {
        self.recent.as_ref()
    }

    /// Files in the base (the delta's first id).
    pub fn base_len(&self) -> u32 {
        self.base_len
    }

    /// Files in the delta (the recent segment's first id is `base_len + delta_len`).
    pub fn delta_len(&self) -> u32 {
        self.delta_len
    }

    fn recent_len(&self) -> u32 {
        self.recent
            .as_ref()
            .map_or(0, |d| d.content.file_count() as u32)
    }

    /// The tombstoned base postings' planning sizes.
    pub fn tomb(&self) -> Option<&TombPlan> {
        self.tomb.as_ref()
    }

    /// The tombstoned delta postings' planning sizes.
    pub fn tomb_delta(&self) -> Option<&TombPlan> {
        self.tomb_delta.as_ref()
    }

    /// Whether id `id` (base or delta) is tombstoned.
    #[inline]
    pub fn is_dead(&self, id: u32) -> bool {
        id < self.base_len + self.delta_len
            && self
                .dead
                .get((id / 64) as usize)
                .is_some_and(|w| w & (1u64 << (id % 64)) != 0)
    }

    /// Upper bound of file ids (`0..id_bound()`); some ids below it may be dead.
    pub fn id_bound(&self) -> u32 {
        self.base_len + self.delta_len + self.recent_len()
    }

    /// Number of live files (what a fresh build of the same tree holds).
    pub fn live_file_count(&self) -> usize {
        self.id_bound() as usize - self.dead_count
    }

    /// Whether `id` names a live file.
    pub fn is_live(&self, id: u32) -> bool {
        id < self.id_bound() && !self.is_dead(id)
    }

    /// Every live file id, ascending.
    pub fn live_ids(&self) -> impl Iterator<Item = u32> + '_ {
        (0..self.id_bound()).filter(|&id| !self.is_dead(id))
    }

    /// The segment holding `id`, and the id within it.
    #[inline]
    fn route(&self, id: u32) -> (&Segment, u32) {
        if id < self.base_len {
            return (&self.base, id);
        }
        match (&self.delta, &self.recent) {
            (Some(delta), _) if id < self.base_len + self.delta_len => (delta, id - self.base_len),
            (_, Some(recent)) => (recent, id - self.base_len - self.delta_len),
            _ => (&self.base, id),
        }
    }

    /// Content of a live file.
    pub fn get_file_content(&self, file_id: u32) -> Result<&str> {
        let (segment, local) = self.route(file_id);
        segment.content.get_file_content(local)
    }

    /// Drop the resident pages of every content store (see
    /// [`ContentReader::release_pages`]).
    pub fn release_pages(&self) {
        for segment in [Some(&self.base), self.delta.as_ref(), self.recent.as_ref()]
            .into_iter()
            .flatten()
        {
            segment.content.release_pages();
        }
    }

    /// Length of a file's text, from the entry table (no content page touched).
    pub fn file_len(&self, file_id: u32) -> Option<u64> {
        let (segment, local) = self.route(file_id);
        segment.content.file_len(local)
    }

    /// Path of a live file (`None` for an id that is out of range or dead).
    pub fn get_file_path(&self, file_id: u32) -> Option<&Path> {
        if !self.is_live(file_id) {
            return None;
        }
        let (segment, local) = self.route(file_id);
        segment.content.get_file_path(local)
    }

    /// Lines around `line_number` of a live file.
    pub fn get_context_by_line(
        &self,
        file_id: u32,
        line_number: usize,
        context_lines: usize,
    ) -> Result<(Vec<String>, Vec<String>)> {
        let (segment, local) = self.route(file_id);
        segment
            .content
            .get_context_by_line(local, line_number, context_lines)
    }

    /// Live id of `path` (a leading `./` is ignored), by linear scan. Callers on a
    /// hot path use `OpenIndex::file_id_for`, which caches the map.
    pub fn get_file_id_by_path(&self, path: &str) -> Option<u32> {
        let normalized = path.strip_prefix("./").unwrap_or(path);
        self.live_ids().find(|&id| {
            self.get_file_path(id)
                .and_then(|p| p.to_str())
                .is_some_and(|p| p.strip_prefix("./").unwrap_or(p) == normalized)
        })
    }

    /// Whether candidate lookups can go straight to the base index.
    fn base_alone(&self) -> bool {
        self.delta.is_none() && self.recent.is_none() && self.dead_count == 0
    }

    /// Planning size of `trigram`'s live postings (0: none).
    pub fn live_plan(&self, trigram: Trigram) -> u64 {
        self.list(trigram).map_or(0, |l| l.plan)
    }

    /// `trigram`'s posting list over the base and the delta (tombstones left out)
    /// and the recent segment, with the planning size a full build of the same
    /// tree has.
    fn list(&self, trigram: Trigram) -> Option<TrigramList<'_>> {
        let mut parts: Vec<ListPart<'_>> = Vec::with_capacity(3);
        let mut plan: i64 = 0;
        let dead: Option<&[u64]> = (self.dead_count > 0).then_some(self.dead.as_slice());
        if let Some((mut part, base_plan)) = self.base.trigrams.list_part(trigram) {
            part.dead = dead;
            parts.push(part);
            plan += base_plan as i64;
        }
        for tomb in [&self.tomb, &self.tomb_delta].into_iter().flatten() {
            plan -= tomb.get(trigram) as i64;
        }
        if let Some(delta) = &self.delta
            && let Some((mut part, delta_plan)) = delta.trigrams.list_part(trigram)
        {
            part.id_offset = self.base_len;
            part.dead = dead;
            parts.push(part);
            plan += delta_plan as i64;
        }
        if let Some(recent) = &self.recent
            && let Some((mut part, recent_plan)) = recent.trigrams.list_part(trigram)
        {
            part.id_offset = self.base_len + self.delta_len;
            parts.push(part);
            plan += recent_plan as i64;
        }
        // Every live file block adds at least 2 to the planning size, so 0 means
        // every file holding the trigram is tombstoned: a fresh build has no list.
        if parts.is_empty() || plan <= 0 {
            return None;
        }
        Some(TrigramList {
            trigram,
            plan: plan as u64,
            parts,
        })
    }

    /// Candidate lines for `pattern` (see [`TrigramIndex::search_candidates`]).
    pub fn search_candidates(&self, pattern: &str) -> Vec<FileLocation> {
        if self.base_alone() {
            return self.base.trigrams.search_candidates(pattern);
        }
        let lists = pattern_trigrams(pattern)
            .into_iter()
            .map(|t| self.list(t))
            .collect::<Vec<_>>();
        if lists.is_empty() {
            return vec![];
        }
        plan_intersection(lists, true)
    }

    /// Case-insensitive candidate lines (see [`TrigramIndex::search_candidates_fold`]).
    pub fn search_candidates_fold(&self, literal: &[u8]) -> Vec<FileLocation> {
        if self.base_alone() {
            return self.base.trigrams.search_candidates_fold(literal);
        }
        let Some(windows) = fold_windows(literal) else {
            return vec![];
        };
        let lists = windows
            .iter()
            .map(|variants| variants.iter().filter_map(|&t| self.list(t)).collect())
            .collect();
        plan_fold_intersection(lists)
    }

    /// Lines with a Kelvin sign or long s (see [`TrigramIndex::exotic_fold_lines`]).
    pub fn exotic_fold_lines(&self) -> Vec<FileLocation> {
        if self.base_alone() {
            return self.base.trigrams.exotic_fold_lines();
        }
        let (lo, hi) = EXOTIC_LONG_S_RANGE;
        let mut trigrams: Vec<Trigram> = self
            .base
            .trigrams
            .list_parts_in(lo, hi)
            .into_iter()
            .map(|(t, _, _)| t)
            .collect();
        for segment in [&self.delta, &self.recent].into_iter().flatten() {
            trigrams.extend(
                segment
                    .trigrams
                    .list_parts_in(lo, hi)
                    .into_iter()
                    .map(|(t, _, _)| t),
            );
        }
        trigrams.extend(exotic_singles());
        trigrams.sort_unstable();
        trigrams.dedup();
        let lists: Vec<TrigramList> = trigrams.into_iter().filter_map(|t| self.list(t)).collect();
        union_lists(&lists)
    }

    /// Distinct trigrams in the snapshot's live files.
    pub fn trigram_count(&self) -> usize {
        match &self.manifest {
            Some(m) => m.live_trigrams as usize,
            None => self.base.trigrams.trigram_count(),
        }
    }
}

/// What the published snapshot is made of, for sizes and integrity checks. Every
/// file is counted once (the fixed names are links to the base, not extra bytes).
#[derive(Debug, Clone)]
pub struct StoreSummary {
    /// `content.bin`-format files of the snapshot.
    pub content_files: Vec<PathBuf>,
    /// `trigrams.bin`-format files of the snapshot.
    pub trigram_files: Vec<PathBuf>,
    /// Sidecars of the snapshot (planning sizes).
    pub other_files: Vec<PathBuf>,
    /// Text bytes of the live files, when a manifest records it.
    pub live_corpus_bytes: Option<u64>,
    /// Distinct trigrams of the live files, when a manifest records it.
    pub live_trigrams: Option<u64>,
}

impl StoreSummary {
    /// Every store file of the snapshot.
    pub fn files(&self) -> impl Iterator<Item = &PathBuf> {
        self.content_files
            .iter()
            .chain(&self.trigram_files)
            .chain(&self.other_files)
    }
}

/// The snapshot of `cache_dir` as its manifest names it, or the fixed names
/// without one.
pub fn store_summary(cache_dir: &Path) -> StoreSummary {
    match read_manifest(cache_dir) {
        Ok(Some(m)) => {
            let mut content_files = vec![cache_dir.join(&m.base.content)];
            let mut trigram_files = vec![cache_dir.join(&m.base.trigrams)];
            let mut other_files: Vec<PathBuf> =
                m.base.plan.iter().map(|p| cache_dir.join(p)).collect();
            for d in [&m.delta, &m.recent].into_iter().flatten() {
                content_files.push(cache_dir.join(&d.content));
                trigram_files.push(cache_dir.join(&d.trigrams));
                other_files.extend(d.plan.iter().map(|p| cache_dir.join(p)));
            }
            other_files.extend(m.tomb.iter().map(|t| cache_dir.join(t)));
            other_files.extend(m.tomb_delta.iter().map(|t| cache_dir.join(t)));
            StoreSummary {
                content_files,
                trigram_files,
                other_files,
                live_corpus_bytes: Some(m.live_corpus_bytes),
                live_trigrams: Some(m.live_trigrams),
            }
        }
        _ => StoreSummary {
            content_files: vec![cache_dir.join(FIXED_CONTENT)],
            trigram_files: vec![cache_dir.join(FIXED_TRIGRAMS)],
            other_files: Vec::new(),
            live_corpus_bytes: None,
            live_trigrams: None,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn generation_file_names() {
        assert!(is_generation_file("content.12.bin"));
        assert!(is_generation_file("trigrams.3.bin"));
        assert!(is_generation_file("trigrams.3.plan"));
        assert!(is_generation_file("delta.4.content.bin"));
        assert!(is_generation_file("delta.4.trigrams.bin"));
        assert!(is_generation_file("delta.4.plan"));
        assert!(is_generation_file("delta.4.tomb"));
        assert!(is_generation_file("delta.4.dtomb"));
        assert!(is_generation_file("recent.4.content.bin"));
        assert!(is_generation_file("recent.4.trigrams.bin"));
        assert!(is_generation_file("recent.4.plan"));
        assert!(!is_generation_file("recent.4.tomb"));
        assert!(!is_generation_file("content.3.plan"));
        assert!(!is_generation_file("content.bin"));
        assert!(!is_generation_file("trigrams.bin"));
        assert!(!is_generation_file("content.x.bin"));
        assert!(!is_generation_file("meta.db"));
        assert!(!is_generation_file("manifest.json"));
    }

    #[test]
    fn manifest_round_trip_and_checksum() {
        let temp = tempfile::TempDir::new().unwrap();
        let (content, trigrams, plan) = base_file_names(7);
        let m = Manifest::for_base(
            7,
            SegmentFiles {
                content,
                trigrams,
                plan: Some(plan),
                files: 3,
                content_bytes: 100,
                trigrams_bytes: 200,
            },
            42,
            90,
        );
        write_manifest(temp.path(), &m).unwrap();
        assert_eq!(read_manifest(temp.path()).unwrap(), Some(m));

        // A tampered manifest fails its checksum.
        let path = temp.path().join(MANIFEST);
        let text = std::fs::read_to_string(&path)
            .unwrap()
            .replace("\"generation\": 7", "\"generation\": 8");
        std::fs::write(&path, text).unwrap();
        assert!(read_manifest(temp.path()).is_err());
    }

    #[test]
    fn tomb_file_round_trip() {
        let temp = tempfile::TempDir::new().unwrap();
        let path = temp.path().join("t.tomb");
        write_tomb_file(&path, &[(3, 10), (70_000, 4), (0xE2_84_AA, 7)]).unwrap();
        let tomb = TombPlan::load(&path).unwrap();
        assert_eq!(tomb.get(3), 10);
        assert_eq!(tomb.get(70_000), 4);
        assert_eq!(tomb.get(0xE2_84_AA), 7);
        assert_eq!(tomb.get(4), 0);
        write_tomb_file(&path, &[]).unwrap();
        assert_eq!(TombPlan::load(&path).unwrap().get(3), 0);
    }

    /// A reader that meets a manifest naming a file that is gone (a publish in
    /// between) retries and opens the snapshot the next manifest names; with no
    /// next manifest it reports the cache corrupted.
    #[test]
    fn open_retries_while_a_publish_replaces_the_manifest() {
        let temp = tempfile::TempDir::new().unwrap();
        let root = temp.path();
        write(root, "a.rs", "fn alpha() {}\n");
        index_unlimited(root);
        let cache = root.join(".reflex");
        let good = read_manifest(&cache).unwrap().unwrap();
        let mut files = good.base.clone();
        files.content = "content.999.bin".to_string();
        let broken = Manifest::for_base(
            good.generation + 1,
            files,
            good.live_trigrams,
            good.live_corpus_bytes,
        );

        // The first read sees the manifest a publish is about to replace.
        let mut reads = 0;
        let snapshot = IndexSnapshot::open_reading(&cache, || {
            reads += 1;
            Ok(Some(if reads == 1 {
                broken.clone()
            } else {
                good.clone()
            }))
        })
        .expect("a retry opens the next manifest");
        assert_eq!(reads, 2);
        assert_eq!(snapshot.generation(), Some(good.generation));

        write_manifest(&cache, &broken).unwrap();
        let err = IndexSnapshot::open(&cache).unwrap_err();
        assert!(
            matches!(
                err.downcast_ref::<ReflexError>(),
                Some(ReflexError::CacheCorrupted(_))
            ),
            "{err:#}"
        );
    }

    fn index_unlimited(root: &Path) {
        index_with(root, None);
    }

    fn write(root: &Path, rel: &str, body: &str) {
        let p = root.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, body).unwrap();
    }

    /// Candidate lines of `snapshot` for `pattern`, by path.
    fn candidates(snapshot: &IndexSnapshot, pattern: &str) -> Vec<(PathBuf, u32)> {
        let mut out: Vec<(PathBuf, u32)> = snapshot
            .search_candidates(pattern)
            .into_iter()
            .map(|l| {
                let path = snapshot.get_file_path(l.file_id).expect("a live candidate");
                (path.to_path_buf(), l.line_no)
            })
            .collect();
        out.sort();
        out
    }

    /// Copy the files under `from` into `to`, without `.reflex`.
    fn copy_tree(from: &Path, to: &Path) {
        for entry in std::fs::read_dir(from).unwrap() {
            let entry = entry.unwrap();
            let name = entry.file_name();
            if name == ".reflex" {
                continue;
            }
            let (src, dst) = (entry.path(), to.join(&name));
            if entry.file_type().unwrap().is_dir() {
                std::fs::create_dir_all(&dst).unwrap();
                copy_tree(&src, &dst);
            } else {
                std::fs::copy(&src, &dst).unwrap();
            }
        }
    }

    fn index_with(root: &Path, recent: Option<(usize, u64)>) {
        let mut indexer = crate::Indexer::new(
            crate::CacheManager::new(root),
            crate::models::IndexConfig::default(),
        );
        indexer.set_merge_limits(usize::MAX, u64::MAX);
        if let Some((files, bytes)) = recent {
            indexer.set_recent_limits(files, bytes);
        }
        indexer.index(root, false).unwrap();
    }

    /// Every trigram of the published snapshot has the planning size and presence a
    /// fresh build of the same tree has (so a trigram whose files are all
    /// tombstoned has no list), and so do the live counts and some candidate sets.
    fn assert_plans_as_fresh(root: &Path) {
        let cache = root.join(".reflex");
        let updated = IndexSnapshot::open(&cache).unwrap();
        assert!(!updated.base_alone());
        // The fresh build indexes a copy of the tree: Windows cannot rename a
        // directory whose files are mapped, and `updated` maps `.reflex`.
        let copy = tempfile::TempDir::new().unwrap();
        copy_tree(root, copy.path());
        index_unlimited(copy.path());
        let fresh = IndexSnapshot::open(&copy.path().join(".reflex")).unwrap();
        assert!(fresh.base_alone());

        let mut all: Vec<Trigram> = updated.base().trigrams.trigrams().collect();
        for segment in [updated.delta(), updated.recent()].into_iter().flatten() {
            all.extend(segment.trigrams.trigrams());
        }
        all.extend(fresh.base().trigrams.trigrams());
        all.sort_unstable();
        all.dedup();
        let mut live = 0;
        for t in all {
            let u = updated.list(t).map(|l| l.plan);
            let f = fresh.list(t).map(|l| l.plan);
            assert_eq!(u, f, "planning size of trigram {t:#08x}");
            live += u.is_some() as usize;
        }
        assert_eq!(live, fresh.trigram_count());
        assert_eq!(updated.trigram_count(), fresh.trigram_count());
        assert_eq!(updated.live_file_count(), fresh.live_file_count());
        assert_eq!(
            updated.manifest().unwrap().live_corpus_bytes,
            fresh.manifest().unwrap().live_corpus_bytes
        );

        for pattern in [
            "shared",
            "common_1",
            "rare_marker_qx",
            "edited",
            "brand_new_token",
            "vanishing_zqj",
            "line 1",
        ] {
            assert_eq!(
                candidates(&updated, pattern),
                candidates(&fresh, pattern),
                "{pattern}"
            );
        }
        let fold_paths = |s: &IndexSnapshot| {
            let mut v: Vec<(PathBuf, u32)> = s
                .search_candidates_fold(b"RARE_MARKER")
                .into_iter()
                .map(|l| (s.get_file_path(l.file_id).unwrap().to_path_buf(), l.line_no))
                .collect();
            v.sort();
            v
        };
        assert_eq!(fold_paths(&updated), fold_paths(&fresh));
    }

    /// 200 files, so file-id gaps pass 128 (where planning size and on-disk size
    /// part ways).
    fn seed_tree(root: &Path) {
        for i in 0..200 {
            let rare = if i % 50 == 0 { "rare_marker_qx\n" } else { "" };
            write(
                root,
                &format!("src/f{i:03}.rs"),
                &format!("pub fn common_{i}() {{ shared(); }}\n{rare}// line {i}\n"),
            );
        }
        write(root, "only/gone.rs", "fn vanishing_zqj() {}\n");
    }

    #[test]
    fn a_delta_snapshot_plans_and_answers_as_a_fresh_build() {
        let temp = tempfile::TempDir::new().unwrap();
        let root = temp.path();
        seed_tree(root);
        index_unlimited(root);

        write(root, "src/f000.rs", "pub fn common_0() { edited(); }\n");
        write(
            root,
            "src/f150.rs",
            "pub fn common_150() {}\nrare_marker_qx\n",
        );
        write(
            root,
            "src/new_file.rs",
            "fn brand_new_token() { shared(); }\n",
        );
        std::fs::remove_file(root.join("src/f100.rs")).unwrap();
        std::fs::remove_file(root.join("only/gone.rs")).unwrap();
        index_unlimited(root);
        let updated = IndexSnapshot::open(&root.join(".reflex")).unwrap();
        assert!(candidates(&updated, "vanishing_zqj").is_empty());
        drop(updated);
        assert_plans_as_fresh(root);
    }

    /// The two tiers: the recent segment folds into a new delta past its limit;
    /// delta files are tombstoned while a recent segment is live; a second fold
    /// drops the delta's tombstones.
    #[test]
    fn a_two_tier_snapshot_plans_and_answers_as_a_fresh_build() {
        let temp = tempfile::TempDir::new().unwrap();
        let root = temp.path();
        seed_tree(root);
        index_unlimited(root);
        let recent = Some((2, u64::MAX));
        let manifest = |root: &Path| read_manifest(&root.join(".reflex")).unwrap().unwrap();

        write(root, "src/f000.rs", "pub fn common_0() { edited(); }\n");
        write(root, "src/f001.rs", "pub fn common_1() { edited(); }\n");
        index_with(root, recent);
        let m = manifest(root);
        assert!(m.delta.is_none() && m.recent.as_ref().map(|r| r.files) == Some(2));
        assert_plans_as_fresh(root);

        write(root, "src/f002.rs", "pub fn common_2() { edited(); }\n");
        index_with(root, recent);
        let m = manifest(root);
        assert!(
            m.recent.is_none() && m.delta.as_ref().map(|d| d.files) == Some(3),
            "{m:?}"
        );
        assert_plans_as_fresh(root);

        // f001 now lives in the delta: its new version tombstones a delta id.
        write(
            root,
            "src/f001.rs",
            "pub fn common_1() {}\nrare_marker_qx\n",
        );
        std::fs::remove_file(root.join("only/gone.rs")).unwrap();
        index_with(root, recent);
        let m = manifest(root);
        assert!(
            m.delta.is_some() && m.recent.is_some() && m.tomb_delta.is_some(),
            "{m:?}"
        );
        assert_plans_as_fresh(root);

        write(root, "src/f150.rs", "pub fn common_150() {}\n");
        write(
            root,
            "src/new_file.rs",
            "fn brand_new_token() { shared(); }\n",
        );
        index_with(root, recent);
        let m = manifest(root);
        assert!(m.recent.is_none() && m.tomb_delta.is_none(), "{m:?}");
        assert_eq!(m.delta.as_ref().map(|d| d.files), Some(5));
        assert_plans_as_fresh(root);
    }
}