inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
//! Persistent spill files, startup recovery, and bounded SSD eviction.

use super::*;

// ---------------------------------------------------------------------------
// On-disk checksummed block store (SpillStore)
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, Debug)]
struct DiskEntry {
    bytes: u64,
    lru_seq: u64,
}

/// Statistics tracked by [`SpillStore`].
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct SpillStoreStats {
    pub writes_committed: u64,
    pub bytes_written: u64,
    pub write_us_total: u64,
    pub reads_hit: u64,
    pub reads_miss: u64,
    pub bytes_read: u64,
    pub read_us_total: u64,
    pub corrupt_files_removed: u64,
    pub disk_gc_evictions: u64,
    pub over_budget_drops: u64,
    pub orphans_swept: u64,
}

/// RAII wrapper around the exclusive `flock(LOCK_EX | LOCK_NB)` directory descriptor.
/// Holding this guard in its own field (rather than implementing `Drop` on [`SpillStore`])
/// lets [`SpillStore::open_or_rotate_stale_at`] and [`SpillStore::verify_or_rotate_kv4_digest`]
/// move the live locked descriptor across `fs::rename` without any unlock-to-rename race window.
struct LockedDirGuard(File);

impl Drop for LockedDirGuard {
    fn drop(&mut self) {
        // Release immediately even if a concurrent fork briefly inherited the descriptor.
        let _ = self.0.unlock();
    }
}

enum OpenLockedOutcome {
    Opened(Box<SpillStore>),
    ModeMismatch {
        locked_dir: LockedDirGuard,
        expected: u32,
        found: u32,
    },
}

/// Crash-safe, bounded, checksummed SSD directory store (`--spill-dir`).
pub struct SpillStore {
    // Keeping the locked directory open gives its index, writers, and GC a single owner.
    directory_lock: LockedDirGuard,
    last_allocated_id: u64,
    dir: PathBuf,
    max_bytes: u64,
    used_bytes: u64,
    lru_clock: u64,
    kvb: u32,
    entries: HashMap<SpillKey, DiskEntry>,
    /// Bytes admitted by [`SpillStore::reserve_write`] for writes that have not landed yet. A reserved key is
    /// not in `entries` (it cannot be read, reused or evicted) until [`SpillStore::apply_raw_write`] commits it.
    reserved: HashMap<SpillKey, u64>,
    reserved_bytes: u64,
    stats: SpillStoreStats,
}

fn enable_nocache(file: &File) {
    #[cfg(target_os = "macos")]
    {
        use std::os::fd::AsRawFd;
        unsafe {
            libc::fcntl(file.as_raw_fd(), libc::F_NOCACHE, 1);
        }
    }
    #[cfg(not(target_os = "macos"))]
    {
        let _ = file;
    }
}

fn fsync_dir(dir: &Path) -> io::Result<()> {
    let f = File::open(dir)?;
    f.sync_all()
}

fn unlink_if_present(path: &Path) -> io::Result<bool> {
    match fs::remove_file(path) {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e),
    }
}

fn pread_exact(file: &File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
    #[cfg(unix)]
    {
        while !buf.is_empty() {
            let n = file.read_at(buf, offset)?;
            if n == 0 {
                return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "unexpected EOF in pread"));
            }
            buf = &mut buf[n..];
            offset = offset.checked_add(n as u64).ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "pread offset overflow")
            })?;
        }
        Ok(())
    }
    #[cfg(not(unix))]
    {
        use std::io::{Read, Seek, SeekFrom};
        let mut f = file;
        f.seek(SeekFrom::Start(offset))?;
        f.read_exact(buf)
    }
}

fn encode_header(
    key: SpillKey,
    kvb: u32,
    generation: u64,
    kv_bytes: &[u8],
    recurrent_state: Option<&[u8]>,
) -> [u8; SPILL_HEADER_LEN] {
    let state_slice = recurrent_state.unwrap_or(&[]);
    let mut header = [0u8; SPILL_HEADER_LEN];
    header[0..8].copy_from_slice(&SPILL_MAGIC);
    header[8..12].copy_from_slice(&SPILL_FORMAT_VERSION.to_le_bytes());
    header[12..14].copy_from_slice(&(key.kind as u16).to_le_bytes());
    header[14..16].copy_from_slice(&(kvb as u16).to_le_bytes());
    header[16..24].copy_from_slice(&key.id.to_le_bytes());
    header[24..32].copy_from_slice(&generation.to_le_bytes());
    header[32..40].copy_from_slice(&(kv_bytes.len() as u64).to_le_bytes());
    header[40..48].copy_from_slice(&(state_slice.len() as u64).to_le_bytes());

    let mut hasher = Sha256::new();
    hasher.update(&header[0..HEADER_PREFIX_LEN]);
    hasher.update(kv_bytes);
    if !state_slice.is_empty() {
        hasher.update(state_slice);
    }
    let digest = hasher.finalize();
    header[48..80].copy_from_slice(&digest);
    header
}

/// Receipt returned when [`SpillStore::open_or_rotate_stale`] moves an incompatible derived
/// `--spill-dir` aside intact (`<spill-dir>.stale-<unix_ts>[-N]`) and initializes a fresh cache.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleSpillRotation {
    pub moved_to: PathBuf,
    pub old_mode_desc: String,
    pub new_mode_desc: String,
}

impl StaleSpillRotation {
    pub fn format_warning(&self, spill_dir: &Path) -> String {
        format!(
            "[serve] WARNING: --spill-dir {} stale cache mismatch (found {}, expected {}); moved existing spill directory aside intact to {} and initialized a fresh empty spill cache",
            spill_dir.display(),
            self.old_mode_desc,
            self.new_mode_desc,
            self.moved_to.display(),
        )
    }
}

impl SpillStore {
    /// Prepare `--spill-dir` (mode `0700` on Unix), sweep orphan `.tmp.*` files,
    /// index surviving `.blk` files, and enforce `max_bytes` via LRU disk GC (default fp16 `kvb = 2`).
    pub fn open(dir: impl AsRef<Path>, max_bytes: u64) -> Result<Self, SpillError> {
        Self::open_with_kvb(dir, max_bytes, 2)
    }

    /// Prepare `--spill-dir` with an explicit KV element width `kvb` (`1` for `--kv8`, `2` for fp16).
    pub fn open_with_kvb(dir: impl AsRef<Path>, max_bytes: u64, kvb: u32) -> Result<Self, SpillError> {
        if kvb != 1 && kvb != 2 {
            return Err(SpillError::InvalidKvb(kvb));
        }
        Self::open_inner(dir, max_bytes, kvb)
    }

    /// Prepare `--spill-dir` with an explicit [`crate::blocks::KvMode`] (`Fp16`, `Kv8`, or `Kv4`).
    pub fn open_with_mode(
        dir: impl AsRef<Path>,
        max_bytes: u64,
        mode: crate::blocks::KvMode,
    ) -> Result<Self, SpillError> {
        Self::open_inner(dir, max_bytes, mode.kvb_tag())
    }

    /// Prepare `--spill-dir` in `--kv4` mode and immediately verify (or stamp on a fresh empty
    /// directory) the SHA-256 digest of the calibrated `98,304`-byte `K_DC_ROT` table + codec flags.
    pub fn open_with_kv4_digest(
        dir: impl AsRef<Path>,
        max_bytes: u64,
        kv4_digest: [u8; 32],
    ) -> Result<Self, SpillError> {
        let mut store = Self::open_with_mode(dir, max_bytes, crate::blocks::KvMode::Kv4)?;
        store.verify_or_stamp_kv4_digest(kv4_digest)?;
        Ok(store)
    }

    /// Open `--spill-dir` for `inky serve`; if an existing derived cache directory was written
    /// under a different KV mode or KV4 `K_DC_ROT`/shader digest (`SpillError::ModeMismatch`),
    /// never delete it — retain `flock(LOCK_EX | LOCK_NB)` on the directory inode across the
    /// mismatch check AND across `fs::rename` to `<spill-dir>.stale-<unix_ts>[-N]`, unlock the
    /// moved backup directory only after `fs::rename` completes, and initialize a fresh empty
    /// [`SpillStore`] at `dir`. If `dir` is already locked by an active opener, fails immediately
    /// with [`SpillError::DirectoryLocked`] without touching `dir`.
    pub fn open_or_rotate_stale(
        dir: impl AsRef<Path>,
        max_bytes: u64,
        mode: crate::blocks::KvMode,
        kv4_digest: Option<[u8; 32]>,
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        let unix_ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        Self::open_or_rotate_stale_at(dir, max_bytes, mode, kv4_digest, unix_ts)
    }

    pub fn open_or_rotate_stale_at(
        dir: impl AsRef<Path>,
        max_bytes: u64,
        mode: crate::blocks::KvMode,
        kv4_digest: Option<[u8; 32]>,
        unix_ts: u64,
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        let dir_path = dir.as_ref();
        match Self::open_locked(dir_path, max_bytes, mode.kvb_tag())? {
            OpenLockedOutcome::Opened(mut store) => {
                if let Some(d) = kv4_digest {
                    match store.verify_or_stamp_kv4_digest(d) {
                        Ok(()) => Ok((*store, None)),
                        Err(SpillError::ModeMismatch { found, .. }) => {
                            let Self { directory_lock, .. } = *store;
                            Self::rotate_locked_and_reopen(
                                dir_path,
                                directory_lock,
                                max_bytes,
                                mode,
                                kv4_digest,
                                found,
                                unix_ts,
                            )
                        }
                        Err(e) => Err(e),
                    }
                } else {
                    Ok((*store, None))
                }
            }
            OpenLockedOutcome::ModeMismatch { locked_dir, found, .. } => {
                Self::rotate_locked_and_reopen(
                    dir_path,
                    locked_dir,
                    max_bytes,
                    mode,
                    kv4_digest,
                    found,
                    unix_ts,
                )
            }
        }
    }

    /// Verify or stamp `kv4_digest` on an already-opened `--kv4` [`SpillStore`], or on
    /// [`SpillError::ModeMismatch`] rotate the directory aside while **retaining** `self`'s
    /// exclusive directory lock across `fs::rename` and open a fresh empty store at `self.dir`.
    pub fn verify_or_rotate_kv4_digest(
        mut self,
        kv4_digest: [u8; 32],
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        match self.verify_or_stamp_kv4_digest(kv4_digest) {
            Ok(()) => Ok((self, None)),
            Err(SpillError::ModeMismatch { found, .. }) => {
                let unix_ts = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let Self { directory_lock, dir, max_bytes, .. } = self;
                Self::rotate_locked_and_reopen(
                    &dir,
                    directory_lock,
                    max_bytes,
                    crate::blocks::KvMode::Kv4,
                    Some(kv4_digest),
                    found,
                    unix_ts,
                )
            }
            Err(e) => Err(e),
        }
    }

    fn rotate_locked_and_reopen(
        dir_path: &Path,
        locked_dir: LockedDirGuard,
        max_bytes: u64,
        mode: crate::blocks::KvMode,
        kv4_digest: Option<[u8; 32]>,
        found_kvb: u32,
        unix_ts: u64,
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        let new_mode_desc = Self::describe_requested_mode(mode, kv4_digest);
        let old_mode_desc = Self::describe_existing_spill_dir(dir_path, found_kvb);
        let moved_to = Self::rotate_stale_spill_dir_locked(dir_path, locked_dir, unix_ts)?;
        let fresh = match kv4_digest {
            Some(d) => Self::open_with_kv4_digest(dir_path, max_bytes, d)?,
            None => Self::open_with_mode(dir_path, max_bytes, mode)?,
        };
        Ok((
            fresh,
            Some(StaleSpillRotation { moved_to, old_mode_desc, new_mode_desc }),
        ))
    }

    fn describe_kvb_tag(kvb: u32) -> String {
        match kvb {
            2 => "kvb=2 (fp16)".into(),
            1 => "kvb=1 (kv8)".into(),
            k if k == crate::blocks::KVB_KV4 => format!("kvb={k} (kv4)"),
            other => format!("kvb={other}"),
        }
    }

    fn describe_requested_mode(mode: crate::blocks::KvMode, kv4_digest: Option<[u8; 32]>) -> String {
        match (mode, kv4_digest) {
            (crate::blocks::KvMode::Kv4, Some(d)) => {
                format!("kvb={} (kv4-wht-v1 sha256={})", crate::blocks::KVB_KV4, Self::format_hex32(&d))
            }
            (m, _) => Self::describe_kvb_tag(m.kvb_tag()),
        }
    }

    fn describe_existing_spill_dir(dir: &Path, fallback_found_kvb: u32) -> String {
        let marker = dir.join(SPILL_KV4_MARKER_FILENAME);
        if let Ok(meta) = fs::symlink_metadata(&marker) {
            if meta.file_type().is_file() && meta.len() <= 256 {
                if let Ok(raw) = fs::read(&marker) {
                    if let Ok(s) = std::str::from_utf8(&raw) {
                        let t = s.trim();
                        if !t.is_empty() {
                            return format!("kvb={} ({t})", crate::blocks::KVB_KV4);
                        }
                    }
                }
            }
        }
        if let Some(idx_kvb) = Self::peek_index_kvb(&dir.join(SPILL_INDEX_FILENAME)) {
            return Self::describe_kvb_tag(idx_kvb);
        }
        if let Ok(rd) = fs::read_dir(dir) {
            for entry in rd.flatten() {
                let path = entry.path();
                if let Some(name) = entry.file_name().to_str() {
                    if SpillKey::parse_blk_filename(name).is_some() {
                        if let Some(blk_kvb) = Self::peek_blk_kvb(&path) {
                            return Self::describe_kvb_tag(blk_kvb);
                        }
                    }
                }
            }
        }
        Self::describe_kvb_tag(fallback_found_kvb)
    }

    fn rotate_stale_spill_dir_locked(
        dir: &Path,
        locked_dir: LockedDirGuard,
        unix_ts: u64,
    ) -> Result<PathBuf, SpillError> {
        let clean: PathBuf = dir.components().collect();
        let Some(parent) = clean.parent() else {
            return Err(SpillError::InvalidDir(format!("cannot rotate root path {}", dir.display())));
        };
        let parent_dir = if parent.as_os_str().is_empty() { Path::new(".") } else { parent };
        let Some(base_os) = clean.file_name() else {
            return Err(SpillError::InvalidDir(format!("cannot rotate {}", dir.display())));
        };
        let base = base_os.to_string_lossy();

        #[cfg(test)]
        run_test_spill_rotate_hook(&clean);

        // Verify under the held `LOCK_EX` descriptor right before `fs::rename` that `clean` still
        // resolves to the exact `(dev, ino)` directory inode we locked.
        let path_meta = fs::symlink_metadata(&clean)?;
        if !path_meta.file_type().is_dir() {
            return Err(SpillError::InvalidDir(format!(
                "--spill-dir {} is not a regular directory",
                dir.display()
            )));
        }
        #[cfg(unix)]
        {
            let fd_meta = locked_dir.0.metadata()?;
            if (fd_meta.dev(), fd_meta.ino()) != (path_meta.dev(), path_meta.ino()) {
                return Err(SpillError::InvalidDir(format!(
                    "--spill-dir {} inode changed while locked (locked {}:{}, path {}:{})",
                    dir.display(),
                    fd_meta.dev(),
                    fd_meta.ino(),
                    path_meta.dev(),
                    path_meta.ino(),
                )));
            }
        }

        for attempt in 0u64..10_000 {
            let cand_name = if attempt == 0 {
                format!("{base}.stale-{unix_ts}")
            } else {
                format!("{base}.stale-{unix_ts}-{attempt}")
            };
            let cand_path = parent_dir.join(cand_name);
            if fs::symlink_metadata(&cand_path).is_ok() {
                continue;
            }
            match fs::rename(&clean, &cand_path) {
                Ok(()) => {
                    fsync_dir(parent_dir)?;
                    // Only release/unlock the old directory descriptor AFTER `fs::rename` completes!
                    drop(locked_dir);
                    return Ok(cand_path);
                }
                Err(e)
                    if e.kind() == io::ErrorKind::AlreadyExists
                        || e.kind() == io::ErrorKind::DirectoryNotEmpty =>
                {
                    continue;
                }
                Err(e) => return Err(SpillError::Io(e)),
            }
        }
        Err(SpillError::InvalidDir(format!(
            "exhausted stale rotation names for {}",
            dir.display()
        )))
    }

    fn acquire_spill_dir_lock(dir: &Path) -> Result<LockedDirGuard, SpillError> {
        for _attempt in 0..4 {
            prepare_spill_dir(dir)?;
            let mut options = OpenOptions::new();
            options.read(true);
            #[cfg(unix)]
            options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
            let file = match options.open(dir) {
                Ok(f) => f,
                Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
                Err(e) => return Err(e.into()),
            };
            match file.try_lock() {
                Ok(()) => {}
                Err(std::fs::TryLockError::WouldBlock) => {
                    return Err(SpillError::DirectoryLocked(dir.to_path_buf()));
                }
                Err(std::fs::TryLockError::Error(err)) => return Err(err.into()),
            }
            let guard = LockedDirGuard(file);
            #[cfg(unix)]
            {
                let fd_meta = guard.0.metadata()?;
                match fs::symlink_metadata(dir) {
                    Ok(path_meta)
                        if path_meta.file_type().is_dir()
                            && (fd_meta.dev(), fd_meta.ino()) == (path_meta.dev(), path_meta.ino()) =>
                    {
                        return Ok(guard);
                    }
                    Ok(_) | Err(_) => {
                        // A concurrent rotation moved `dir` between `open(dir)` and `try_lock()`;
                        // drop `guard` to unlock the detached inode and re-open the live `dir`.
                        drop(guard);
                        continue;
                    }
                }
            }
            #[cfg(not(unix))]
            {
                return Ok(guard);
            }
        }
        Err(SpillError::InvalidDir(format!(
            "concurrent directory replacement contended on {}",
            dir.display()
        )))
    }

    fn open_locked(dir: &Path, max_bytes: u64, kvb: u32) -> Result<OpenLockedOutcome, SpillError> {
        let directory_lock = Self::acquire_spill_dir_lock(dir)?;
        let mut store = Self {
            directory_lock,
            last_allocated_id: 1,
            dir: dir.to_path_buf(),
            max_bytes,
            used_bytes: 0,
            lru_clock: 0,
            kvb,
            entries: HashMap::new(),
            reserved: HashMap::new(),
            reserved_bytes: 0,
            stats: SpillStoreStats::default(),
        };
        match store.scan_and_sweep() {
            Ok(()) => Ok(OpenLockedOutcome::Opened(Box::new(store))),
            Err(SpillError::ModeMismatch { expected, found }) => {
                let Self { directory_lock, .. } = store;
                Ok(OpenLockedOutcome::ModeMismatch {
                    locked_dir: directory_lock,
                    expected,
                    found,
                })
            }
            Err(e) => Err(e),
        }
    }

    fn open_inner(dir: impl AsRef<Path>, max_bytes: u64, kvb: u32) -> Result<Self, SpillError> {
        match Self::open_locked(dir.as_ref(), max_bytes, kvb)? {
            OpenLockedOutcome::Opened(store) => Ok(*store),
            OpenLockedOutcome::ModeMismatch { expected, found, .. } => {
                Err(SpillError::ModeMismatch { expected, found })
            }
        }
    }

    pub fn kvb(&self) -> u32 {
        self.kvb
    }

    #[cfg(test)]
    pub(super) fn clone_directory_lock(&self) -> io::Result<File> {
        self.directory_lock.0.try_clone()
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    pub fn used_bytes(&self) -> u64 {
        self.used_bytes
    }

    pub fn max_bytes(&self) -> u64 {
        self.max_bytes
    }

    pub fn stats(&self) -> SpillStoreStats {
        self.stats
    }

    pub fn contains(&self, key: SpillKey) -> bool {
        self.entries.contains_key(&key)
    }

    /// Allocate an identity for a new checkpoint block, skipping surviving blocks
    /// whose content belongs to an earlier generation of the in-memory checkpoint index.
    pub fn fresh_key(&mut self, kind: SpillBlockKind) -> SpillKey {
        loop {
            self.last_allocated_id = self.last_allocated_id.wrapping_add(1).max(1);
            let key = SpillKey::new(kind, self.last_allocated_id);
            if !self.contains(key) && !self.reserved.contains_key(&key) {
                return key;
            }
        }
    }

    pub(super) fn keys(&self) -> impl Iterator<Item = SpillKey> + '_ {
        self.entries.keys().copied()
    }

    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    pub fn block_path(&self, key: SpillKey) -> PathBuf {
        self.dir.join(key.blk_filename())
    }

    fn next_lru(&mut self) -> u64 {
        self.lru_clock = self.lru_clock.wrapping_add(1);
        self.lru_clock
    }

    fn peek_blk_kvb(path: &Path) -> Option<u32> {
        let mut opts = OpenOptions::new();
        opts.read(true);
        #[cfg(unix)]
        {
            opts.custom_flags(libc::O_NOFOLLOW);
        }
        let file = opts.open(path).ok()?;
        let mut hdr = [0u8; 16];
        pread_exact(&file, &mut hdr, 0).ok()?;
        if hdr[0..8] != SPILL_MAGIC {
            return None;
        }
        let ver = u32::from_le_bytes(hdr[8..12].try_into().ok()?);
        if ver != SPILL_FORMAT_VERSION {
            return None;
        }
        Some(u32::from(u16::from_le_bytes(hdr[14..16].try_into().ok()?)))
    }

    fn peek_index_kvb(path: &Path) -> Option<u32> {
        let mut opts = OpenOptions::new();
        opts.read(true);
        #[cfg(unix)]
        {
            opts.custom_flags(libc::O_NOFOLLOW);
        }
        let file = opts.open(path).ok()?;
        let mut hdr = [0u8; 16];
        pread_exact(&file, &mut hdr, 0).ok()?;
        if hdr[0..8] != SPILL_INDEX_MAGIC {
            return None;
        }
        Some(u32::from_le_bytes(hdr[12..16].try_into().ok()?))
    }

    fn format_hex32(bytes: &[u8; 32]) -> String {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut out = String::with_capacity(64);
        for &b in bytes {
            out.push(HEX[(b >> 4) as usize] as char);
            out.push(HEX[(b & 0x0f) as usize] as char);
        }
        out
    }

    fn parse_hex32(s: &str) -> Option<[u8; 32]> {
        if s.len() != 64 {
            return None;
        }
        let hex_nibble = |c: u8| -> Option<u8> {
            match c {
                b'0'..=b'9' => Some(c - b'0'),
                b'a'..=b'f' => Some(c - b'a' + 10),
                b'A'..=b'F' => Some(c - b'A' + 10),
                _ => None,
            }
        };
        let raw = s.as_bytes();
        let mut out = [0u8; 32];
        for (i, slot) in out.iter_mut().enumerate() {
            let hi = hex_nibble(raw[2 * i])?;
            let lo = hex_nibble(raw[2 * i + 1])?;
            *slot = (hi << 4) | lo;
        }
        Some(out)
    }

    fn write_kv4_marker_atomic(&self, content: &[u8]) -> Result<(), SpillError> {
        let final_path = self.dir.join(SPILL_KV4_MARKER_FILENAME);
        let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
        let tmp_path = self.dir.join(format!("{SPILL_KV4_MARKER_TMP_PREFIX}{}.{nonce}", std::process::id()));
        let res = (|| -> io::Result<()> {
            let mut opts = OpenOptions::new();
            opts.write(true).create_new(true);
            #[cfg(unix)]
            {
                opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
            }
            let mut file = opts.open(&tmp_path)?;
            #[cfg(unix)]
            {
                file.set_permissions(fs::Permissions::from_mode(0o600))?;
            }
            file.write_all(content)?;
            file.sync_all()?;
            drop(file);
            fs::rename(&tmp_path, &final_path)?;
            fsync_dir(&self.dir)?;
            Ok(())
        })();
        if let Err(e) = res {
            let _ = fs::remove_file(&tmp_path);
            return Err(SpillError::Io(e));
        }
        Ok(())
    }

    /// Verify that an existing `--kv4` spill directory's `kv4.mode` stamp matches `kv4_digest`,
    /// or atomically stamp `kv4-wht-v1 sha256=<hex>` when the directory is freshly created and empty.
    /// Fails closed with [`SpillError::ModeMismatch`] if `kv4.mode` carries a different digest or
    /// if pre-existing KV4 blocks lack a verified digest stamp.
    pub fn verify_or_stamp_kv4_digest(&mut self, kv4_digest: [u8; 32]) -> Result<(), SpillError> {
        let kv4_tag = crate::blocks::KVB_KV4;
        if self.kvb != kv4_tag {
            return Err(SpillError::ModeMismatch { expected: kv4_tag, found: self.kvb });
        }
        let kv4_marker = self.dir.join(SPILL_KV4_MARKER_FILENAME);
        let pending_line = "kv4-wht-v1 pending";
        if let Ok(meta) = fs::symlink_metadata(&kv4_marker) {
            if !meta.file_type().is_file() || meta.len() > 256 {
                return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
            }
            let mut opts = OpenOptions::new();
            opts.read(true);
            #[cfg(unix)]
            {
                opts.custom_flags(libc::O_NOFOLLOW);
            }
            let mut file = opts.open(&kv4_marker)?;
            let mut buf = Vec::with_capacity(meta.len() as usize);
            io::Read::read_to_end(&mut file, &mut buf)?;
            let Ok(text) = std::str::from_utf8(&buf) else {
                return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
            };
            let trimmed = text.trim();
            if let Some(hex) = trimmed.strip_prefix("kv4-wht-v1 sha256=") {
                let Some(found_digest) = Self::parse_hex32(hex) else {
                    return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
                };
                if found_digest != kv4_digest {
                    return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
                }
                return Ok(());
            }
            if trimmed != pending_line {
                return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
            }
        }
        // Only stamp a fresh directory that has zero surviving `.blk` entries and no index yet.
        if !self.entries.is_empty() || fs::symlink_metadata(self.dir.join(SPILL_INDEX_FILENAME)).is_ok() {
            return Err(SpillError::ModeMismatch { expected: kv4_tag, found: kv4_tag });
        }
        let stamped = format!("kv4-wht-v1 sha256={}\n", Self::format_hex32(&kv4_digest));
        self.write_kv4_marker_atomic(stamped.as_bytes())
    }


    fn write_arith_marker_atomic(&self, content: &[u8]) -> Result<(), SpillError> {
        let final_path = self.dir.join(SPILL_ARITH_MARKER_FILENAME);
        let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
        let tmp_path = self.dir.join(format!("{SPILL_ARITH_MARKER_TMP_PREFIX}{}.{nonce}", std::process::id()));
        let res = (|| -> io::Result<()> {
            let mut opts = OpenOptions::new();
            opts.write(true).create_new(true);
            #[cfg(unix)]
            {
                opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
            }
            let mut file = opts.open(&tmp_path)?;
            #[cfg(unix)]
            {
                file.set_permissions(fs::Permissions::from_mode(0o600))?;
            }
            file.write_all(content)?;
            file.sync_all()?;
            drop(file);
            fs::rename(&tmp_path, &final_path)?;
            fsync_dir(&self.dir)?;
            Ok(())
        })();
        if let Err(e) = res {
            let _ = fs::remove_file(&tmp_path);
            return Err(SpillError::Io(e));
        }
        Ok(())
    }

    /// Verify that an existing spill directory's `prefill.arith` stamp matches `arith`,
    /// or atomically stamp `arith.spill_marker_line()` when the directory is freshly created and empty.
    /// Fails closed with [`SpillError::ModeMismatch`] if `prefill.arith` records a different arithmetic
    /// family OR if pre-existing `.blk` / `spill.idx` files lack an arithmetic stamp (legacy untagged state).
    pub fn verify_or_stamp_prefill_arith(&mut self, arith: crate::blocks::PrefillArithMode) -> Result<(), SpillError> {
        match self.prefill_arith_mismatch(arith)? {
            None => Ok(()),
            Some(_) => Err(SpillError::ModeMismatch { expected: self.kvb, found: self.kvb }),
        }
    }

    /// Stamp a fresh store or return a trusted description of the incompatible arithmetic.
    fn prefill_arith_mismatch(&self, arith: crate::blocks::PrefillArithMode) -> Result<Option<&'static str>, SpillError> {
        use std::io::Read;

        const LIMIT: u64 = 256;
        const INVALID: &str = "invalid-prefill-arith";
        let marker = self.dir.join(SPILL_ARITH_MARKER_FILENAME);
        match fs::symlink_metadata(&marker) {
            Ok(meta) if !meta.is_file() || meta.len() > LIMIT => return Ok(Some(INVALID)),
            Ok(_) => {}
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                if !self.entries.is_empty() || fs::symlink_metadata(self.dir.join(SPILL_INDEX_FILENAME)).is_ok() {
                    return Ok(Some("untagged-legacy-prefill"));
                }
                let stamped = format!("{}\n", arith.spill_marker_line());
                self.write_arith_marker_atomic(stamped.as_bytes())?;
                return Ok(None);
            }
            Err(e) => return Err(e.into()),
        }

        let mut opts = OpenOptions::new();
        opts.read(true);
        #[cfg(unix)]
        opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
        let file = opts.open(marker)?;
        let meta = file.metadata()?;
        if !meta.is_file() || meta.len() > LIMIT {
            return Ok(Some(INVALID));
        }
        let mut buf = Vec::with_capacity(meta.len() as usize);
        file.take(LIMIT + 1).read_to_end(&mut buf)?;
        if buf.len() as u64 > LIMIT {
            return Ok(Some(INVALID));
        }
        let found = std::str::from_utf8(&buf).ok()
            .and_then(crate::blocks::PrefillArithMode::from_spill_marker_line);
        Ok(match found {
            Some(mode) if mode == arith => None,
            Some(mode) => Some(mode.spill_marker_line()),
            None => Some(INVALID),
        })
    }

    /// Verify or stamp `arith` on an opened [`SpillStore`], or on [`SpillError::ModeMismatch`]
    /// rotate the incompatible/legacy directory aside intact while retaining the exclusive directory lock
    /// across `fs::rename` and open a fresh stamped store at `self.dir`.
    pub fn verify_or_rotate_prefill_arith(
        self,
        mode: crate::blocks::KvMode,
        kv4_digest: Option<[u8; 32]>,
        arith: crate::blocks::PrefillArithMode,
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        let unix_ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        self.verify_or_rotate_prefill_arith_at(mode, kv4_digest, arith, unix_ts)
    }

    pub fn verify_or_rotate_prefill_arith_at(
        self,
        mode: crate::blocks::KvMode,
        kv4_digest: Option<[u8; 32]>,
        arith: crate::blocks::PrefillArithMode,
        unix_ts: u64,
    ) -> Result<(Self, Option<StaleSpillRotation>), SpillError> {
        match self.prefill_arith_mismatch(arith)? {
            None => Ok((self, None)),
            Some(old_arith_desc) => {
                let old_mode_desc = format!(
                    "{}, {}",
                    Self::describe_existing_spill_dir(&self.dir, self.kvb),
                    old_arith_desc
                );
                let new_mode_desc = format!(
                    "{}, {}",
                    Self::describe_requested_mode(mode, kv4_digest),
                    arith.spill_marker_line()
                );
                let Self { directory_lock, dir, max_bytes, .. } = self;
                let moved_to = Self::rotate_stale_spill_dir_locked(&dir, directory_lock, unix_ts)?;
                let mut fresh = match kv4_digest {
                    Some(d) => Self::open_with_kv4_digest(&dir, max_bytes, d)?,
                    None => Self::open_with_mode(&dir, max_bytes, mode)?,
                };
                fresh.verify_or_stamp_prefill_arith(arith)?;
                Ok((fresh, Some(StaleSpillRotation { moved_to, old_mode_desc, new_mode_desc })))
            }
        }
    }

    fn scan_and_sweep(&mut self) -> Result<(), SpillError> {
        let kv4_tag = crate::blocks::KVB_KV4;
        let kv4_marker = self.dir.join(SPILL_KV4_MARKER_FILENAME);
        if fs::symlink_metadata(&kv4_marker).is_ok() && self.kvb != kv4_tag {
            return Err(SpillError::ModeMismatch { expected: self.kvb, found: kv4_tag });
        }
        if let Some(idx_kvb) = Self::peek_index_kvb(&self.dir.join(SPILL_INDEX_FILENAME)) {
            if (self.kvb == kv4_tag || idx_kvb == kv4_tag) && idx_kvb != self.kvb {
                return Err(SpillError::ModeMismatch { expected: self.kvb, found: idx_kvb });
            }
        }
        let mut discovered: Vec<(SpillKey, u64, u64)> = Vec::new();
        let mut pending_orphan_tmps: Vec<PathBuf> = Vec::new();
        let mut pending_non_regular_blks: Vec<PathBuf> = Vec::new();
        for entry in fs::read_dir(&self.dir)? {
            let entry = entry?;
            let path = entry.path();
            let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
                continue;
            };
            let meta = match fs::symlink_metadata(&path) {
                Ok(m) => m,
                Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
                Err(e) => return Err(e.into()),
            };
            if SpillKey::parse_tmp_filename(&name).is_some()
                || name.starts_with(SPILL_INDEX_TMP_PREFIX)
                || name.starts_with(SPILL_KV4_MARKER_TMP_PREFIX)
                || name.starts_with(SPILL_ARITH_MARKER_TMP_PREFIX)
            {
                if meta.is_file() {
                    pending_orphan_tmps.push(path);
                }
                continue;
            }
            if let Some(key) = SpillKey::parse_blk_filename(&name) {
                if !meta.file_type().is_file() {
                    // Never trust symlinks or non-regular files in spill dir.
                    pending_non_regular_blks.push(path);
                    continue;
                }
                if let Some(blk_kvb) = Self::peek_blk_kvb(&path) {
                    if (self.kvb == kv4_tag || blk_kvb == kv4_tag) && blk_kvb != self.kvb {
                        return Err(SpillError::ModeMismatch { expected: self.kvb, found: blk_kvb });
                    }
                }
                let mtime_key = meta
                    .modified()
                    .ok()
                    .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                    .map(|d| d.as_nanos() as u64)
                    .unwrap_or(0);
                discovered.push((key, meta.len(), mtime_key));
            }
        }
        for path in pending_orphan_tmps {
            if unlink_if_present(&path)? {
                self.stats.orphans_swept += 1;
            }
        }
        for path in pending_non_regular_blks {
            if unlink_if_present(&path)? {
                self.stats.corrupt_files_removed += 1;
            }
        }
        if self.kvb == kv4_tag && fs::symlink_metadata(&kv4_marker).is_err() {
            self.write_kv4_marker_atomic(b"kv4-wht-v1 pending\n")?;
        }
        // Order surviving blocks oldest-mtime first so LRU clock preserves relative age.
        discovered.sort_by_key(|&(key, _, mtime)| (mtime, key));
        for (key, len, _) in discovered {
            self.last_allocated_id = self.last_allocated_id.max(key.id);
            let seq = self.next_lru();
            self.entries.insert(key, DiskEntry { bytes: len, lru_seq: seq });
            self.used_bytes = self.used_bytes.saturating_add(len);
        }
        if self.stats.orphans_swept > 0 {
            fsync_dir(&self.dir)?;
        }
        // Enforce disk budget on startup if existing files exceed max_bytes.
        let empty = HashSet::new();
        self.evict_lru_to_fit(0, &empty);
        if self.used_bytes > self.max_bytes {
            return Err(SpillError::InvalidDir(format!(
                "could not reduce spill usage of {} bytes to the {} byte budget",
                self.used_bytes, self.max_bytes
            )));
        }
        Ok(())
    }

    /// Evict least-recently-used `.blk` files not in `protected` until
    /// `self.used_bytes + additional <= self.max_bytes` (returns evicted keys).
    pub fn evict_lru_to_fit(
        &mut self,
        additional: u64,
        protected: &HashSet<SpillKey>,
    ) -> Vec<SpillKey> {
        self.evict_lru_until(self.max_bytes.checked_sub(additional), protected, None)
    }

    /// LRU disk GC once a spill has landed: evict blocks outside `protected` until the bytes on disk are at most
    /// `--max-spill-bytes` plus `in_flight`, the landed blocks of spills that have not committed yet (each
    /// settles the budget itself when it commits, or is unlinked when it fails). With `owed_unlinks` there is no
    /// file I/O: each victim leaves the index now and its key goes onto the list, for the caller to unlink off
    /// the scheduler thread ([`unlink_block_in_dir`]).
    pub fn settle_budget(
        &mut self,
        in_flight: u64,
        protected: &HashSet<SpillKey>,
        owed_unlinks: Option<&mut Vec<SpillKey>>,
    ) -> Vec<SpillKey> {
        self.evict_lru_until(Some(self.max_bytes.saturating_add(in_flight)), protected, owed_unlinks)
    }

    /// The bytes that would remain on disk if LRU disk GC evicted every block it may (all outside `protected`).
    /// Evicts nothing: a spill asks this before it writes, and again before it settles the budget.
    pub fn bytes_after_full_gc(&self, protected: &HashSet<SpillKey>) -> u64 {
        let evictable: u64 =
            self.entries.iter().filter(|(k, _)| !protected.contains(k)).map(|(_, e)| e.bytes).sum();
        self.used_bytes.saturating_sub(evictable)
    }

    /// On-disk bytes of an indexed block.
    pub fn entry_bytes(&self, key: SpillKey) -> Option<u64> {
        self.entries.get(&key).map(|e| e.bytes)
    }

    /// Mark an indexed block as just used, as a write or a read of it would: a spill that reuses a block
    /// already on disk makes it as recent as the spill, so LRU disk GC does not take it first.
    pub fn touch(&mut self, key: SpillKey) -> bool {
        if !self.entries.contains_key(&key) {
            return false;
        }
        let seq = self.next_lru();
        if let Some(entry) = self.entries.get_mut(&key) {
            entry.lru_seq = seq;
        }
        true
    }

    /// Count a spill refused because it could not fit `--max-spill-bytes`.
    pub fn note_over_budget_drop(&mut self) {
        self.stats.over_budget_drops += 1;
    }

    // Evict until `used_bytes <= limit`; with no limit (nothing could fit), until no victim is left.
    fn evict_lru_until(
        &mut self,
        limit: Option<u64>,
        protected: &HashSet<SpillKey>,
        mut owed_unlinks: Option<&mut Vec<SpillKey>>,
    ) -> Vec<SpillKey> {
        let mut evicted = Vec::new();
        let mut failed = HashSet::new();
        while limit.is_none_or(|limit| self.used_bytes > limit) {
            let victim = self
                .entries
                .iter()
                .filter(|(k, _)| !protected.contains(k) && !failed.contains(*k))
                .min_by_key(|(k, e)| (e.lru_seq, **k))
                .map(|(k, _)| *k);
            let Some(victim_key) = victim else {
                break;
            };
            let removed = match owed_unlinks.as_deref_mut() {
                Some(owed) => {
                    self.forget_block(victim_key);
                    owed.push(victim_key);
                    true
                }
                None => self.remove_block(victim_key),
            };
            if removed {
                self.stats.disk_gc_evictions += 1;
                evicted.push(victim_key);
            } else {
                failed.insert(victim_key);
            }
        }
        evicted
    }

    /// Drop `key` from the index with no file I/O; the caller owes its unlink ([`unlink_block_in_dir`]).
    /// Returns whether the block was indexed.
    pub fn forget_block_owing_unlink(&mut self, key: SpillKey) -> bool {
        let indexed = self.entries.contains_key(&key);
        self.forget_block(key);
        indexed
    }

    /// Remove a specific block from disk if present.
    pub fn remove_block(&mut self, key: SpillKey) -> bool {
        let indexed = self.entries.contains_key(&key);
        self.unlink_block(key).is_ok_and(|removed| removed || indexed)
    }

    fn forget_block(&mut self, key: SpillKey) {
        if let Some(entry) = self.entries.remove(&key) {
            self.used_bytes = self.used_bytes.saturating_sub(entry.bytes);
        }
    }

    fn unlink_block(&mut self, key: SpillKey) -> io::Result<bool> {
        let removed = unlink_if_present(&self.block_path(key))?;
        self.forget_block(key);
        Ok(removed)
    }

    /// Crash-safe atomic write of a block (K/V + optional start-point recurrent state):
    /// enforce `--max-spill-bytes` with LRU disk GC, write `<tmp>` (`0600`), `fsync`,
    /// atomic `rename` to `<id>.blk`, and `fsync` directory.
    ///
    /// Returns `(WriteOutcome, evicted_disk_keys)` so callers can update tier metadata
    /// for any cold blocks GC'd from disk.
    pub fn write_block(
        &mut self,
        key: SpillKey,
        generation: u64,
        kv_bytes: &[u8],
        recurrent_state: Option<&[u8]>,
        protected: &HashSet<SpillKey>,
    ) -> Result<(WriteOutcome, Vec<SpillKey>), SpillError> {
        if kv_bytes.len() > MAX_KV_PAYLOAD_BYTES {
            return Err(SpillError::PayloadTooLarge(kv_bytes.len()));
        }
        let state_slice = recurrent_state.unwrap_or(&[]);
        if state_slice.len() > MAX_RECURRENT_STATE_BYTES {
            return Err(SpillError::PayloadTooLarge(state_slice.len()));
        }
        let total_bytes = (SPILL_HEADER_LEN as u64)
            .checked_add(kv_bytes.len() as u64)
            .and_then(|v| v.checked_add(state_slice.len() as u64))
            .ok_or(SpillError::PayloadTooLarge(usize::MAX))?;

        if total_bytes > self.max_bytes {
            self.stats.over_budget_drops += 1;
            return Ok((WriteOutcome::OverBudget, Vec::new()));
        }

        // A case-insensitive filesystem can resolve a canonical block path to an
        // unrelated, noncanonical filename deliberately left out of the index.
        let final_path = self.block_path(key);
        let existing_bytes = match self.entries.get(&key) {
            Some(entry) => entry.bytes,
            None => match fs::symlink_metadata(&final_path) {
                Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
                Err(e) => return Err(e.into()),
                Ok(_) => {
                    return Err(io::Error::new(io::ErrorKind::AlreadyExists,
                        format!("unindexed file at {}", final_path.display())).into());
                }
            },
        };
        let net_additional = total_bytes.saturating_sub(existing_bytes);
        let mut protected_with_self = protected.clone();
        protected_with_self.insert(key);
        let evicted = self.evict_lru_to_fit(net_additional, &protected_with_self);
        let after = self
            .used_bytes
            .saturating_sub(existing_bytes)
            .saturating_add(self.reserved_bytes)
            .saturating_add(total_bytes);
        if after > self.max_bytes {
            self.stats.over_budget_drops += 1;
            return Ok((WriteOutcome::OverBudget, evicted));
        }

        let raw = write_block_to_dir(&self.dir, self.kvb, key, generation, kv_bytes, recurrent_state, false);
        self.apply_raw_write(key, raw).map(|outcome| (outcome, evicted))
    }

    /// The on-disk size of a block with these payload lengths, under [`Self::write_block`]'s size caps.
    pub fn block_file_bytes(kv_len: usize, state_len: usize) -> Result<u64, SpillError> {
        if kv_len > MAX_KV_PAYLOAD_BYTES {
            return Err(SpillError::PayloadTooLarge(kv_len));
        }
        if state_len > MAX_RECURRENT_STATE_BYTES {
            return Err(SpillError::PayloadTooLarge(state_len));
        }
        (SPILL_HEADER_LEN as u64)
            .checked_add(kv_len as u64)
            .and_then(|v| v.checked_add(state_len as u64))
            .ok_or(SpillError::PayloadTooLarge(usize::MAX))
    }

    /// Record that `bytes` are on their way to disk for `key`, a write the spill writer thread performs later
    /// ([`write_block_to_dir`]). Nothing is evicted and no file is touched: the caller has already checked that
    /// the whole spill fits ([`Self::bytes_after_full_gc`]) and settles the budget when it has landed
    /// ([`Self::settle_budget`]). The reservation ends at [`Self::apply_raw_write`] or
    /// [`Self::release_write_reservation`].
    pub fn reserve_write(&mut self, key: SpillKey, bytes: u64) {
        self.release_write_reservation(key);
        self.reserved.insert(key, bytes);
        self.reserved_bytes = self.reserved_bytes.saturating_add(bytes);
    }

    /// Give back the bytes [`Self::reserve_write`] held for `key` (a cancelled write).
    pub fn release_write_reservation(&mut self, key: SpillKey) {
        if let Some(bytes) = self.reserved.remove(&key) {
            self.reserved_bytes = self.reserved_bytes.saturating_sub(bytes);
        }
    }

    /// Bytes reserved for writes that have not landed.
    pub fn reserved_bytes(&self) -> u64 {
        self.reserved_bytes
    }

    /// The bookkeeping half of a block write: index a [`RawDiskWrite`] that landed, or pass on its error. Either
    /// way `key`'s reservation ends here.
    pub fn apply_raw_write(&mut self, key: SpillKey, raw: RawDiskWrite) -> Result<WriteOutcome, SpillError> {
        self.release_write_reservation(key);
        let total_bytes = raw.result.map_err(SpillError::Io)?;
        if let Some(old) = self.entries.remove(&key) {
            self.used_bytes = self.used_bytes.saturating_sub(old.bytes);
        }
        let seq = self.next_lru();
        self.entries.insert(key, DiskEntry { bytes: total_bytes, lru_seq: seq });
        self.used_bytes = self.used_bytes.saturating_add(total_bytes);
        self.stats.writes_committed += 1;
        self.stats.bytes_written = self.stats.bytes_written.saturating_add(total_bytes);
        self.stats.write_us_total = self.stats.write_us_total.saturating_add(raw.elapsed_us);
        Ok(WriteOutcome::Written { on_disk_bytes: total_bytes })
    }

    /// Read and cryptographically verify a block from SSD via `pread`.
    ///
    /// Any missing, truncated, oversized, mismatched, or checksum-failing file
    /// returns `ReadOutcome::Miss(reason)` (and unlinks the corrupt `.blk`),
    /// NEVER exposing unverified or corrupt bytes.
    pub fn read_block(&mut self, key: SpillKey, expected_kv_len: Option<usize>) -> ReadOutcome {
        let raw = read_block_from_dir(&self.dir, self.kvb, key, expected_kv_len);
        self.apply_raw_read(key, raw)
    }

    /// Apply bookkeeping (LRU touch, hit/miss/corrupt counters, and unlinking corrupt `.blk`
    /// files) for a [`RawDiskRead`] completed by a background restore worker.
    ///
    /// A read never adds a block to the index. The worker reads without the store, so its read
    /// can arrive after the block was removed (a cancelled restore whose start was then restored
    /// by another lane, trimmed, or collected): the file was open, the read succeeded, and the
    /// file is gone. Only a block the index still holds has its size and LRU position updated.
    pub fn apply_raw_read(&mut self, key: SpillKey, raw: RawDiskRead) -> ReadOutcome {
        self.stats.read_us_total = self.stats.read_us_total.saturating_add(raw.elapsed_us);
        if let Some(file_len) = raw.observed_file_len {
            if let Some(entry) = self.entries.get_mut(&key) {
                self.used_bytes = self.used_bytes.saturating_sub(entry.bytes).saturating_add(file_len);
                entry.bytes = file_len;
            }
        }
        match &raw.outcome {
            ReadOutcome::Hit(_) => {
                let seq = self.next_lru();
                if let Some(entry) = self.entries.get_mut(&key) {
                    entry.lru_seq = seq;
                }
                self.stats.reads_hit += 1;
                if let Some(file_len) = raw.observed_file_len {
                    self.stats.bytes_read = self.stats.bytes_read.saturating_add(file_len);
                }
            }
            ReadOutcome::Miss(reason) => {
                if raw.is_corrupt {
                    self.drop_corrupt(key);
                } else {
                    if *reason == MissReason::NotFound {
                        self.forget_block(key);
                    }
                    self.stats.reads_miss += 1;
                }
            }
        }
        raw.outcome
    }

    /// Remove any indexed `.blk` files not present in `keep`, returning the number removed.
    pub fn retain_keys(&mut self, keep: &HashSet<SpillKey>) -> usize {
        let stale: Vec<SpillKey> = self
            .entries
            .keys()
            .copied()
            .filter(|k| !keep.contains(k))
            .collect();
        let mut removed = 0usize;
        for k in stale {
            if self.remove_block(k) {
                removed += 1;
            }
        }
        removed
    }

    /// Crash-safe atomic write of `spill-index.bin` (`0600`, `O_NOFOLLOW`, `fsync`, `rename`, dir `fsync`).
    pub fn write_index_bytes(&self, bytes: &[u8]) -> Result<(), SpillError> {
        write_index_to_dir(&self.dir, bytes).map_err(SpillError::Io)
    }

    /// Read `spill-index.bin` if present and regular (`<= max_len` bytes).
    /// Unlinks and returns `None` if corrupt, non-regular, or oversized.
    pub fn read_index_bytes(&mut self, max_len: usize) -> Option<Vec<u8>> {
        let path = self.dir.join(SPILL_INDEX_FILENAME);
        let mut opts = OpenOptions::new();
        opts.read(true);
        #[cfg(unix)]
        {
            opts.custom_flags(libc::O_NOFOLLOW);
        }
        let file = match opts.open(&path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
            Err(_) => {
                if matches!(unlink_if_present(&path), Ok(true)) {
                    self.stats.corrupt_files_removed += 1;
                }
                return None;
            }
        };
        let meta = match file.metadata() {
            Ok(m) if m.is_file() && m.len() <= max_len as u64 => m,
            _ => {
                drop(file);
                if matches!(unlink_if_present(&path), Ok(true)) {
                    self.stats.corrupt_files_removed += 1;
                }
                return None;
            }
        };
        let len = meta.len() as usize;
        let mut buf = vec![0u8; len];
        if pread_exact(&file, &mut buf, 0).is_err() {
            drop(file);
            if matches!(unlink_if_present(&path), Ok(true)) {
                self.stats.corrupt_files_removed += 1;
            }
            return None;
        }
        Some(buf)
    }

    /// Unlink `spill-index.bin` (recording a corrupt removal if `count_corrupt` is true).
    pub fn remove_index(&mut self, count_corrupt: bool) {
        let path = self.dir.join(SPILL_INDEX_FILENAME);
        if matches!(unlink_if_present(&path), Ok(true)) && count_corrupt {
            self.stats.corrupt_files_removed += 1;
        }
    }

    fn drop_corrupt(&mut self, key: SpillKey) {
        if matches!(self.unlink_block(key), Ok(true)) {
            self.stats.corrupt_files_removed += 1;
        }
        self.stats.reads_miss += 1;
    }
}

/// Result of writing a single `.blk` file without holding `&mut SpillStore`: its on-disk size, or the error.
#[derive(Debug)]
pub struct RawDiskWrite {
    pub result: io::Result<u64>,
    pub elapsed_us: u64,
}

/// Standalone crash-safe write of one block inside `dir`: header and SHA-256, `<tmp>` (`0600`, `O_NOFOLLOW`),
/// `fsync`, atomic `rename` to `<id>.blk`, directory `fsync`. Safe to run on the spill writer thread;
/// [`SpillStore::apply_raw_write`] does the bookkeeping. `refuse_existing` fails the write when any file already
/// sits at the block's path (the caller knows the key is not indexed).
pub fn write_block_to_dir(
    dir: &Path,
    kvb: u32,
    key: SpillKey,
    generation: u64,
    kv_bytes: &[u8],
    recurrent_state: Option<&[u8]>,
    refuse_existing: bool,
) -> RawDiskWrite {
    let state_slice = recurrent_state.unwrap_or(&[]);
    let total_bytes = (SPILL_HEADER_LEN as u64)
        .saturating_add(kv_bytes.len() as u64)
        .saturating_add(state_slice.len() as u64);
    let final_path = dir.join(key.blk_filename());
    if refuse_existing {
        // A case-insensitive filesystem can resolve a canonical block path to an
        // unrelated, noncanonical filename deliberately left out of the index.
        match fs::symlink_metadata(&final_path) {
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return RawDiskWrite { result: Err(e), elapsed_us: 0 },
            Ok(_) => {
                let e = io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!("unindexed file at {}", final_path.display()),
                );
                return RawDiskWrite { result: Err(e), elapsed_us: 0 };
            }
        }
    }
    let header = encode_header(key, kvb, generation, kv_bytes, recurrent_state);
    let pid = std::process::id();
    let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
    let tmp_path = dir.join(key.tmp_filename(pid, nonce));

    let write_began = std::time::Instant::now();
    let write_result = (|| -> io::Result<()> {
        let mut opts = OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
        }
        let mut file = opts.open(&tmp_path)?;
        #[cfg(unix)]
        {
            // Enforce strict 0600 even under permissive umasks.
            file.set_permissions(fs::Permissions::from_mode(0o600))?;
        }
        enable_nocache(&file);
        file.write_all(&header)?;
        if std::env::var("INKY_SERVE_ALLOW_FAULT_INJECTION").as_deref() == Ok("1") {
            if let Some(marker) = std::env::var_os("INKY_TEST_SPILL_PAUSE_MID_WRITE") {
                let marker_path = Path::new(&marker);
                if !marker_path.exists() {
                    let _ = file.flush();
                    let _ = fs::write(marker_path, tmp_path.to_string_lossy().as_bytes());
                    std::thread::sleep(std::time::Duration::from_millis(800));
                }
            }
        }
        file.write_all(kv_bytes)?;
        if !state_slice.is_empty() {
            file.write_all(state_slice)?;
        }
        file.sync_all()?;
        drop(file);
        fs::rename(&tmp_path, &final_path)?;
        fsync_dir(dir)?;
        Ok(())
    })();
    let elapsed_us = write_began.elapsed().as_micros().min(u128::from(u64::MAX)) as u64;
    if let Err(e) = write_result {
        let _ = fs::remove_file(&tmp_path);
        return RawDiskWrite { result: Err(e), elapsed_us };
    }
    RawDiskWrite { result: Ok(total_bytes), elapsed_us }
}

/// Standalone unlink of one block's file inside `dir` (`true` when a file was removed). Safe on the spill writer
/// thread; the index entry is already gone ([`SpillStore::forget_block_owing_unlink`]).
pub fn unlink_block_in_dir(dir: &Path, key: SpillKey) -> io::Result<bool> {
    unlink_if_present(&dir.join(key.blk_filename()))
}

/// Standalone crash-safe atomic write of `spill-index.bin` inside `dir` (`0600`, `O_NOFOLLOW`, `fsync`, `rename`,
/// dir `fsync`). Safe on the spill writer thread.
pub fn write_index_to_dir(dir: &Path, bytes: &[u8]) -> io::Result<()> {
    let final_path = dir.join(SPILL_INDEX_FILENAME);
    let pid = std::process::id();
    let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
    let tmp_path = dir.join(format!("{SPILL_INDEX_TMP_PREFIX}{pid:08x}.{nonce:016x}"));
    let res = (|| -> io::Result<()> {
        let mut opts = OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            opts.mode(0o600).custom_flags(libc::O_NOFOLLOW);
        }
        let mut file = opts.open(&tmp_path)?;
        #[cfg(unix)]
        {
            file.set_permissions(fs::Permissions::from_mode(0o600))?;
        }
        file.write_all(bytes)?;
        file.sync_all()?;
        drop(file);
        fs::rename(&tmp_path, &final_path)?;
        fsync_dir(dir)?;
        Ok(())
    })();
    if res.is_err() {
        let _ = fs::remove_file(&tmp_path);
    }
    res
}

/// Result of reading and SHA-256-verifying a single `.blk` file without holding `&mut SpillStore`.
#[derive(Debug)]
pub struct RawDiskRead {
    pub outcome: ReadOutcome,
    pub observed_file_len: Option<u64>,
    pub is_corrupt: bool,
    pub elapsed_us: u64,
}

/// Standalone `pread` + SHA-256 verification of a `.blk` file inside `dir`.
/// Safe to execute on a background restore worker thread without blocking the scheduler.
pub fn read_block_from_dir(
    dir: &Path,
    kvb: u32,
    key: SpillKey,
    expected_kv_len: Option<usize>,
) -> RawDiskRead {
    let began = std::time::Instant::now();
    let mut raw = read_block_from_dir_inner(dir, kvb, key, expected_kv_len);
    raw.elapsed_us = began.elapsed().as_micros().min(u128::from(u64::MAX)) as u64;
    raw
}

fn read_block_from_dir_inner(
    dir: &Path,
    kvb: u32,
    key: SpillKey,
    expected_kv_len: Option<usize>,
) -> RawDiskRead {
    #[cfg(test)]
    super::run_test_spill_read_hook(dir, key);

    let path = dir.join(key.blk_filename());
    let mut opts = OpenOptions::new();
    opts.read(true);
    #[cfg(unix)]
    {
        opts.custom_flags(libc::O_NOFOLLOW);
    }
    let file = match opts.open(&path) {
        Ok(f) => f,
        Err(e) => {
            #[cfg(unix)]
            if e.raw_os_error() == Some(libc::ELOOP) {
                return RawDiskRead {
                    outcome: ReadOutcome::Miss(MissReason::NotRegularFile),
                    observed_file_len: None,
                    is_corrupt: true,
                    elapsed_us: 0,
                };
            }
            let reason = if e.kind() == io::ErrorKind::NotFound {
                MissReason::NotFound
            } else {
                MissReason::IoReadError
            };
            return RawDiskRead {
                outcome: ReadOutcome::Miss(reason),
                observed_file_len: None,
                is_corrupt: false,
                elapsed_us: 0,
            };
        }
    };

    enable_nocache(&file);

    let meta = match file.metadata() {
        Ok(m) => m,
        Err(_) => {
            return RawDiskRead {
                outcome: ReadOutcome::Miss(MissReason::IoReadError),
                observed_file_len: None,
                is_corrupt: true,
                    elapsed_us: 0,
            };
        }
    };
    if !meta.is_file() {
        return RawDiskRead {
            outcome: ReadOutcome::Miss(MissReason::NotRegularFile),
            observed_file_len: None,
            is_corrupt: true,
                    elapsed_us: 0,
        };
    }
    let file_len = meta.len();
    let miss_corrupt = |reason: MissReason| RawDiskRead {
        outcome: ReadOutcome::Miss(reason),
        observed_file_len: Some(file_len),
        is_corrupt: true,
                    elapsed_us: 0,
    };
    if file_len < SPILL_HEADER_LEN as u64 {
        return miss_corrupt(MissReason::TruncatedHeader);
    }

    let mut header = [0u8; SPILL_HEADER_LEN];
    if pread_exact(&file, &mut header, 0).is_err() {
        return miss_corrupt(MissReason::TruncatedHeader);
    }
    if header[0..8] != SPILL_MAGIC {
        return miss_corrupt(MissReason::BadMagic);
    }
    let version = u32::from_le_bytes(header[8..12].try_into().unwrap());
    if version != SPILL_FORMAT_VERSION {
        return miss_corrupt(MissReason::UnsupportedVersion);
    }
    let raw_kind = u32::from(u16::from_le_bytes(header[12..14].try_into().unwrap()));
    let Some(kind) = SpillBlockKind::from_u32(raw_kind) else {
        return miss_corrupt(MissReason::BadBlockKind);
    };
    let file_kvb = u32::from(u16::from_le_bytes(header[14..16].try_into().unwrap()));
    if file_kvb != kvb {
        return miss_corrupt(MissReason::KvbMismatch);
    }
    let block_id = u64::from_le_bytes(header[16..24].try_into().unwrap());
    if kind != key.kind || block_id != key.id {
        return miss_corrupt(MissReason::MetadataMismatch);
    }
    let generation = u64::from_le_bytes(header[24..32].try_into().unwrap());
    let kv_len_u64 = u64::from_le_bytes(header[32..40].try_into().unwrap());
    let state_len_u64 = u64::from_le_bytes(header[40..48].try_into().unwrap());
    let stored_digest: [u8; 32] = header[48..80].try_into().unwrap();

    let (Ok(kv_len), Ok(state_len)) = (usize::try_from(kv_len_u64), usize::try_from(state_len_u64)) else {
        return miss_corrupt(MissReason::PayloadTooLarge);
    };
    if kv_len > MAX_KV_PAYLOAD_BYTES || state_len > MAX_RECURRENT_STATE_BYTES {
        return miss_corrupt(MissReason::PayloadTooLarge);
    }
    if let Some(exp) = expected_kv_len {
        if kv_len != exp {
            return miss_corrupt(MissReason::LengthMismatch);
        }
    }
    let expected_file_len = (SPILL_HEADER_LEN as u64)
        .checked_add(kv_len_u64)
        .and_then(|v| v.checked_add(state_len_u64));
    if expected_file_len != Some(file_len) {
        return miss_corrupt(MissReason::SizeMismatch);
    }

    let mut kv_bytes = vec![0u8; kv_len];
    if kv_len > 0 && pread_exact(&file, &mut kv_bytes, SPILL_HEADER_LEN as u64).is_err() {
        return miss_corrupt(MissReason::IoReadError);
    }

    let recurrent_state = if state_len > 0 {
        let mut st = vec![0u8; state_len];
        let st_off = (SPILL_HEADER_LEN as u64).saturating_add(kv_len_u64);
        if pread_exact(&file, &mut st, st_off).is_err() {
            return miss_corrupt(MissReason::IoReadError);
        }
        Some(st)
    } else {
        None
    };

    let mut hasher = Sha256::new();
    hasher.update(&header[0..HEADER_PREFIX_LEN]);
    hasher.update(&kv_bytes);
    if let Some(st) = &recurrent_state {
        hasher.update(st);
    }
    let computed = hasher.finalize();
    if !ct_eq_32(&computed, &stored_digest) {
        return miss_corrupt(MissReason::ChecksumMismatch);
    }

    RawDiskRead {
        outcome: ReadOutcome::Hit(RestoredBlock {
            key,
            generation,
            kv_bytes,
            recurrent_state,
        }),
        observed_file_len: Some(file_len),
        is_corrupt: false,
                elapsed_us: 0,
    }
}

pub(super) fn prepare_spill_dir(dir: &Path) -> Result<(), SpillError> {
    match fs::symlink_metadata(dir) {
        Ok(meta) => {
            if meta.file_type().is_symlink() {
                return Err(SpillError::InvalidDir(format!(
                    "{} must not be a symlink",
                    dir.display()
                )));
            }
            if !meta.is_dir() {
                return Err(SpillError::InvalidDir(format!(
                    "{} exists and is not a directory",
                    dir.display()
                )));
            }
            #[cfg(unix)]
            {
                let mode = meta.mode() & 0o777;
                if mode != 0o700 {
                    fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
                }
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            let mut builder = fs::DirBuilder::new();
            builder.recursive(true);
            #[cfg(unix)]
            {
                builder.mode(0o700);
            }
            builder.create(dir)?;
            #[cfg(unix)]
            {
                fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
            }
        }
        Err(e) => return Err(SpillError::Io(e)),
    }
    Ok(())
}