cpp_code_analysis 0.2.0

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
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
//!
//! The directory this replaces held **1 854 files / 160.6 MB** on a real project: 1 768 summaries (69 MB), 85 `.tu`
//! files (85.6 MB) and a 6 MB `sharing.bin`. Three costs came with that shape, and each is what a database removes:
//!
//! * **1 854 `open`/`read` calls before a single answer** — a cold start's first hundred milliseconds were spent
//!   finding files, not reading them.
//! * **No transactions.** A write interrupted half way left a truncated summary, and the only defence was a magic
//!   header checked on the way in.
//! * **No way to ask who references an entry.** `prune` deleted the oldest files, which is not the same question as
//!   "is this summary still reachable from a file the project has".
//!
//! # What lives here, and what does not
//!
//! ```text
//! meta          schema_version / reading_fingerprint / format_version / generation
//! files         path            -> { content, config, env, mtime, size, generation }
//! projections   content         -> zstd(names a file mentions)      — see the plan's §三之二
//! summaries     (content, config, env) -> zstd(summary bytes)
//! renderings    (content, env)  -> zstd(rendered text)
//! environments  env             -> zstd({name -> body hash})
//! macros        body hash       -> zstd(body)
//! ```
//!
//! `env` is the **projection** hash (the macros a file mentions, transitively), not the whole environment: measured
//! on MSVC's standard library, a header mentions 43–408 macro names where the toolchain defines 9 401, and the
//! definitions it does mention do not change with include order. See the plan for the arithmetic and for the
//! fallback when a projection is larger than 512 names.
//!
//! **The cache is not authoritative.** Every row here is a function of files on disk; a version mismatch deletes the
//! database and the next run rebuilds it. That is the property that makes a single file safe: there is nothing to
//! recover, only something to recompute.

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

use redb::{Database, ReadableDatabase, ReadableTable, ReadableTableMetadata, TableDefinition};

/// The name of the database file inside the cache directory.
pub const DATABASE_FILE: &str = "cache.redb";

/// **What the rows mean, as a number.** A binary whose summaries changed shape bumps this, and the next open
/// deletes the file rather than reading bytes it cannot interpret.
pub const SCHEMA_VERSION: u64 = 1;

/// **How long the cache spent inside the database**, for the question the probes kept asking and could not answer:
/// why the *same* operation on the *same* cache takes 0.8 s in one run and 51 s in the next.
///
/// Every phase inside the analysis measured milliseconds in both runs, so the seconds are either in here or outside
/// the process — and a number that says "the database took 40 s of it" is the difference between the two.
///
/// Two counters, not five: a read is a `begin_read` plus a decompress, a write is a transaction, and the question is
/// which *kind* of traffic the seconds belong to. `reset` is the probe's, because a session's numbers include
/// everything before the operation it cares about.
pub mod io {
    use std::sync::atomic::{AtomicU64, Ordering};

    static READS: AtomicU64 = AtomicU64::new(0);
    static READ_NANOS: AtomicU64 = AtomicU64::new(0);
    static WRITES: AtomicU64 = AtomicU64::new(0);
    static WRITE_NANOS: AtomicU64 = AtomicU64::new(0);

    /// Reads done, nanoseconds spent in them, writes done, nanoseconds spent in them.
    pub fn statistics() -> (u64, u64, u64, u64) {
        (
            READS.load(Ordering::Relaxed),
            READ_NANOS.load(Ordering::Relaxed),
            WRITES.load(Ordering::Relaxed),
            WRITE_NANOS.load(Ordering::Relaxed),
        )
    }

    pub fn reset() {
        for counter in [&READS, &READ_NANOS, &WRITES, &WRITE_NANOS] {
            counter.store(0, Ordering::Relaxed);
        }
    }

    pub(super) fn read_done(elapsed: std::time::Duration) {
        READS.fetch_add(1, Ordering::Relaxed);
        READ_NANOS.fetch_add(elapsed.as_nanos() as u64, Ordering::Relaxed);
    }

    pub(super) fn write_done(elapsed: std::time::Duration) {
        WRITES.fetch_add(1, Ordering::Relaxed);
        WRITE_NANOS.fetch_add(elapsed.as_nanos() as u64, Ordering::Relaxed);
    }
}

/// A scoped timer for one database call — see [`io`].
enum Timed {
    Read(std::time::Instant),
    Write(std::time::Instant),
}

impl Timed {
    fn read() -> Self {
        Timed::Read(std::time::Instant::now())
    }

    fn write() -> Self {
        Timed::Write(std::time::Instant::now())
    }
}

impl Drop for Timed {
    fn drop(&mut self) {
        match self {
            Timed::Read(started) => io::read_done(started.elapsed()),
            Timed::Write(started) => io::write_done(started.elapsed()),
        }
    }
}

const META: TableDefinition<&str, &[u8]> = TableDefinition::new("meta");
const FILES: TableDefinition<&str, &[u8]> = TableDefinition::new("files");
const PROJECTIONS: TableDefinition<u64, &[u8]> = TableDefinition::new("projections");
const SUMMARIES: TableDefinition<(u64, u64, u64), &[u8]> = TableDefinition::new("summaries");
/// **The cooked reading of a file** — the L2 record a warm start serves instead of rebuilding. Keyed like a summary
/// (`(content, config, env)`), because a cooked reading is a summary-shape answer: what the *program* declares of this
/// file, under one compilation context and one macro environment. See `summary_codec::encode_the_cooked_reading`.
const COOKED_READINGS: TableDefinition<(u64, u64, u64), &[u8]> =
    TableDefinition::new("cooked_readings");
const RENDERINGS: TableDefinition<(u64, u64), &[u8]> = TableDefinition::new("renderings");
const ENVIRONMENTS: TableDefinition<u64, &[u8]> = TableDefinition::new("environments");
const MACROS: TableDefinition<u64, &[u8]> = TableDefinition::new("macros");
const UNITS: TableDefinition<u64, &[u8]> = TableDefinition::new("units");
const UNIT_INDICES: TableDefinition<u64, &[u8]> = TableDefinition::new("unit_indices");
/// **Which rendering a root produced last** — `"<context>:<root>"` to the units key.
///
/// The walk that produces that key is **63–70 ms** on the standard library's 256 files, and it is paid by every
/// session. A rendering records the walk's own file list (`RenderedUnit::walked`), so this row lets a caller go from
/// the root — which it has before the closure exists — to the rendering, and validate it against the texts of the files
/// the rendering says it was built from. A stale row is a miss, not a wrong answer.
const UNIT_ROOTS: TableDefinition<&str, u64> = TableDefinition::new("unit_roots");
/// **Where an `#include` resolved**, by the question — see `SummaryStore::include_search_key`.
///
/// A value of the empty string is an answer too: the include resolved nowhere. The key folds the spelling, the form,
/// whether it is a `#include_next`, the directory a quoted include was asked from, the include-path set and the
/// dialect, so a project whose configuration changes asks a different question instead of reading the old answer.
const INCLUDE_SEARCHES: TableDefinition<&str, &str> = TableDefinition::new("include_searches");
/// **What one file contributed to a walk**, keyed by the contribution key the walk computes — see
/// [`crate::index::walk_cache`].
///
/// It used to be a separate `<cache>/sharing.bin`, written whole at shutdown and decoded whole on every start: one
/// file whose failure mode was "the whole sharing cache is lost", and a start that paid for every entry before it
/// could answer anything. A table gives it the atomicity the rest of the cache already has. Measured on the modules
/// fixture: `sharing.bin` was **634 KB** beside a 22 MB database, so the merge is about the failure mode and the
/// startup cost rather than about disk.
const CONTRIBUTIONS: TableDefinition<u64, &[u8]> = TableDefinition::new("contributions");

const KEY_SCHEMA: &str = "schema_version";
const KEY_GENERATION: &str = "generation";
const KEY_FINGERPRINT: &str = "reading_fingerprint";

/// **Everything that decides what a summary contains** — the address of one row.
///
/// The three parts are separate rather than hashed together on purpose: `content` says which text, `config` says
/// which compiler and include directories, and `env` says which macro definitions the text was read with. A miss
/// can then say *which* of the three changed, which is the difference between a cache that can be debugged and one
/// that can only be cleared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CacheKey {
    pub content: u64,
    pub config: u64,
    /// The projection hash — or, for a file whose projection exceeded the threshold, its unit's whole environment.
    pub env: u64,
}

/// One file's row: what it was, and what it was read with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileRow {
    pub content: u64,
    pub config: u64,
    pub env: u64,
    pub mtime: u64,
    pub size: u64,
    pub generation: u64,
}

impl FileRow {
    fn encode(self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(48);
        for value in [
            self.content,
            self.config,
            self.env,
            self.mtime,
            self.size,
            self.generation,
        ] {
            bytes.extend_from_slice(&value.to_le_bytes());
        }
        bytes
    }

    fn decode(bytes: &[u8]) -> Option<FileRow> {
        if bytes.len() < 48 {
            return None;
        }
        let mut values = [0u64; 6];
        for (index, value) in values.iter_mut().enumerate() {
            let at = index * 8;
            *value = u64::from_le_bytes(bytes[at..at + 8].try_into().ok()?);
        }
        Some(FileRow {
            content: values[0],
            config: values[1],
            env: values[2],
            mtime: values[3],
            size: values[4],
            generation: values[5],
        })
    }
}

/// What a garbage collection did — the numbers a probe prints and a test asserts on.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Collected {
    pub summaries: usize,
    pub renderings: usize,
    pub projections: usize,
}

/// What the database holds, for `Session::cache_sizes` and the probes.
#[derive(Debug, Clone, Copy, Default)]
pub struct DatabaseSizes {
    pub files: usize,
    pub summaries: usize,
    pub renderings: usize,
    pub projections: usize,
    pub environments: usize,
    pub macros: usize,
    pub units: usize,
    pub unit_indices: usize,
    /// The sharing cache's rows — see [`CacheDb::put_contributions`].
    pub contributions: usize,
    pub bytes: u64,
}

#[derive(Debug)]
pub enum CacheError {
    Database(redb::Error),
    Table(redb::TableError),
    Storage(redb::StorageError),
    Transaction(redb::TransactionError),
    Commit(redb::CommitError),
    Io(std::io::Error),
    /// The bytes in a row are not what this build wrote — see [`SCHEMA_VERSION`].
    Corrupt(&'static str),
}

impl std::fmt::Display for CacheError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CacheError::Database(error) => write!(formatter, "cache database: {error}"),
            CacheError::Table(error) => write!(formatter, "cache table: {error}"),
            CacheError::Storage(error) => write!(formatter, "cache storage: {error}"),
            CacheError::Transaction(error) => write!(formatter, "cache transaction: {error}"),
            CacheError::Commit(error) => write!(formatter, "cache commit: {error}"),
            CacheError::Io(error) => write!(formatter, "cache io: {error}"),
            CacheError::Corrupt(what) => write!(formatter, "cache row is corrupt: {what}"),
        }
    }
}

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

impl From<redb::DatabaseError> for CacheError {
    fn from(error: redb::DatabaseError) -> Self {
        CacheError::Database(error.into())
    }
}
impl From<redb::Error> for CacheError {
    fn from(error: redb::Error) -> Self {
        CacheError::Database(error)
    }
}
impl From<redb::TableError> for CacheError {
    fn from(error: redb::TableError) -> Self {
        CacheError::Table(error)
    }
}
impl From<redb::StorageError> for CacheError {
    fn from(error: redb::StorageError) -> Self {
        CacheError::Storage(error)
    }
}
impl From<redb::TransactionError> for CacheError {
    fn from(error: redb::TransactionError) -> Self {
        CacheError::Transaction(error)
    }
}
impl From<redb::CommitError> for CacheError {
    fn from(error: redb::CommitError) -> Self {
        CacheError::Commit(error)
    }
}
impl From<std::io::Error> for CacheError {
    fn from(error: std::io::Error) -> Self {
        CacheError::Io(error)
    }
}

type Result<T> = std::result::Result<T, CacheError>;

/// **One embedded database, one open handle, one writer at a time.**
///
/// redb's MVCC is the reason for the shape: a transaction is a scope, readers never wait for the writer, and a
/// `commit` is the only durability point. Every method here opens the transaction it needs and returns, so no lock
/// outlives a call and a query that reads two rows cannot deadlock against a slice that writes one.
pub struct CacheDb {
    database: Database,
    directory: PathBuf,
}

impl CacheDb {
    /// Open (or create) the database in `directory`, deleting it when its version does not match this build.
    ///
    /// The deletion is deliberate and safe: everything here is recomputable from the files on disk, so a schema this
    /// binary cannot read is a schema to throw away rather than migrate. `reading_fingerprint` covers changes to the
    /// *readers* (the summary codec's meaning), which `SCHEMA_VERSION` cannot see because they do not change the
    /// table layout.
    pub fn open(directory: &Path, reading_fingerprint: u64) -> Result<CacheDb> {
        std::fs::create_dir_all(directory)?;
        let path = directory.join(DATABASE_FILE);

        let want_schema = SCHEMA_VERSION.to_le_bytes();
        let want_fingerprint = reading_fingerprint.to_le_bytes();

        let mut database = match Database::create(&path) {
            Ok(database) => database,
            Err(_) => {
                // A file that cannot even be opened as a database is a file to replace.
                let _ = std::fs::remove_file(&path);
                Database::create(&path)?
            }
        };

        let reusable = {
            let read = database.begin_read()?;
            let table = read.open_table(META);
            match table {
                Ok(table) => {
                    let schema = table
                        .get(KEY_SCHEMA)
                        .ok()
                        .flatten()
                        .map(|value| value.value().to_vec());
                    let fingerprint = table
                        .get(KEY_FINGERPRINT)
                        .ok()
                        .flatten()
                        .map(|value| value.value().to_vec());
                    schema.as_deref() == Some(&want_schema[..])
                        && fingerprint.as_deref() == Some(&want_fingerprint[..])
                }
                // A database with no `meta` is new, not broken: the write below creates it.
                Err(redb::TableError::TableDoesNotExist(_)) => true,
                Err(error) => return Err(error.into()),
            }
        };

        if !reusable {
            // Close the handle before deleting: Windows will not unlink an open file.
            drop(database);
            for suffix in ["", "-wal", "-shm"] {
                let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
            }
            database = Database::create(&path)?;
        }

        let write = database.begin_write()?;
        {
            let mut meta = write.open_table(META)?;
            meta.insert(KEY_SCHEMA, &want_schema[..])?;
            meta.insert(KEY_FINGERPRINT, &want_fingerprint[..])?;
            if meta.get(KEY_GENERATION)?.is_none() {
                meta.insert(KEY_GENERATION, &0u64.to_le_bytes()[..])?;
            }
            // Creating the tables up front keeps every later write free of "does it exist yet".
            write.open_table(FILES)?;
            write.open_table(PROJECTIONS)?;
            write.open_table(SUMMARIES)?;
            write.open_table(RENDERINGS)?;
            write.open_table(ENVIRONMENTS)?;
            write.open_table(MACROS)?;
            write.open_table(UNITS)?;
            write.open_table(UNIT_INDICES)?;
            write.open_table(CONTRIBUTIONS)?;
        }
        write.commit()?;

        Ok(CacheDb {
            database,
            directory: directory.to_path_buf(),
        })
    }

    /// Where this database lives, for a log line that says which cache was used.
    pub fn directory(&self) -> &Path {
        &self.directory
    }

    // ---- generations -------------------------------------------------------------------------------

    /// The generation a write belongs to — bumped once per session, so a collection can tell this run's rows from
    /// the previous run's.
    pub fn generation(&self) -> Result<u64> {
        let read = self.database.begin_read()?;
        let meta = read.open_table(META)?;
        Ok(meta
            .get(KEY_GENERATION)?
            .map(|value| {
                let mut bytes = [0u8; 8];
                let value = value.value();
                let length = value.len().min(8);
                bytes[..length].copy_from_slice(&value[..length]);
                u64::from_le_bytes(bytes)
            })
            .unwrap_or(0))
    }

    /// Start a new generation, and answer it. Called once when a session opens its cache.
    pub fn begin_generation(&self) -> Result<u64> {
        let _timed = Timed::write();
        let write = self.database.begin_write()?;
        let next = {
            let mut meta = write.open_table(META)?;
            let current = meta
                .get(KEY_GENERATION)?
                .map(|value| {
                    let mut bytes = [0u8; 8];
                    let value = value.value();
                    let length = value.len().min(8);
                    bytes[..length].copy_from_slice(&value[..length]);
                    u64::from_le_bytes(bytes)
                })
                .unwrap_or(0);
            let next = current + 1;
            meta.insert(KEY_GENERATION, &next.to_le_bytes()[..])?;
            next
        };
        write.commit()?;
        Ok(next)
    }

    // ---- files -------------------------------------------------------------------------------------

    /// Record what a file is, and what it was read with.
    pub fn put_file(&self, path: &Path, row: FileRow) -> Result<()> {
        let _timed = Timed::write();
        let key = normalise(path);
        let write = self.database.begin_write()?;
        {
            let mut files = write.open_table(FILES)?;
            files.insert(&key[..], &row.encode()[..])?;
        }
        write.commit()?;
        Ok(())
    }

    /// What the last run recorded for a file, without opening it.
    pub fn file(&self, path: &Path) -> Result<Option<FileRow>> {
        let _timed = Timed::read();
        let key = normalise(path);
        let read = self.database.begin_read()?;
        let files = read.open_table(FILES)?;
        let Some(value) = files.get(&key[..])? else {
            return Ok(None);
        };
        Ok(FileRow::decode(value.value()))
    }

    // ---- summaries ---------------------------------------------------------------------------------

    /// The summary bytes for a key, decompressed. `None` is a miss, and a miss is never an error.
    pub fn summary(&self, key: CacheKey) -> Result<Option<Vec<u8>>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let summaries = read.open_table(SUMMARIES)?;
        let Some(value) = summaries.get((key.content, key.config, key.env))? else {
            return Ok(None);
        };
        Ok(Some(decompress(value.value())?))
    }

    /// Store a summary. The caller's bytes are compressed here, once, and the write is one transaction.
    pub fn put_summary(&self, key: CacheKey, bytes: &[u8]) -> Result<()> {
        let _timed = Timed::write();
        let packed = compress(bytes);
        let write = self.database.begin_write()?;
        {
            let mut summaries = write.open_table(SUMMARIES)?;
            summaries.insert((key.content, key.config, key.env), &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    /// **Summaries and file rows in one transaction.** The two belong together: a summary no `files` row references
    /// is exactly what a collection deletes, so a batch that wrote only half of the pair would create garbage on
    /// every commit — and a slice writes both.
    pub fn put_rows(
        &self,
        summaries: &[(CacheKey, Vec<u8>)],
        files: &[(String, FileRow)],
    ) -> Result<()> {
        let _timed = Timed::write();
        if summaries.is_empty() && files.is_empty() {
            return Ok(());
        }
        let packed: Vec<((u64, u64, u64), Vec<u8>)> = summaries
            .iter()
            .map(|(key, bytes)| ((key.content, key.config, key.env), compress(bytes)))
            .collect();
        let rows: Vec<(String, Vec<u8>)> = files
            .iter()
            .map(|(path, row)| (normalise(Path::new(path)), row.encode()))
            .collect();

        let write = self.database.begin_write()?;
        {
            let mut table = write.open_table(SUMMARIES)?;
            for (key, bytes) in &packed {
                table.insert(*key, &bytes[..])?;
            }
        }
        {
            let mut table = write.open_table(FILES)?;
            for (path, bytes) in &rows {
                table.insert(&path[..], &bytes[..])?;
            }
        }
        write.commit()?;
        Ok(())
    }

    /// **Write many summaries in one transaction.** Measured on the project's own file cache: 1 768 single-row
    /// writes took **8.2 s** (4.6 ms each, almost all of it transaction overhead), and the same rows written
    /// together take well under a tenth of that. A cold build writes thousands of rows, so this is the shape the
    /// pump should use rather than a nicety.
    pub fn put_summaries(&self, rows: &[(CacheKey, Vec<u8>)]) -> Result<()> {
        let _timed = Timed::write();
        if rows.is_empty() {
            return Ok(());
        }
        let packed: Vec<((u64, u64, u64), Vec<u8>)> = rows
            .iter()
            .map(|(key, bytes)| ((key.content, key.config, key.env), compress(bytes)))
            .collect();
        let write = self.database.begin_write()?;
        {
            let mut summaries = write.open_table(SUMMARIES)?;
            for (key, bytes) in &packed {
                summaries.insert(*key, &bytes[..])?;
            }
        }
        write.commit()?;
        Ok(())
    }

    // ---- renderings --------------------------------------------------------------------------------

    /// The rendered text of a file under one environment — what a translation unit is built from.
    pub fn rendering(&self, content: u64, env: u64) -> Result<Option<String>> {
        let read = self.database.begin_read()?;
        let renderings = read.open_table(RENDERINGS)?;
        let Some(value) = renderings.get((content, env))? else {
            return Ok(None);
        };
        Ok(Some(
            String::from_utf8_lossy(&decompress(value.value())?).into_owned(),
        ))
    }

    /// The cooked reading stored for one key — see [`COOKED_READINGS`].
    pub fn cooked_reading(&self, key: CacheKey) -> Result<Option<Vec<u8>>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let cooked = read.open_table(COOKED_READINGS)?;
        let Some(value) = cooked.get((key.content, key.config, key.env))? else {
            return Ok(None);
        };
        Ok(Some(decompress(value.value())?))
    }

    /// Store a cooked reading. Compressed here, once, like a summary — the two are the same order of bytes.
    pub fn put_cooked_reading(&self, key: CacheKey, bytes: &[u8]) -> Result<()> {
        let _timed = Timed::write();
        let packed = compress(bytes);
        let write = self.database.begin_write()?;
        {
            let mut cooked = write.open_table(COOKED_READINGS)?;
            cooked.insert((key.content, key.config, key.env), &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    pub fn put_rendering(&self, content: u64, env: u64, text: &str) -> Result<()> {
        let packed = compress(text.as_bytes());
        let write = self.database.begin_write()?;
        {
            let mut renderings = write.open_table(RENDERINGS)?;
            renderings.insert((content, env), &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    // ---- projections -------------------------------------------------------------------------------

    /// The macro names a file mentions — the lexical half of the projection, and the half that does not depend on
    /// any environment, so it is stored once per content and reused across every root.
    pub fn projection(&self, content: u64) -> Result<Option<Vec<String>>> {
        let read = self.database.begin_read()?;
        let projections = read.open_table(PROJECTIONS)?;
        let Some(value) = projections.get(content)? else {
            return Ok(None);
        };
        let bytes = decompress(value.value())?;
        Ok(Some(
            bytes
                .split(|byte| *byte == 0)
                .filter(|name| !name.is_empty())
                .map(|name| String::from_utf8_lossy(name).into_owned())
                .collect(),
        ))
    }

    pub fn put_projection(&self, content: u64, names: &[String]) -> Result<()> {
        let mut joined = Vec::new();
        for name in names {
            joined.extend_from_slice(name.as_bytes());
            joined.push(0);
        }
        let packed = compress(&joined);
        let write = self.database.begin_write()?;
        {
            let mut projections = write.open_table(PROJECTIONS)?;
            projections.insert(content, &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    // ---- units -------------------------------------------------------------------------------------

    /// **One translation unit's rendering**, by the key `Session::render_the_unit` computes over the closure — see
    /// [`crate::unit_codec`]. Stored compressed like the rest: the record is about 20 bytes per token of a program,
    /// and a real one is 14 MB before zstd.
    pub fn unit(&self, key: u64) -> Result<Option<crate::RenderedUnit>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let units = read.open_table(UNITS)?;
        let Some(value) = units.get(key)? else {
            return Ok(None);
        };
        let bytes = decompress(value.value())?;
        Ok(crate::unit_codec::decode(&bytes).ok())
    }

    pub fn put_unit(&self, key: u64, unit: &crate::RenderedUnit) -> Result<()> {
        let _timed = Timed::write();
        let packed = compress(&crate::unit_codec::encode(unit));
        let write = self.database.begin_write()?;
        {
            let mut units = write.open_table(UNITS)?;
            write.open_table(UNIT_INDICES)?;
            units.insert(key, &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    /// **Where an `#include` resolved**, by the question — see [`INCLUDE_SEARCHES`].
    pub fn include_search(&self, key: &str) -> Result<Option<String>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let table = read.open_table(INCLUDE_SEARCHES)?;
        Ok(table.get(key)?.map(|value| value.value().to_string()))
    }

    pub fn put_include_search(&self, key: &str, answer: &str) -> Result<()> {
        let _timed = Timed::write();
        let write = self.database.begin_write()?;
        {
            let mut table = write.open_table(INCLUDE_SEARCHES)?;
            table.insert(key, answer)?;
        }
        write.commit()?;
        Ok(())
    }

    /// **Which rendering this root produced last** — see [`UNIT_ROOTS`].
    pub fn unit_root(&self, root: &str) -> Result<Option<u64>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let table = read.open_table(UNIT_ROOTS)?;
        Ok(table.get(root)?.map(|value| value.value()))
    }

    pub fn put_unit_root(&self, root: &str, units_key: u64) -> Result<()> {
        let _timed = Timed::write();
        let write = self.database.begin_write()?;
        {
            let mut table = write.open_table(UNIT_ROOTS)?;
            table.insert(root, units_key)?;
        }
        write.commit()?;
        Ok(())
    }

    /// **A unit's facts**, by the hash of the rendering they were read from — see
    /// [`crate::unit_codec::encode_indexed_unit`].
    ///
    /// This is the half of a unit read that costs the most (the sweep is ≈3.8 s of a 4.4 s read) and the half that is
    /// a pure function of the text, so it is the one worth keeping.
    pub fn indexed_unit(&self, program: u64) -> Result<Option<crate::IndexedUnit>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let table = read.open_table(UNIT_INDICES)?;
        let Some(value) = table.get(program)? else {
            return Ok(None);
        };
        let bytes = decompress(value.value())?;
        Ok(crate::unit_codec::decode_indexed_unit(&bytes).ok())
    }

    pub fn put_indexed_unit(&self, program: u64, unit: &crate::IndexedUnit) -> Result<()> {
        let _timed = Timed::write();
        let packed = compress(&crate::unit_codec::encode_indexed_unit(unit));
        let write = self.database.begin_write()?;
        {
            let mut table = write.open_table(UNIT_INDICES)?;
            table.insert(program, &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    // ---- contributions -----------------------------------------------------------------------------

    /// **Every walk contribution, in one transaction** — the sharing cache, in the database rather than in a
    /// `sharing.bin` beside it.
    ///
    /// The bytes are [`crate::index::walk_cache_codec::encode`]'s, so this table has no opinion about their shape: a
    /// contribution that cannot be decoded is a miss, which is the same rule the summaries follow.
    pub fn put_contributions(&self, entries: &[(u64, Vec<u8>)]) -> Result<usize> {
        let _timed = Timed::write();
        let write = self.database.begin_write()?;
        let written;
        {
            let mut table = write.open_table(CONTRIBUTIONS)?;
            for (key, bytes) in entries {
                table.insert(*key, &bytes[..])?;
            }
            written = entries.len();
        }
        write.commit()?;
        Ok(written)
    }

    /// What the previous run left. `Ok(vec![])` is a cold start, not an error — the walk is correct without it.
    pub fn contributions(&self) -> Result<Vec<(u64, Vec<u8>)>> {
        let _timed = Timed::read();
        let read = self.database.begin_read()?;
        let table = read.open_table(CONTRIBUTIONS)?;
        let mut entries: Vec<(u64, Vec<u8>)> = Vec::new();
        for entry in table.iter()? {
            let (key, value) = entry?;
            entries.push((key.value(), value.value().to_vec()));
        }
        Ok(entries)
    }

    /// How many contributions the table holds, for a cache report.
    pub fn contribution_count(&self) -> usize {
        let count = || -> Result<usize> {
            let read = self.database.begin_read()?;
            let table = read.open_table(CONTRIBUTIONS)?;
            Ok(table.len()? as usize)
        };
        count().unwrap_or(0)
    }

    // ---- environments and macros -------------------------------------------------------------------

    pub fn put_environment(&self, env: u64, bytes: &[u8]) -> Result<()> {
        let packed = compress(bytes);
        let write = self.database.begin_write()?;
        {
            let mut environments = write.open_table(ENVIRONMENTS)?;
            environments.insert(env, &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    pub fn put_macro(&self, body_hash: u64, body: &str) -> Result<()> {
        let packed = compress(body.as_bytes());
        let write = self.database.begin_write()?;
        {
            let mut macros = write.open_table(MACROS)?;
            write.open_table(UNITS)?;
            write.open_table(UNIT_INDICES)?;
            macros.insert(body_hash, &packed[..])?;
        }
        write.commit()?;
        Ok(())
    }

    // ---- collection --------------------------------------------------------------------------------

    /// **Delete what no file row references.** The question the directory tree could not answer: a summary is worth
    /// keeping exactly when some file still says it was read that way.
    ///
    /// Rows are gathered first and deleted after, because redb will not let a table be mutated while it is being
    /// iterated — and because a delete set built from a consistent snapshot is the only one whose counts a test can
    /// assert on.
    pub fn collect(&self) -> Result<Collected> {
        let (live_summaries, live_contents) = {
            let read = self.database.begin_read()?;
            let files = read.open_table(FILES)?;
            // **Live by (content, config), not by the environment.** A file has more than one reading now — the
            // unrefined one from indexing and the refined one the second pass stored — and both are readings of the
            // same `(content, config)`. The exact-triple set deleted whichever of the two the file row did not name:
            // measured as the two ways the refinement cache failed, `not stored` when the row kept `env: 0` and `Built`
            // when it kept the fingerprint.
            let mut summaries: HashSet<(u64, u64)> = HashSet::new();
            let mut contents: HashSet<u64> = HashSet::new();
            for entry in files.iter()? {
                let (_, value) = entry?;
                let Some(row) = FileRow::decode(value.value()) else {
                    continue;
                };
                summaries.insert((row.content, row.config));
                contents.insert(row.content);
            }
            (summaries, contents)
        };

        // **Nothing referenced means nothing to collect.** The first run has no `files` rows yet — the store
        // writes summaries before it records what they belong to — and a collection that read that as "every
        // summary is garbage" would empty a database that had just been filled. A collection is only meaningful
        // once some file says what it is, and this is the guard that makes the difference a rule rather than an
        // accident of ordering.
        if live_summaries.is_empty() && live_contents.is_empty() {
            return Ok(Collected::default());
        }

        let mut collected = Collected::default();
        let write = self.database.begin_write()?;
        {
            let mut summaries = write.open_table(SUMMARIES)?;
            let dead: Vec<(u64, u64, u64)> = summaries
                .iter()?
                .filter_map(|entry| entry.ok().map(|(key, _)| key.value()))
                .filter(|key| !live_summaries.contains(&(key.0, key.1)))
                .collect();
            for key in dead {
                summaries.remove(key)?;
                collected.summaries += 1;
            }
        }
        {
            let mut renderings = write.open_table(RENDERINGS)?;
            let dead: Vec<(u64, u64)> = renderings
                .iter()?
                .filter_map(|entry| entry.ok().map(|(key, _)| key.value()))
                .filter(|key| !live_contents.contains(&key.0))
                .collect();
            for key in dead {
                renderings.remove(key)?;
                collected.renderings += 1;
            }
        }
        {
            let mut projections = write.open_table(PROJECTIONS)?;
            let dead: Vec<u64> = projections
                .iter()?
                .filter_map(|entry| entry.ok().map(|(key, _)| key.value()))
                .filter(|key| !live_contents.contains(key))
                .collect();
            for key in dead {
                projections.remove(key)?;
                collected.projections += 1;
            }
        }
        write.commit()?;
        Ok(collected)
    }

    /// **Give the bytes back to the filesystem.** redb does not shrink its file when rows are deleted — measured, a
    /// collection left the database **larger** than before it (16.6 MB → 24.6 MB). Compaction rewrites the live
    /// pages, so it belongs to the idle step next to [`CacheDb::collect`], never to a query.
    pub fn compact(&mut self) -> Result<bool> {
        self.database
            .compact()
            .map_err(|error| CacheError::Io(std::io::Error::other(error)))
    }

    /// How many rows each table holds, and how large the file is — the numbers a probe prints.
    pub fn sizes(&self) -> Result<DatabaseSizes> {
        let read = self.database.begin_read()?;
        let count = |length: usize| length;
        Ok(DatabaseSizes {
            files: count(read.open_table(FILES)?.len()? as usize),
            summaries: count(read.open_table(SUMMARIES)?.len()? as usize),
            renderings: count(read.open_table(RENDERINGS)?.len()? as usize),
            projections: count(read.open_table(PROJECTIONS)?.len()? as usize),
            environments: count(read.open_table(ENVIRONMENTS)?.len()? as usize),
            macros: count(read.open_table(MACROS)?.len()? as usize),
            units: count(read.open_table(UNITS)?.len()? as usize),
            unit_indices: count(read.open_table(UNIT_INDICES)?.len()? as usize),
            contributions: count(read.open_table(CONTRIBUTIONS)?.len()? as usize),
            bytes: std::fs::metadata(self.directory.join(DATABASE_FILE))
                .map(|metadata| metadata.len())
                .unwrap_or(0),
        })
    }
}

/// **The summary cache as the store uses it**: a database, plus the batch a slice is still holding.
///
/// The batch is the reason this type exists at all. Measured on the project's own 1 768 summaries: one transaction
/// per row cost **8.2 s**, and the same rows in one transaction **0.97 s** — so a caller writing a slice's worth of
/// summaries must not be handed a per-row `put`. The buffer flushes when it is full and when the store says so
/// (`Session` does, at the end of a slice), and a half-full buffer loses nothing that is not recomputable.
///
/// # One handle per directory, process-wide
///
/// A database file has one writer, and a process that opened it twice would be two writers of the same rows with two
/// buffers — a summary written by one store would be invisible to the other until either flushed. Measured as seven
/// failing tests, each of the shape "write with one store, read with the next". [`shared`] is the answer: the second
/// caller gets the same handle, and therefore the same batch.
pub struct SummaryCache {
    database: CacheDb,
    pending: std::sync::Mutex<(Vec<(CacheKey, Vec<u8>)>, Vec<(String, FileRow)>)>,
}

/// How many rows one transaction takes — the wave sizes this store writes in are 8–32, and the measured cost of a
/// commit at that size is noise next to the parse it follows.
const BATCH: usize = 32;

/// **The handles this process holds, by directory.** See the note on [`SummaryCache`]: two stores over one cache must
/// be one writer, or a summary written through one is invisible to the other until a flush that may never come.
fn open_handles()
-> &'static std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<SummaryCache>>> {
    static HANDLES: std::sync::OnceLock<
        std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<SummaryCache>>>,
    > = std::sync::OnceLock::new();
    HANDLES.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

/// **The one handle for a cache directory**, opened on first use. `None` when it cannot be opened — the file cache is
/// still there, so a cache that cannot open is not a session that cannot start.
pub fn shared(directory: &Path, reading_fingerprint: u64) -> Option<std::sync::Arc<SummaryCache>> {
    // **Lexically, not canonically**: the first caller may be holding a directory that does not exist yet, so
    // `canonicalize` would fail for it and succeed for the next caller — which is exactly the two-handles bug this
    // function exists to prevent (measured as twenty failing tests, each asking the same question with two stores).
    let key = directory.to_string_lossy().to_lowercase();
    let Ok(mut handles) = open_handles().lock() else {
        return None;
    };
    if let Some(handle) = handles.get(key.as_str()) {
        return Some(std::sync::Arc::clone(handle));
    }
    let opened = std::sync::Arc::new(SummaryCache::open(directory, reading_fingerprint)?);
    handles.insert(key, std::sync::Arc::clone(&opened));
    Some(opened)
}

impl SummaryCache {
    /// Open the database next to the file cache it replaces, and answer `None` when it cannot be opened — the file
    /// cache is still there, so a cache that cannot open is not a session that cannot start.
    pub fn open(directory: &Path, reading_fingerprint: u64) -> Option<SummaryCache> {
        match CacheDb::open(directory, reading_fingerprint) {
            Ok(database) => Some(SummaryCache {
                database,
                pending: std::sync::Mutex::new((Vec::new(), Vec::new())),
            }),
            Err(error) => {
                log::warn!("the summary database could not be opened: {error}");
                None
            }
        }
    }

    /// **The cooked reading for a key**, decoded — see `CacheDb::cooked_reading`.
    ///
    /// A miss is `None` and never an error: a parent that stored the refinement before this table existed has a
    /// summary and no cooked reading, which is a file the pass rebuilds (`SummaryStore::take_the_stored_refinements`).
    pub fn cooked_reading(&self, key: CacheKey) -> Option<Vec<u8>> {
        self.database.cooked_reading(key).ok().flatten()
    }

    /// **Write a cooked reading.** Through the database directly, unlike summaries: a cooked reading is written once
    /// per refinement and read by the *next* start, so the in-process buffer the summaries need has nothing to add.
    pub fn put_cooked_reading(&self, key: CacheKey, bytes: &[u8]) {
        if let Err(error) = self.database.put_cooked_reading(key, bytes) {
            log::debug!("a cooked reading was not stored: {error}");
        }
    }

    /// The summary for a key, decoded. A miss is `None` and never an error.
    ///
    /// **The batch is read before the database**, because a summary that has been written but not yet committed is
    /// still a summary this process must answer with: a query for a file the pump has just read would otherwise
    /// re-parse it — and the store's own tests are exactly that question asked with two stores, where the answer was
    /// twenty failures until the buffer became readable.
    pub fn summary(&self, key: crate::cache::SummaryKey) -> Option<crate::FileSummary> {
        // **The environment is part of the key, and it was not.** A reading refined under one environment and one
        // taken from the file's own text are two different answers (`_STD` is `::std::` under one and a plain name
        // under the other); with `env: 0` the second overwrote the first, which is why the second pass could not store
        // what it built. `SummaryKey::env_hash` is 0 exactly when a reading claims no environment.
        let cache_key = CacheKey {
            content: key.content_hash,
            config: key.context_hash,
            env: key.env_hash,
        };
        let buffered = self.pending.lock().ok().and_then(|pending| {
            pending
                .0
                .iter()
                .rev()
                .find(|(held, _)| *held == cache_key)
                .map(|(_, bytes)| bytes.clone())
        });
        let bytes = match buffered {
            Some(bytes) => bytes,
            None => self.database.summary(cache_key).ok().flatten()?,
        };
        match crate::summary_codec::decode(&bytes) {
            Ok(summary) => Some(summary),
            Err(error) => {
                log::debug!("a stored summary could not be decoded: {error}");
                None
            }
        }
    }

    /// Buffer a summary, and commit the batch when it is full.
    pub fn put(&self, key: crate::cache::SummaryKey, summary: &crate::FileSummary) {
        let bytes = crate::summary_codec::encode(summary);
        let cache_key = CacheKey {
            content: key.content_hash,
            config: key.context_hash,
            env: key.env_hash,
        };
        let Ok(mut pending) = self.pending.lock() else {
            return;
        };
        pending.0.push((cache_key, bytes));
        if pending.0.len() >= BATCH {
            flush(&self.database, &mut pending);
        }
    }

    /// **Record what a file is**, so a collection can ask whether a summary is still reachable — and so a later
    /// start can compare `content` without reading the file.
    pub fn note_file(&self, path: &Path, content: u64, config: u64, env: u64, generation: u64) {
        let (mtime, size) = std::fs::metadata(path)
            .map(|metadata| {
                let mtime = metadata
                    .modified()
                    .ok()
                    .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|since| since.as_millis() as u64)
                    .unwrap_or(0);
                (mtime, metadata.len())
            })
            .unwrap_or((0, 0));
        let row = FileRow {
            content,
            config,
            env,
            mtime,
            size,
            generation,
        };
        let Ok(mut pending) = self.pending.lock() else {
            return;
        };
        pending.1.push((path.to_string_lossy().to_string(), row));
        if pending.0.len() + pending.1.len() >= BATCH {
            flush(&self.database, &mut pending);
        }
    }

    /// Commit whatever the buffer holds — the end of a slice.
    pub fn flush(&self) {
        if let Ok(mut pending) = self.pending.lock() {
            flush(&self.database, &mut pending);
        }
    }

    /// **Drop the rows nothing references**, after committing the batch — the idle step.
    ///
    /// Reading nothing into memory and taking no exclusive ownership: `collect` is a write transaction like any
    /// other, so it runs beside a reader. Compaction is a different matter and stays off this path — it rewrites the
    /// file and needs `&mut`, which a handle shared through [`shared`] cannot promise.
    pub fn collect(&self) -> Option<Collected> {
        self.flush();
        self.database.collect().ok()
    }

    /// **A unit rendering, by its closure key** — see [`CacheDb::unit`].
    pub fn unit(&self, key: u64) -> Result<Option<crate::RenderedUnit>> {
        self.database.unit(key)
    }

    /// Where this database lives — the directory its rows are in, for a caller that has to tell one project's cache
    /// from another's.
    pub fn directory(&self) -> &Path {
        self.database.directory()
    }

    /// **The sharing cache, in the database** — see [`CacheDb::put_contributions`].
    ///
    /// It was a `sharing.bin` beside the database until the merge: one file, decoded whole on every start, and lost
    /// whole if it was interrupted. Rows in a table get the atomicity the summaries already had.
    pub fn put_contributions(&self, entries: &[(u64, Vec<u8>)]) -> Result<usize> {
        self.database.put_contributions(entries)
    }

    /// What the previous run left — see [`CacheDb::contributions`].
    pub fn contributions(&self) -> Result<Vec<(u64, Vec<u8>)>> {
        self.database.contributions()
    }

    pub fn put_unit(&self, key: u64, unit: &crate::RenderedUnit) -> Result<()> {
        self.database.put_unit(key, unit)
    }

    /// **A unit's facts, by its program hash** — see [`CacheDb::indexed_unit`].
    pub fn indexed_unit(&self, program: u64) -> Result<Option<crate::IndexedUnit>> {
        self.database.indexed_unit(program)
    }

    pub fn put_indexed_unit(&self, program: u64, unit: &crate::IndexedUnit) -> Result<()> {
        self.database.put_indexed_unit(program, unit)
    }

    /// Start a new generation, and answer it — see [`CacheDb::begin_generation`].
    pub fn begin_generation(&self) -> Result<u64> {
        self.database.begin_generation()
    }

    /// **Where an `#include` resolved**, by the question — see [`INCLUDE_SEARCHES`].
    pub fn include_search(&self, key: &str) -> Result<Option<String>> {
        self.database.include_search(key)
    }

    pub fn put_include_search(&self, key: &str, answer: &str) -> Result<()> {
        self.database.put_include_search(key, answer)
    }

    /// **Collect and compact** — the idle step: both rewrite the file, so neither belongs to a query.
    pub fn collect_and_compact(&mut self) -> Option<(Collected, bool)> {
        let collected = self.database.collect().ok()?;
        let compacted = self.database.compact().ok()?;
        Some((collected, compacted))
    }

    /// **Which rendering this root produced last** — see [`UNIT_ROOTS`].
    pub fn unit_root(&self, root: &str) -> Result<Option<u64>> {
        self.database.unit_root(root)
    }

    pub fn put_unit_root(&self, root: &str, units_key: u64) -> Result<()> {
        self.database.put_unit_root(root, units_key)
    }

    /// Rows and bytes, for the probes.
    pub fn sizes(&self) -> Option<DatabaseSizes> {
        self.database.sizes().ok()
    }
}

/// **A batch is flushed when the handle goes away.** A store that wrote a summary and was then dropped would
/// otherwise lose it, and a cache whose last writes are lost re-parses them on the next start — the cost it exists
/// to avoid. The pump still flushes at the end of a slice, so this is the backstop rather than the mechanism.
impl Drop for SummaryCache {
    fn drop(&mut self) {
        self.flush();
    }
}

fn flush(database: &CacheDb, pending: &mut (Vec<(CacheKey, Vec<u8>)>, Vec<(String, FileRow)>)) {
    if pending.0.is_empty() && pending.1.is_empty() {
        return;
    }
    let (summaries, files) = std::mem::take(pending);
    if let Err(error) = database.put_rows(&summaries, &files) {
        log::warn!("a batch of summaries could not be written: {error}");
    }
}

/// redb keys are byte strings, so a path is stored as its lossy UTF-8 — the same choice the VFS makes when it
/// normalises, which is what keeps the two spellings of a Windows path from becoming two rows.
fn normalise(path: &Path) -> String {
    path.to_string_lossy().to_lowercase()
}

fn compress(bytes: &[u8]) -> Vec<u8> {
    zstd::encode_all(bytes, 3).unwrap_or_else(|_| bytes.to_vec())
}

fn decompress(bytes: &[u8]) -> Result<Vec<u8>> {
    zstd::decode_all(bytes).map_err(|_| CacheError::Corrupt("zstd frame"))
}

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

    fn scratch(name: &str) -> PathBuf {
        let directory =
            std::env::temp_dir().join(format!("cppls-cache-db-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&directory);
        directory
    }

    fn row(content: u64, env: u64, generation: u64) -> FileRow {
        FileRow {
            content,
            config: 7,
            env,
            mtime: 1,
            size: 2,
            generation,
        }
    }

    /// **A summary goes in and comes out, compressed** — and the same key twice is one row.
    #[test]
    fn a_summary_survives_a_round_trip() {
        let directory = scratch("round-trip");
        let database = CacheDb::open(&directory, 42).expect("opens");
        let key = CacheKey {
            content: 1,
            config: 2,
            env: 3,
        };
        let body = vec![b'x'; 4_096];

        assert!(
            database.summary(key).unwrap().is_none(),
            "a miss is not an error"
        );
        database.put_summary(key, &body).unwrap();
        assert_eq!(database.summary(key).unwrap().unwrap(), body);

        let sizes = database.sizes().unwrap();
        assert_eq!(sizes.summaries, 1);
        assert!(sizes.bytes > 0);

        drop(database);
        let _ = std::fs::remove_dir_all(&directory);
    }

    /// **A summary no file references is collected; one a file does reference is kept.**
    #[test]
    fn collection_keeps_what_a_file_references() {
        let directory = scratch("collection");
        let database = CacheDb::open(&directory, 42).expect("opens");
        let live = CacheKey {
            content: 10,
            config: 7,
            env: 20,
        };
        let dead = CacheKey {
            content: 11,
            config: 7,
            env: 20,
        };
        database.put_summary(live, b"live").unwrap();
        database.put_summary(dead, b"dead").unwrap();
        database
            .put_rendering(live.content, live.env, "int x;")
            .unwrap();
        database
            .put_rendering(dead.content, dead.env, "int y;")
            .unwrap();
        database
            .put_projection(live.content, &["_STD".to_string()])
            .unwrap();
        database
            .put_projection(dead.content, &["_HAS_CXX20".to_string()])
            .unwrap();
        database
            .put_file(Path::new("C:/p/live.cpp"), row(live.content, live.env, 1))
            .unwrap();

        let collected = database.collect().unwrap();
        assert_eq!(collected.summaries, 1, "the unreferenced summary is gone");
        assert_eq!(
            collected.renderings, 1,
            "and so is the unreferenced rendering"
        );
        assert_eq!(collected.projections, 1, "and the unreferenced projection");
        assert!(
            database.summary(live).unwrap().is_some(),
            "the referenced one stays"
        );
        assert!(database.summary(dead).unwrap().is_none());

        drop(database);
        let _ = std::fs::remove_dir_all(&directory);
    }

    /// **A batch of summaries is one transaction, and compaction returns the bytes of a collection.**
    ///
    /// Both are shapes rather than niceties: 1 768 single-row writes measured **8.2 s** against **0.97 s** for the
    /// batch, and a collection without compaction left the file *larger* than it started (16.6 → 24.6 MB).
    #[test]
    fn a_batch_is_one_transaction_and_compaction_shrinks() {
        let directory = scratch("batch");
        let mut database = CacheDb::open(&directory, 42).expect("opens");

        let rows: Vec<(CacheKey, Vec<u8>)> = (0..256u64)
            .map(|index| {
                (
                    CacheKey {
                        content: index,
                        config: 1,
                        env: 2,
                    },
                    vec![b'a'; 4_096],
                )
            })
            .collect();
        database.put_summaries(&rows).unwrap();
        // One file row, so the collection below means something: with no rows at all the database is new rather than
        // garbage, and `collect` deliberately does nothing.
        database
            .put_file(
                Path::new("C:/p/wanted.cpp"),
                FileRow {
                    content: 0,
                    config: 1,
                    env: 2,
                    mtime: 1,
                    size: 1,
                    generation: 1,
                },
            )
            .unwrap();
        assert_eq!(database.sizes().unwrap().summaries, 256);
        assert_eq!(database.summary(rows[7].0).unwrap().unwrap(), rows[7].1);

        // Nothing references them, so a collection drops the lot — and compaction is what gives the file back.
        let collected = database.collect().unwrap();
        assert_eq!(
            collected.summaries, 255,
            "every summary but the referenced one"
        );
        assert_eq!(
            database.sizes().unwrap().summaries,
            1,
            "the one a file references stays"
        );
        let before = database.sizes().unwrap().bytes;
        assert!(database.compact().unwrap());
        let after = database.sizes().unwrap().bytes;
        assert!(
            after < before,
            "compaction must shrink: {before} -> {after}"
        );

        drop(database);
        let _ = std::fs::remove_dir_all(&directory);
    }

    /// **A database written by another schema is deleted, not read.** The cache is recomputable, so the only honest
    /// answer to bytes this build cannot interpret is to throw them away.
    #[test]
    fn a_foreign_schema_is_replaced() {
        let directory = scratch("schema");
        let database = CacheDb::open(&directory, 1).expect("opens");
        database
            .put_summary(
                CacheKey {
                    content: 5,
                    config: 5,
                    env: 5,
                },
                b"body",
            )
            .unwrap();
        drop(database);

        let reopened = CacheDb::open(&directory, 2).expect("reopens");
        assert!(
            reopened
                .summary(CacheKey {
                    content: 5,
                    config: 5,
                    env: 5
                })
                .unwrap()
                .is_none(),
            "a different fingerprint is a different database"
        );
        assert_eq!(reopened.generation().unwrap(), 0, "and a fresh generation");

        drop(reopened);
        let _ = std::fs::remove_dir_all(&directory);
    }

    /// **A generation is bumped once per session**, and the row a write records carries it.
    #[test]
    fn a_generation_is_bumped_once() {
        let directory = scratch("generation");
        let database = CacheDb::open(&directory, 42).expect("opens");
        assert_eq!(database.generation().unwrap(), 0);
        assert_eq!(database.begin_generation().unwrap(), 1);
        assert_eq!(database.generation().unwrap(), 1);
        assert_eq!(database.begin_generation().unwrap(), 2);

        database
            .put_file(
                Path::new("C:/p/a.cpp"),
                row(1, 2, database.generation().unwrap()),
            )
            .unwrap();
        assert_eq!(
            database
                .file(Path::new("c:/P/A.CPP"))
                .unwrap()
                .unwrap()
                .generation,
            2
        );

        drop(database);
        let _ = std::fs::remove_dir_all(&directory);
    }
}