inky-engine 3.0.1

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
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
use super::{store::prepare_spill_dir, *};
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// RAII scratch test directory created under `target/spill-tests/` (never `/tmp`).
struct ScratchTestDir {
    path: PathBuf,
}

impl ScratchTestDir {
    fn new(label: &str) -> Self {
        let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("target")
            .join("spill-tests");
        fs::create_dir_all(&base).expect("create target/spill-tests");
        #[cfg(unix)]
        let _ = fs::set_permissions(&base, fs::Permissions::from_mode(0o700));
        let nonce = TEMP_NONCE.fetch_add(1, Ordering::Relaxed);
        let path = base.join(format!("{label}-{}-{nonce}", std::process::id()));
        let _ = fs::remove_dir_all(&path);
        fs::create_dir_all(&path).expect("create scratch test dir");
        #[cfg(unix)]
        fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
            .expect("chmod 0700 scratch test dir");
        Self { path }
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

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

fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        use std::fmt::Write;
        let _ = write!(&mut s, "{b:02x}");
    }
    s
}

#[test]
fn fresh_checkpoint_keys_skip_existing_blocks_after_restart() {
    let scratch = ScratchTestDir::new("restart-ids");
    let mut first = SpillStore::open(scratch.path(), 1024).unwrap();
    let old = first.fresh_key(SpillBlockKind::Full);
    first.write_block(old, 1, b"old KV", None, &HashSet::new()).unwrap();
    drop(first);

    let mut next = SpillStore::open(scratch.path(), 1024).unwrap();
    let fresh = next.fresh_key(SpillBlockKind::Full);
    assert_ne!(old, fresh);
    assert!(!next.contains(fresh));
    next.write_block(fresh, 1, b"new KV", None, &HashSet::new()).unwrap();
    assert!(matches!(next.read_block(old, None), ReadOutcome::Hit(b) if b.kv_bytes == b"old KV"));
    assert!(matches!(next.read_block(fresh, None), ReadOutcome::Hit(b) if b.kv_bytes == b"new KV"));
}

#[test]
fn blocks_from_before_the_v2_0_3_format_are_refused_on_reopen() {
    // v2.0.3 changed --exact's prefill arithmetic, so a block written by v2.0.2 (format 2) must never be restored.
    assert_eq!(SPILL_FORMAT_VERSION, 3);
    let scratch = ScratchTestDir::new("old-format");
    let mut first = SpillStore::open(scratch.path(), 1 << 20).unwrap();
    let old = first.fresh_key(SpillBlockKind::Full);
    first.write_block(old, 1, b"v2.0.2 KV", None, &HashSet::new()).unwrap();
    let current = first.fresh_key(SpillBlockKind::Full);
    first.write_block(current, 1, b"v2.0.3 KV", None, &HashSet::new()).unwrap();
    let old_path = first.block_path(old);
    drop(first);
    let mut raw = fs::read(&old_path).unwrap();
    raw[8..12].copy_from_slice(&2u32.to_le_bytes());
    fs::write(&old_path, &raw).unwrap();

    let mut next = SpillStore::open(scratch.path(), 1 << 20).unwrap();
    assert_eq!(next.read_block(old, None), ReadOutcome::Miss(MissReason::UnsupportedVersion));
    assert!(!old_path.exists(), "a block in an older format must be removed, not kept for a later restore");
    assert!(matches!(next.read_block(current, None), ReadOutcome::Hit(b) if b.kv_bytes == b"v2.0.3 KV"));
}

#[test]
fn dropping_the_store_releases_ownership_even_with_a_duplicate_fd() {
    let scratch = ScratchTestDir::new("directory-lock-lifetime");
    let owner = SpillStore::open(scratch.path(), 1024).unwrap();
    // A child between fork and exec holds another descriptor for the same open file.
    let inherited = owner.clone_directory_lock().unwrap();
    drop(owner);
    let successor = SpillStore::open(scratch.path(), 1024).unwrap();
    drop(inherited);
    assert!(SpillStore::open(scratch.path(), 1024).is_err());
    drop(successor);
}

#[test]
fn one_process_owns_the_spill_directory_until_drop() {
    const CHILD_DIR: &str = "INKY_TEST_CONTENDED_SPILL_DIR";
    if let Some(dir) = std::env::var_os(CHILD_DIR) {
        // A second opener must fail before a zero-byte budget can evict the writer's blocks.
        let result = SpillStore::open(&dir, 0);
        match result {
            Err(e @ SpillError::DirectoryLocked(_)) => {
                assert!(e.to_string().contains("already in use"), "{e}");
            }
            other => panic!("expected Err(SpillError::DirectoryLocked), got {}", other.err().map(|e| e.to_string()).unwrap_or_else(|| "Ok".into())),
        }
        return;
    }

    let scratch = ScratchTestDir::new("directory-owner");
    let dir = scratch.path();
    let mut owner = SpillStore::open(dir, 1024).unwrap();
    let key = SpillKey::full(37);
    owner.write_block(key, 1, b"retained", None, &HashSet::new()).unwrap();
    let child = Command::new(std::env::current_exe().unwrap())
        .args(["--exact", "spill::tests::one_process_owns_the_spill_directory_until_drop"])
        .env(CHILD_DIR, dir)
        .output().unwrap();
    assert!(child.status.success(), "{}", String::from_utf8_lossy(&child.stdout));
    drop(owner);

    let mut successor = SpillStore::open(dir, 1024).unwrap();
    assert!(matches!(successor.read_block(key, None), ReadOutcome::Hit(block) if block.kv_bytes == b"retained"));
}

/// Deterministic ground-truth generator for block K/V bytes and optional recurrent state.
fn deterministic_kv(key: SpillKey, len: usize) -> Vec<u8> {
    let mut x = key.id.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ ((key.kind as u64 + 1) << 56) ^ 0xa076_1d64_78bd_642f;
    let mut out = vec![0u8; len];
    for chunk in out.chunks_mut(8) {
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        let v = x.wrapping_mul(0x2545_f491_4f6c_dd1d).to_le_bytes();
        let n = chunk.len();
        chunk.copy_from_slice(&v[..n]);
    }
    out
}

fn deterministic_state(key: SpillKey, len: usize) -> Vec<u8> {
    let mut x = key.id.wrapping_mul(0xd1b5_4a32_d192_ed03) ^ 0x55aa_33cc_9966_11ee;
    let mut out = vec![0u8; len];
    for chunk in out.chunks_mut(8) {
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        let v = x.wrapping_mul(0x94d0_49bb_1331_11eb).to_le_bytes();
        let n = chunk.len();
        chunk.copy_from_slice(&v[..n]);
    }
    out
}

#[test]
fn sha256_matches_nist_vectors() {
    let h_empty = Sha256::new().finalize();
    assert_eq!(
        hex(&h_empty),
        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
    );

    let mut h_abc = Sha256::new();
    h_abc.update(b"abc");
    assert_eq!(
        hex(&h_abc.finalize()),
        "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
    );

    let mut h_448 = Sha256::new();
    h_448.update(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq");
    assert_eq!(
        hex(&h_448.finalize()),
        "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
    );

    // Streaming chunked equivalence on 128 KiB payload.
    let payload = deterministic_kv(SpillKey::full(42), 131_072);
    let mut whole = Sha256::new();
    whole.update(&payload);
    let mut chunked = Sha256::new();
    for c in payload.chunks(137) {
        chunked.update(c);
    }
    assert_eq!(whole.finalize(), chunked.finalize());
}

#[cfg(unix)]
#[test]
fn spill_dir_and_files_have_strict_unix_permissions() {
    let scratch = ScratchTestDir::new("perms");
    let dir = scratch.path().join("spill");
    let mut store = SpillStore::open(&dir, 1024 * 1024).unwrap();
    let dir_mode = fs::symlink_metadata(&dir).unwrap().mode() & 0o777;
    assert_eq!(dir_mode, 0o700, "spill dir must be mode 0700");

    let key = SpillKey::full(7);
    let kv = deterministic_kv(key, 4096);
    let (outcome, _) = store.write_block(key, 1, &kv, None, &HashSet::new()).unwrap();
    assert!(matches!(outcome, WriteOutcome::Written { .. }));
    let file_mode = fs::symlink_metadata(store.block_path(key)).unwrap().mode() & 0o777;
    assert_eq!(file_mode, 0o600, "spilled .blk files must be mode 0600");
}

#[test]
fn lazy_lru_spill_never_writes_eagerly_and_evicts_strict_lru_under_pressure() {
    let scratch = ScratchTestDir::new("lazy-lru");
    let dir = scratch.path().join("spill");
    let full_stride = 4096;
    let win_stride = 8192;
    let pool = HostBlockPoolBackend::new(4, 2, full_stride, win_stride);
    let store = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();
    let mut mgr = SpillManager::new(pool, store);

    // Allocate, fill, seal, and pin 4 full blocks (fills 100% of Full pool).
    let mut slots = Vec::new();
    for id in 0..4u64 {
        let key = SpillKey::full(id);
        let slot = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
        let kv = deterministic_kv(key, full_stride);
        mgr.pool_mut().write_and_seal(slot, &kv).unwrap();
        let state = if id == 2 { Some(deterministic_state(key, 1024)) } else { None };
        mgr.register_sealed_block(key, slot, state).unwrap();
        mgr.pin(key).unwrap();
        slots.push((key, slot));
    }

    // LAZY INVARIANT: 0 disk writes while filling memory pool.
    assert_eq!(mgr.store().stats().writes_committed, 0);
    assert_eq!(mgr.store().entry_count(), 0);

    // Unpin all 4 blocks in an explicit recency order:
    // oldest -> newest: id 2, id 0, id 3, id 1.
    for id in [2u64, 0, 3, 1] {
        assert_eq!(mgr.unpin(SpillKey::full(id)).unwrap(), 0);
    }
    // Re-pin id 0 so it CANNOT be evicted even though it is older than 3 and 1.
    mgr.pin(SpillKey::full(0)).unwrap();

    // LAZY INVARIANT: dropping refs to 0 still triggers ZERO disk writes!
    assert_eq!(mgr.store().stats().writes_committed, 0);
    assert_eq!(mgr.store().entry_count(), 0);
    for id in 0..4u64 {
        assert_eq!(mgr.tier(SpillKey::full(id)), BlockTier::Memory);
    }

    // Now request a 5th full block -> memory pressure!
    // Must evict id 2 (oldest unreferenced) ONLY, writing its K/V + recurrent state.
    let k4 = SpillKey::full(4);
    let s4 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(s4, &deterministic_kv(k4, full_stride)).unwrap();
    mgr.register_sealed_block(k4, s4, None).unwrap();
    mgr.pin(k4).unwrap();

    assert_eq!(mgr.stats().lazy_spills_written, 1);
    assert_eq!(mgr.tier(SpillKey::full(2)), BlockTier::Disk);
    assert_eq!(mgr.tier(SpillKey::full(0)), BlockTier::Memory); // pinned!
    assert_eq!(mgr.tier(SpillKey::full(3)), BlockTier::Memory);
    assert_eq!(mgr.tier(SpillKey::full(1)), BlockTier::Memory);

    // Request a 6th full block -> must evict id 3 (NOT pinned id 0, NOT newer id 1).
    let k5 = SpillKey::full(5);
    let s5 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(s5, &deterministic_kv(k5, full_stride)).unwrap();
    mgr.register_sealed_block(k5, s5, None).unwrap();
    mgr.pin(k5).unwrap();

    assert_eq!(mgr.stats().lazy_spills_written, 2);
    assert_eq!(mgr.tier(SpillKey::full(3)), BlockTier::Disk);
    assert_eq!(mgr.tier(SpillKey::full(0)), BlockTier::Memory);
    assert_eq!(mgr.tier(SpillKey::full(1)), BlockTier::Memory);

    // Restore id 2 (a start point with recurrent state) -> must evict id 1,
    // read id 2 from SSD, and recover bit-identical K/V + recurrent state!
    let prepared = mgr.prepare_working_set_restore(&[SpillKey::full(2)], &[]).unwrap();
    let restored = mgr.execute_working_set_restore(prepared).unwrap();
    assert_eq!(restored.full_slots.len(), 1);
    let (rk, rslot) = restored.full_slots[0];
    assert_eq!(rk, SpillKey::full(2));
    assert_eq!(
        mgr.pool().read_slot_bytes(rslot).unwrap(),
        deterministic_kv(SpillKey::full(2), full_stride).as_slice()
    );
    assert_eq!(
        restored.recurrent_states.get(&SpillKey::full(2)).map(Vec::as_slice),
        Some(deterministic_state(SpillKey::full(2), 1024).as_slice())
    );
    assert_eq!(mgr.tier(SpillKey::full(2)), BlockTier::Both);
    assert_eq!(mgr.tier(SpillKey::full(1)), BlockTier::Disk);

    // Unpin id 2 and trigger one more eviction: because id 2 is already `Both`
    // (clean copy on disk), evicting it again must NOT rewrite to SSD!
    mgr.unpin(SpillKey::full(2)).unwrap();
    let writes_before = mgr.store().stats().writes_committed;
    let _s6 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    assert_eq!(mgr.store().stats().writes_committed, writes_before);
    assert_eq!(mgr.stats().clean_mem_evictions, 1);
    assert_eq!(mgr.tier(SpillKey::full(2)), BlockTier::Disk);
}

#[test]
fn failed_unlink_preserves_budget_and_gc_skips_the_stuck_victim() {
    let scratch = ScratchTestDir::new("unlink-budget");
    let charge = (SPILL_HEADER_LEN + 4) as u64;
    let mut store = SpillStore::open(scratch.path().join("spill"), 2 * charge).unwrap();
    let keys = [1, 2, 3, 4].map(SpillKey::full);
    let unprotected = HashSet::new();
    for &key in &keys[..2] {
        store.write_block(key, 1, b"data", None, &unprotected).unwrap();
    }

    // Preserve the original bytes under a directory that remove_file cannot unlink,
    // including when this test runs with elevated filesystem permissions.
    let path = store.block_path(keys[0]);
    let saved = scratch.path().join("saved");
    fs::rename(&path, &saved).unwrap();
    fs::create_dir(&path).unwrap();
    fs::rename(&saved, path.join("original")).unwrap();
    assert!(!store.remove_block(keys[0]));
    assert!(matches!(store.read_block(keys[0], None), ReadOutcome::Miss(_)));
    assert_eq!(store.stats().corrupt_files_removed, 0);
    assert!(store.contains(keys[0]));
    assert_eq!(store.used_bytes(), 2 * charge);

    let (outcome, victims) = store.write_block(keys[2], 1, b"data", None, &unprotected).unwrap();
    assert_eq!(outcome, WriteOutcome::Written { on_disk_bytes: charge });
    assert_eq!(victims, vec![keys[1]]);
    let (outcome, victims) = store.write_block(keys[3], 1, b"data", None, &HashSet::from([keys[2]])).unwrap();
    assert_eq!(outcome, WriteOutcome::OverBudget);
    assert!(victims.is_empty());
    assert_eq!(store.stats().disk_gc_evictions, 1);
    assert!(store.contains(keys[0]));
    assert_eq!(store.used_bytes(), 2 * charge);

    fs::rename(path.join("original"), &saved).unwrap();
    fs::remove_dir(&path).unwrap();
    fs::rename(&saved, &path).unwrap();
    assert!(store.remove_block(keys[0]));
    assert_eq!(store.used_bytes(), charge);
}

#[test]
fn startup_reports_canonical_block_it_cannot_remove() {
    let scratch = ScratchTestDir::new("startup-unlink");
    let dir = scratch.path().join("spill");
    fs::create_dir(&dir).unwrap();
    let stuck = dir.join(SpillKey::full(1).blk_filename());
    fs::create_dir(&stuck).unwrap();
    assert!(matches!(SpillStore::open(&dir, 0), Err(SpillError::Io(_))));
    assert!(stuck.is_dir());
    fs::remove_dir(stuck).unwrap();
    let store = SpillStore::open(&dir, 0).unwrap();
    assert_eq!(store.used_bytes(), 0);
}

#[test]
fn transient_open_error_retains_charge_and_absent_files_release_it_once() {
    let scratch = ScratchTestDir::new("open-accounting");
    let dir = scratch.path().join("spill");
    let charge = (SPILL_HEADER_LEN + 4) as u64;
    let mut store = SpillStore::open(&dir, 2 * charge).unwrap();
    let keys = [1, 2].map(SpillKey::full);
    for key in keys {
        store.write_block(key, 1, b"data", None, &HashSet::new()).unwrap();
    }

    let saved = scratch.path().join("saved-dir");
    fs::rename(&dir, &saved).unwrap();
    fs::write(&dir, b"temporarily inaccessible").unwrap();
    assert_eq!(store.read_block(keys[0], None), ReadOutcome::Miss(MissReason::IoReadError));
    assert_eq!(store.used_bytes(), 2 * charge);
    assert!(store.contains(keys[0]));
    fs::remove_file(&dir).unwrap();
    fs::rename(&saved, &dir).unwrap();
    assert!(matches!(store.read_block(keys[0], None), ReadOutcome::Hit(_)));

    fs::remove_file(store.block_path(keys[0])).unwrap();
    assert_eq!(store.read_block(keys[0], None), ReadOutcome::Miss(MissReason::NotFound));
    assert!(!store.remove_block(keys[0]));
    assert_eq!(store.used_bytes(), charge);
    fs::remove_file(store.block_path(keys[1])).unwrap();
    assert!(store.remove_block(keys[1]));
    assert!(!store.remove_block(keys[1]));
    assert_eq!(store.used_bytes(), 0);
}

#[test]
fn disk_budget_enforces_max_spill_bytes_with_lru_gc() {
    let scratch = ScratchTestDir::new("disk-gc");
    let dir = scratch.path().join("spill");
    let kv_len = 4096usize;
    let one_file = (SPILL_HEADER_LEN + kv_len) as u64;
    // Budget holds at most 3 spilled blocks.
    let max_bytes = one_file * 3;
    let mut store = SpillStore::open(&dir, max_bytes).unwrap();

    for id in 0..8u64 {
        let key = SpillKey::full(id);
        let kv = deterministic_kv(key, kv_len);
        let (out, _evicted) = store.write_block(key, 1, &kv, None, &HashSet::new()).unwrap();
        assert_eq!(out, WriteOutcome::Written { on_disk_bytes: one_file });
        assert!(
            store.used_bytes() <= max_bytes,
            "used_bytes {} exceeded max_bytes {}",
            store.used_bytes(),
            max_bytes
        );
        // Verify actual on-disk bytes across all files in --spill-dir also respect budget.
        let actual_bytes: u64 = fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().metadata().unwrap().len())
            .sum();
        assert!(actual_bytes <= max_bytes);
    }

    assert_eq!(store.entry_count(), 3);
    assert_eq!(store.stats().disk_gc_evictions, 5);
    // Oldest 0..5 evicted; newest 5, 6, 7 survive and verify bit-identically.
    for id in 0..5u64 {
        assert!(matches!(
            store.read_block(SpillKey::full(id), Some(kv_len)),
            ReadOutcome::Miss(MissReason::NotFound)
        ));
    }
    for id in 5..8u64 {
        let key = SpillKey::full(id);
        match store.read_block(key, Some(kv_len)) {
            ReadOutcome::Hit(blk) => assert_eq!(blk.kv_bytes, deterministic_kv(key, kv_len)),
            ReadOutcome::Miss(r) => panic!("expected surviving block {id}, got miss {r:?}"),
        }
    }

    // Touch block 5 (already touched above, now touch 6 and 7 then 5 so 6 is oldest).
    let _ = store.read_block(SpillKey::full(6), Some(kv_len));
    let _ = store.read_block(SpillKey::full(7), Some(kv_len));
    let _ = store.read_block(SpillKey::full(5), Some(kv_len));
    // Writing block 8 must evict block 6 (LRU), keeping 5, 7, 8!
    let k8 = SpillKey::full(8);
    store
        .write_block(k8, 1, &deterministic_kv(k8, kv_len), None, &HashSet::new())
        .unwrap();
    assert!(!store.contains(SpillKey::full(6)));
    assert!(store.contains(SpillKey::full(5)));
    assert!(store.contains(SpillKey::full(7)));
    assert!(store.contains(SpillKey::full(8)));

    // Zero disk budget drops cleanly without failing or writing files.
    let dir0 = scratch.path().join("spill-zero");
    let pool0 = HostBlockPoolBackend::new(1, 1, 512, 512);
    let store0 = SpillStore::open(&dir0, 0).unwrap();
    let mut mgr0 = SpillManager::new(pool0, store0);
    let s0 = mgr0.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr0.pool_mut().write_and_seal(s0, &deterministic_kv(SpillKey::full(1), 512)).unwrap();
    mgr0.register_sealed_block(SpillKey::full(1), s0, None).unwrap();
    // refs == 0 -> allocating another block drops block 1 cleanly with 0 disk usage.
    let _s1 = mgr0.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    assert_eq!(mgr0.store().used_bytes(), 0);
    assert_eq!(mgr0.tier(SpillKey::full(1)), BlockTier::None);
    assert_eq!(mgr0.stats().over_budget_mem_drops, 1);
}

#[test]
fn atomic_working_set_reservation_prevents_partial_restore_thrashing() {
    let scratch = ScratchTestDir::new("atomic-reserve");
    let dir = scratch.path().join("spill");
    let f_stride = 2048;
    let w_stride = 4096;
    // Pool holds 4 Full slots and 3 Window slots.
    let pool = HostBlockPoolBackend::new(4, 3, f_stride, w_stride);
    let mut store = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();

    // Pre-populate 6 Full blocks and 4 Window blocks on SSD (simulating spilled prefixes).
    for id in 1..=6u64 {
        let k = SpillKey::full(id);
        store.write_block(k, 1, &deterministic_kv(k, f_stride), None, &HashSet::new()).unwrap();
    }
    for id in 1..=4u64 {
        let k = SpillKey::window(id);
        store.write_block(k, 1, &deterministic_kv(k, w_stride), None, &HashSet::new()).unwrap();
    }

    let mut mgr = SpillManager::new(pool, store);
    mgr.index_existing_disk_blocks();

    // Put one cold Full block in memory (refs == 0) so we verify asymmetric WouldBlock
    // triggers ZERO spills when Window slots cannot fit!
    let cold_f = SpillKey::full(100);
    let sf = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(sf, &deterministic_kv(cold_f, f_stride)).unwrap();
    mgr.register_sealed_block(cold_f, sf, None).unwrap();

    // Request exceeding capacity returns ExceedsCapacity with zero mutations.
    assert!(matches!(
        mgr.reserve_working_set(5, 1),
        Err(ReserveError::ExceedsCapacity { .. })
    ));
    assert_eq!(mgr.tier(cold_f), BlockTier::Memory);

    // Lane A reserves (3 full, 2 window) atomically -> succeeds!
    let lane_a_full = [SpillKey::full(1), SpillKey::full(2), SpillKey::full(3)];
    let lane_a_win = [SpillKey::window(1), SpillKey::window(2)];
    let prep_a = mgr.prepare_working_set_restore(&lane_a_full, &lane_a_win).unwrap();
    assert_eq!(prep_a.reservation.full_count(), 3);
    assert_eq!(prep_a.reservation.window_count(), 2);
    // 3 free Full slots were enough without even spilling cold_f!
    assert_eq!(mgr.tier(cold_f), BlockTier::Memory);
    assert_eq!(mgr.stats().lazy_spills_written, 0);

    // Now Lane B wants (3 full, 2 window) while Lane A is in Restoring!
    // Only 1 Full (cold_f) and 1 Window remain -> MUST fail atomically with WouldBlock,
    // spilling ZERO blocks (cold_f stays untouched in Memory!) and NEVER evicting Lane A!
    let lane_b_full = [SpillKey::full(4), SpillKey::full(5), SpillKey::full(6)];
    let lane_b_win = [SpillKey::window(3), SpillKey::window(4)];
    let err_b = mgr.prepare_working_set_restore(&lane_b_full, &lane_b_win).unwrap_err();
    assert!(matches!(
        err_b,
        PrepareRestoreError::Reserve(ReserveError::WouldBlock {
            need_full: 3,
            avail_full: 1,
            need_window: 2,
            avail_window: 1,
        })
    ));
    assert_eq!(mgr.tier(cold_f), BlockTier::Memory, "WouldBlock must not spill cold_f");
    assert_eq!(mgr.stats().lazy_spills_written, 0);
    assert_eq!(mgr.stats().reservations_would_block, 1);

    // Asymmetric WouldBlock: Lane C wants (1 full, 2 window). Full fits (1 <= 1),
    // Window does NOT (2 > 1). MUST NOT spill cold_f!
    let err_c = mgr.reserve_working_set(1, 2).unwrap_err();
    assert!(matches!(err_c, ReserveError::WouldBlock { .. }));
    assert_eq!(mgr.tier(cold_f), BlockTier::Memory, "asymmetric WouldBlock must not spill Full");

    // Lane A completes its SSD reads with zero interference.
    let res_a = mgr.execute_working_set_restore(prep_a).unwrap();
    assert_eq!(res_a.full_slots.len(), 3);
    assert_eq!(res_a.window_slots.len(), 2);
    for &(k, s) in &res_a.full_slots {
        assert_eq!(mgr.pool().read_slot_bytes(s).unwrap(), deterministic_kv(k, f_stride).as_slice());
    }
    for &(k, s) in &res_a.window_slots {
        assert_eq!(mgr.pool().read_slot_bytes(s).unwrap(), deterministic_kv(k, w_stride).as_slice());
    }

    // Lane A finishes and unpins its blocks -> they stay hot in memory (`Both`, refs=0).
    for &(k, _) in res_a.full_slots.iter().chain(res_a.window_slots.iter()) {
        assert_eq!(mgr.unpin(k).unwrap(), 0);
    }

    // Now Lane B retries: its full working set fits via lazy eviction of cold blocks!
    let prep_b = mgr.prepare_working_set_restore(&lane_b_full, &lane_b_win).unwrap();
    let res_b = mgr.execute_working_set_restore(prep_b).unwrap();
    for &(k, s) in &res_b.full_slots {
        assert_eq!(mgr.pool().read_slot_bytes(s).unwrap(), deterministic_kv(k, f_stride).as_slice());
    }
    for &(k, s) in &res_b.window_slots {
        assert_eq!(mgr.pool().read_slot_bytes(s).unwrap(), deterministic_kv(k, w_stride).as_slice());
    }
}

#[test]
fn restore_never_evicts_its_own_in_memory_working_set() {
    let scratch = ScratchTestDir::new("self-pin");
    let dir = scratch.path().join("spill");
    let stride = 1024;
    // Pool has capacity 2 Full slots.
    let pool = HostBlockPoolBackend::new(2, 1, stride, stride);
    let mut store = SpillStore::open(&dir, 1024 * 1024).unwrap();
    // Two blocks on disk: full(2), full(3).
    for id in [2u64, 3] {
        let k = SpillKey::full(id);
        store.write_block(k, 1, &deterministic_kv(k, stride), None, &HashSet::new()).unwrap();
    }
    let mut mgr = SpillManager::new(pool, store);
    mgr.index_existing_disk_blocks();

    // full(1) is in memory with refs == 0, and full(99) is in memory with refs == 1 (pinned by another lane).
    let k1 = SpillKey::full(1);
    let s1 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(s1, &deterministic_kv(k1, stride)).unwrap();
    mgr.register_sealed_block(k1, s1, None).unwrap();

    let k99 = SpillKey::full(99);
    let s99 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(s99, &deterministic_kv(k99, stride)).unwrap();
    mgr.register_sealed_block(k99, s99, None).unwrap();
    mgr.pin(k99).unwrap();

    // A lane wants working set [full(1) (in memory, refs=0), full(2) (on disk)].
    // Total slots needed = 2, but full(99) holds 1 slot -> MUST WouldBlock and MUST NOT
    // spill full(1) to make room for full(2)!
    let err = mgr.prepare_working_set_restore(&[k1, SpillKey::full(2)], &[]).unwrap_err();
    assert!(matches!(err, PrepareRestoreError::Reserve(ReserveError::WouldBlock { .. })));
    assert_eq!(mgr.tier(k1), BlockTier::Memory);
    assert_eq!(mgr.pool().refs(s1).unwrap(), 0, "failed prepare must unpin full(1)");

    // Once full(99) unpins, [full(1), full(2)] succeeds by spilling full(99), keeping full(1) resident!
    mgr.unpin(k99).unwrap();
    let prep = mgr.prepare_working_set_restore(&[k1, SpillKey::full(2)], &[]).unwrap();
    let res = mgr.execute_working_set_restore(prep).unwrap();
    assert_eq!(res.full_slots.len(), 2);
    assert_eq!(mgr.tier(k1), BlockTier::Memory);
    assert_eq!(mgr.tier(SpillKey::full(2)), BlockTier::Both);
    assert_eq!(mgr.tier(k99), BlockTier::Disk);
}

#[test]
fn publication_preserves_an_unindexed_file_at_the_destination() {
    let scratch = ScratchTestDir::new("unindexed-destination");
    let mut store = SpillStore::open(scratch.path(), 4096).unwrap();
    let key = SpillKey::full(0xab);
    let destination = store.block_path(key);
    fs::write(&destination, b"keep").unwrap();
    let result = store.write_block(key, 1, b"new KV", None, &HashSet::new());
    assert!(matches!(result, Err(SpillError::Io(err)) if err.kind() == io::ErrorKind::AlreadyExists));
    assert_eq!(fs::read(&destination).unwrap(), b"keep");
    assert_eq!(store.entry_count(), 0);
}

#[test]
fn spill_file_names_require_canonical_lowercase_hex_fields() {
    for key in [SpillKey::full(0), SpillKey::window(u64::MAX)] {
        assert_eq!(SpillKey::parse_blk_filename(&key.blk_filename()), Some(key));
        assert_eq!(SpillKey::parse_tmp_filename(&key.tmp_filename(u32::MAX, u64::MAX)), Some(key));
    }
    for name in ["blk-f-00000000000000AB.blk", "blk-f-+000000000000001.blk"] {
        assert_eq!(SpillKey::parse_blk_filename(name), None, "{name}");
    }
    for name in [
        "blk-f-0000000000000001.tmp.0000000A.0000000000000001",
        "blk-f-0000000000000001.tmp.00000001.000000000000000A",
    ] {
        assert_eq!(SpillKey::parse_tmp_filename(name), None, "{name}");
    }
}

#[test]
fn corrupt_torn_bitflip_zero_and_orphan_files_cause_clean_cache_miss_never_corruption() {
    let scratch = ScratchTestDir::new("corruption");
    let dir = scratch.path().join("spill");
    let kv_len = 2048usize;
    let state_len = 512usize;

    // Only a spill writer's exact temporary names are eligible for cleanup.
    prepare_spill_dir(&dir).unwrap();
    let orphan1 = dir.join(SpillKey::full(1).tmp_filename(0x1234, 1));
    let orphan2 = dir.join(SpillKey::window(0x99).tmp_filename(0x5678, 2));
    fs::write(&orphan1, b"half-written-tmp-data").unwrap();
    fs::write(&orphan2, b"").unwrap();
    let unrelated = [
        "notes.tmp.backup",
        "blk-x-0000000000000001.tmp.00001234.0000000000000001",
        "blk-f-00000000000000AB.tmp.00001234.0000000000000001",
        "blk-f-0000000000000001.tmp.1234.0000000000000001",
        "blk-f-0000000000000001.tmp.00001234.000000000000000g",
        "blk-f-0000000000000001.tmp.00001234.0000000000000001.bak",
    ];
    for name in unrelated {
        fs::write(dir.join(name), b"keep").unwrap();
    }

    let mut store = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();
    assert_eq!(store.stats().orphans_swept, 2);
    assert!(!orphan1.exists());
    assert!(!orphan2.exists());
    for name in unrelated {
        assert_eq!(fs::read(dir.join(name)).unwrap(), b"keep", "{name}");
    }

    let write_good = |s: &mut SpillStore, id: u64| -> (SpillKey, PathBuf) {
        let key = SpillKey::full(id);
        let kv = deterministic_kv(key, kv_len);
        let st = deterministic_state(key, state_len);
        s.write_block(key, 3, &kv, Some(&st), &HashSet::new()).unwrap();
        let p = s.block_path(key);
        (key, p)
    };

    // 1. Zero-byte .blk file.
    let (k1, p1) = write_good(&mut store, 1);
    fs::write(&p1, b"").unwrap();
    assert_eq!(store.read_block(k1, Some(kv_len)), ReadOutcome::Miss(MissReason::TruncatedHeader));
    assert!(!p1.exists(), "corrupt file should be unlinked");

    // 2. Truncated header (40 bytes).
    let (k2, p2) = write_good(&mut store, 2);
    let raw = fs::read(&p2).unwrap();
    fs::write(&p2, &raw[..40]).unwrap();
    assert_eq!(store.read_block(k2, Some(kv_len)), ReadOutcome::Miss(MissReason::TruncatedHeader));

    // 3. Torn K/V payload (1 byte short & half-written).
    let (k3, p3) = write_good(&mut store, 3);
    let raw = fs::read(&p3).unwrap();
    fs::write(&p3, &raw[..SPILL_HEADER_LEN + kv_len / 2]).unwrap();
    assert_eq!(store.read_block(k3, Some(kv_len)), ReadOutcome::Miss(MissReason::SizeMismatch));

    // 4. Torn recurrent state (1 byte short).
    let (k4, p4) = write_good(&mut store, 4);
    let raw = fs::read(&p4).unwrap();
    fs::write(&p4, &raw[..raw.len() - 1]).unwrap();
    assert_eq!(store.read_block(k4, Some(kv_len)), ReadOutcome::Miss(MissReason::SizeMismatch));

    // 5. Trailing garbage appended.
    let (k5, p5) = write_good(&mut store, 5);
    let mut raw = fs::read(&p5).unwrap();
    raw.push(0xAA);
    fs::write(&p5, &raw).unwrap();
    assert_eq!(store.read_block(k5, Some(kv_len)), ReadOutcome::Miss(MissReason::SizeMismatch));

    // 6. Single-bit flips across header, digest, K/V payload, and recurrent state.
    let flip_offsets = [
        (0usize, MissReason::BadMagic),
        (8, MissReason::UnsupportedVersion),
        (12, MissReason::BadBlockKind),
        (14, MissReason::KvbMismatch),
        (16, MissReason::MetadataMismatch),
        (24, MissReason::ChecksumMismatch), // generation bit-flip
        (48, MissReason::ChecksumMismatch), // sha256 byte flip
        (SPILL_HEADER_LEN, MissReason::ChecksumMismatch), // first K/V byte
        (SPILL_HEADER_LEN + kv_len / 2, MissReason::ChecksumMismatch), // mid K/V byte
        (SPILL_HEADER_LEN + kv_len - 1, MissReason::ChecksumMismatch), // last K/V byte
        (SPILL_HEADER_LEN + kv_len + state_len / 2, MissReason::ChecksumMismatch), // recurrent state byte
    ];
    for (i, &(off, expected_reason)) in flip_offsets.iter().enumerate() {
        let (k, p) = write_good(&mut store, 100 + i as u64);
        let mut raw = fs::read(&p).unwrap();
        raw[off] ^= 0x04;
        fs::write(&p, &raw).unwrap();
        assert_eq!(
            store.read_block(k, Some(kv_len)),
            ReadOutcome::Miss(expected_reason),
            "bit flip at offset {off} must return {expected_reason:?}"
        );
        assert!(!p.exists(), "corrupt file at offset {off} must be unlinked");
    }

    // 7. File-swap attack: copy valid block 200 over block 201.
    let (k200, p200) = write_good(&mut store, 200);
    let (k201, p201) = write_good(&mut store, 201);
    fs::copy(&p200, &p201).unwrap();
    assert_eq!(store.read_block(k201, Some(kv_len)), ReadOutcome::Miss(MissReason::MetadataMismatch));
    // Original block 200 remains intact.
    match store.read_block(k200, Some(kv_len)) {
        ReadOutcome::Hit(blk) => {
            assert_eq!(blk.kv_bytes, deterministic_kv(k200, kv_len));
            assert_eq!(blk.recurrent_state, Some(deterministic_state(k200, state_len)));
        }
        ReadOutcome::Miss(r) => panic!("block 200 should be intact, got {r:?}"),
    }

    // 8. End-to-end SpillManager rollback on corrupt block in multi-block working set:
    //    pool slots must remain completely clean (zero-filled, zero leaks)!
    let pool = HostBlockPoolBackend::new(3, 1, kv_len, kv_len);
    drop(store);
    let store2 = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();
    let mut mgr = SpillManager::new(pool, store2);
    // Write two blocks via store and corrupt the second.
    let ka = SpillKey::full(300);
    let kb = SpillKey::full(301);
    mgr.store.write_block(ka, 1, &deterministic_kv(ka, kv_len), None, &HashSet::new()).unwrap();
    mgr.store.write_block(kb, 1, &deterministic_kv(kb, kv_len), None, &HashSet::new()).unwrap();
    let pb = mgr.store.block_path(kb);
    let mut raw_b = fs::read(&pb).unwrap();
    raw_b[SPILL_HEADER_LEN + 7] ^= 0x80;
    fs::write(&pb, &raw_b).unwrap();
    mgr.index_existing_disk_blocks();

    let prep = mgr.prepare_working_set_restore(&[ka, kb], &[]).unwrap();
    let miss = mgr.execute_working_set_restore(prep).unwrap_err();
    assert_eq!(miss.failed_key, kb);
    assert_eq!(miss.reason, MissReason::ChecksumMismatch);
    // Zero leaked slots, zero active reservations, and every pool slot is zeroed!
    assert_eq!(mgr.active_reservation_count(), 0);
    assert_eq!(mgr.pool().used_slots(SpillBlockKind::Full), 0);
    assert_eq!(mgr.pool().free_slots(SpillBlockKind::Full), 3);
    for slot_i in 1..=3u32 {
        assert!(
            mgr.pool().raw_slot_bytes(SpillBlockKind::Full, slot_i).iter().all(|&b| b == 0),
            "slot {slot_i} must remain zero-filled after corrupt-block rollback"
        );
    }
}

/// Child helper mode spawned by [`kill9_mid_write_loses_cache_never_correctness`].
/// Marked `#[ignore]` so normal `cargo test` runs do not invoke it directly;
/// returns immediately if `INKY_SPILL_KILL9_DIR` is unset.
#[test]
#[ignore = "internal child helper spawned by kill9_mid_write_loses_cache_never_correctness"]
fn kill9_writer_helper() {
    let Ok(dir) = std::env::var("INKY_SPILL_KILL9_DIR") else {
        return;
    };
    let round: u64 = std::env::var("INKY_SPILL_KILL9_ROUND")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(0);
    let kv_len: usize = std::env::var("INKY_SPILL_KILL9_KV_LEN")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(256 * 1024);
    let state_len: usize = std::env::var("INKY_SPILL_KILL9_STATE_LEN")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(32 * 1024);

    let mut store = SpillStore::open(&dir, 512 * 1024 * 1024).expect("child open spill store");
    let empty = HashSet::new();

    // Write continuously until parent sends SIGKILL.
    let mut seq = 0u64;
    loop {
        let id = (round << 32) | seq;
        let kind = if seq.is_multiple_of(4) {
            SpillBlockKind::Window
        } else {
            SpillBlockKind::Full
        };
        let key = SpillKey::new(kind, id);
        let kv = deterministic_kv(key, kv_len);
        let st = if seq.is_multiple_of(3) {
            Some(deterministic_state(key, state_len))
        } else {
            None
        };
        let _ = store.write_block(key, seq + 1, &kv, st.as_deref(), &empty);
        if seq == 0 {
            println!("READY");
            let _ = io::stdout().flush();
        } else {
            println!("COMMIT {seq}");
            let _ = io::stdout().flush();
        }
        seq = seq.wrapping_add(1);
        if seq >= 500 {
            break;
        }
    }
}

/// Layer 4 Gate (`docs/ROADMAP.md:140`):
/// *"Gate: kill -9 in mid-write loses cache and never correctness"*
///
/// Spawns real writer subprocesses that continuously spill blocks to SSD while
/// the parent delivers `SIGKILL` mid-write (both targeted on observed `.tmp.*`
/// files and at staggered intervals), then verifies after every crash:
/// - 100% of orphan `.tmp.*` files are swept on recovery;
/// - 100% of surviving `.blk` files either verify SHA-256 and match ground-truth
///   K/V + recurrent state bit-for-bit, or return `CacheMiss` and fall back to
///   ground-truth recomputation with bit-identical outputs.
#[cfg(unix)]
#[test]
#[ignore = "spawns SIGKILL writer subprocesses; run explicitly in nightly unit-extras"]
fn kill9_mid_write_loses_cache_never_correctness() {
    use std::os::unix::process::ExitStatusExt;

    let scratch = ScratchTestDir::new("kill9-gate");
    let exe = std::env::current_exe().expect("current test binary path");
    let kv_len = 256 * 1024usize; // 256 KiB per block so writes take real SSD I/O time
    let state_len = 32 * 1024usize;

    let mut total_hits = 0u64;
    let mut total_misses = 0u64;
    let mut total_orphans_swept = 0u64;
    let mut total_kills_verified = 0u64;

    let rounds = 10u64;
    for round in 0..rounds {
        let dir = scratch.path().join(format!("round-{round}"));
        prepare_spill_dir(&dir).unwrap();

        let mut child = Command::new(&exe)
            .args([
                "--exact",
                "spill::tests::kill9_writer_helper",
                "--ignored",
                "--nocapture",
            ])
            .env("INKY_SPILL_KILL9_DIR", &dir)
            .env("INKY_SPILL_KILL9_ROUND", round.to_string())
            .env("INKY_SPILL_KILL9_KV_LEN", kv_len.to_string())
            .env("INKY_SPILL_KILL9_STATE_LEN", state_len.to_string())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn kill9 writer helper");

        let child_pid = child.id() as libc::pid_t;
        let stdout = child.stdout.take().expect("child stdout");

        // Wait for child to finish block 0 and enter continuous write loop.
        let mut reader = BufReader::new(stdout);
        let mut line = String::new();
        let mut saw_ready = false;
        let deadline = Instant::now() + Duration::from_secs(10);
        while Instant::now() < deadline {
            line.clear();
            match reader.read_line(&mut line) {
                Ok(0) => break,
                Ok(_) => {
                    if line.trim() == "READY" {
                        saw_ready = true;
                        break;
                    }
                }
                Err(_) => break,
            }
        }
        assert!(saw_ready, "round {round}: child writer did not report READY");

        if round % 2 == 0 {
            // Active mid-write hunt: poll spill dir until a `.tmp.*` file is in flight,
            // then immediately fire SIGKILL right in mid-write!
            let hunt_deadline = Instant::now() + Duration::from_millis(250);
            while Instant::now() < hunt_deadline {
                let has_tmp = fs::read_dir(&dir)
                    .ok()
                    .map(|rd| {
                        rd.filter_map(Result::ok)
                            .any(|e| e.file_name().to_str().and_then(SpillKey::parse_tmp_filename).is_some())
                    })
                    .unwrap_or(false);
                if has_tmp {
                    break;
                }
                std::thread::yield_now();
            }
        } else {
            // Staggered asynchronous kill during active write loop.
            std::thread::sleep(Duration::from_millis(2 + (round * 3) % 17));
        }

        // Deliver genuine SIGKILL (`kill -9`)!
        let rc = unsafe { libc::kill(child_pid, libc::SIGKILL) };
        assert_eq!(rc, 0, "round {round}: SIGKILL failed");
        let status = child.wait().expect("wait for killed child");
        assert_eq!(
            status.signal(),
            Some(libc::SIGKILL),
            "round {round}: child should terminate from SIGKILL, got {status:?}"
        );
        total_kills_verified += 1;

        // Recover with a fresh SpillStore::open().
        let mut store = SpillStore::open(&dir, 512 * 1024 * 1024).expect("recover spill store");
        total_orphans_swept += store.stats().orphans_swept;

        // Assert ZERO orphan `.tmp.*` files remain after startup sweep.
        let remaining_tmps: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(Result::ok)
            .filter(|e| e.file_name().to_str().and_then(SpillKey::parse_tmp_filename).is_some())
            .collect();
        assert!(
            remaining_tmps.is_empty(),
            "round {round}: orphan tmp files remained after open(): {remaining_tmps:?}"
        );

        // Check every block ID in the range 0..max_seen+8 (including in-flight/unwritten tail).
        let max_id = store
            .keys()
            .map(|k| k.id & 0xffff_ffff)
            .max()
            .unwrap_or(0);
        let check_limit = (max_id + 8).min(500);

        for seq in 0..=check_limit {
            let id = (round << 32) | seq;
            let kind = if seq % 4 == 0 {
                SpillBlockKind::Window
            } else {
                SpillBlockKind::Full
            };
            let key = SpillKey::new(kind, id);
            let expected_kv = deterministic_kv(key, kv_len);
            let expected_state = if seq % 3 == 0 {
                Some(deterministic_state(key, state_len))
            } else {
                None
            };

            let (recovered_kv, recovered_state) = match store.read_block(key, Some(kv_len)) {
                ReadOutcome::Hit(blk) => {
                    total_hits += 1;
                    (blk.kv_bytes, blk.recurrent_state)
                }
                ReadOutcome::Miss(_) => {
                    total_misses += 1;
                    // Clean fallback to recomputation from ground truth.
                    (deterministic_kv(key, kv_len), expected_state.clone())
                }
            };

            assert_eq!(
                recovered_kv, expected_kv,
                "round {round} seq {seq}: K/V bytes must be bit-identical"
            );
            assert_eq!(
                recovered_state, expected_state,
                "round {round} seq {seq}: recurrent state must be bit-identical"
            );
        }
    }

    assert_eq!(total_kills_verified, rounds);
    assert!(total_hits >= rounds, "expected committed hits across SIGKILL rounds, got {total_hits}");
    assert!(total_misses > 0, "expected cache misses on interrupted tail, got {total_misses}");
    // Print concise receipt when run with --nocapture.
    eprintln!(
        "[kill9-gate] rounds={rounds} kills={total_kills_verified} hits={total_hits} misses={total_misses} orphans_swept={total_orphans_swept}"
    );
}

#[test]
fn pending_restore_blocks_are_protected_from_disk_gc() {
    let scratch = ScratchTestDir::new("io-pin-gc");
    let dir = scratch.path().join("spill");
    let stride = 2048usize;
    let one_file = (SPILL_HEADER_LEN + stride) as u64;
    // Disk holds at most 2 blocks.
    let mut store = SpillStore::open(&dir, one_file * 2).unwrap();
    let k1 = SpillKey::full(1);
    let k2 = SpillKey::full(2);
    store.write_block(k1, 1, &deterministic_kv(k1, stride), None, &HashSet::new()).unwrap();
    store.write_block(k2, 1, &deterministic_kv(k2, stride), None, &HashSet::new()).unwrap();

    // Pool holds 2 Full slots.
    let pool = HostBlockPoolBackend::new(2, 1, stride, stride);
    let mut mgr = SpillManager::new(pool, store);
    mgr.index_existing_disk_blocks();

    // Put a cold block k3 in memory (refs == 0), leaving 1 free slot.
    let k3 = SpillKey::full(3);
    let s3 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().write_and_seal(s3, &deterministic_kv(k3, stride)).unwrap();
    mgr.register_sealed_block(k3, s3, None).unwrap();

    // Lane A prepares to restore k1 (the OLDEST on-disk block!).
    // k1 now has io_pins == 1 and 1 free slot is reserved.
    let prep_a = mgr.prepare_working_set_restore(&[k1], &[]).unwrap();

    // Now another allocation triggers lazy spill of k3 to disk!
    // Disk budget is 2 blocks: k1 is older than k2, BUT k1 is io-pinned by prep_a,
    // so disk GC MUST evict k2 and MUST preserve k1 on disk!
    let _s4 = mgr.alloc_slot_lazy(SpillBlockKind::Full).unwrap();
    assert!(mgr.store().contains(k1), "io-pinned block k1 must survive disk GC");
    assert!(!mgr.store().contains(k2), "unpinned block k2 should be evicted by disk GC");
    assert!(mgr.store().contains(k3), "spilled block k3 should be on disk");

    // Lane A executes its restore of k1 cleanly with zero miss!
    let res_a = mgr.execute_working_set_restore(prep_a).unwrap();
    assert_eq!(res_a.full_slots.len(), 1);
    assert_eq!(
        mgr.pool().read_slot_bytes(res_a.full_slots[0].1).unwrap(),
        deterministic_kv(k1, stride).as_slice()
    );
}

#[test]
fn concurrent_restores_of_shared_disk_block_deduplicate_without_slot_leak() {
    let scratch = ScratchTestDir::new("dedup-restore");
    let dir = scratch.path().join("spill");
    let stride = 2048usize;
    let mut store = SpillStore::open(&dir, 64 * 1024 * 1024).unwrap();
    let shared = SpillKey::full(77);
    let state = deterministic_state(shared, 512);
    store
        .write_block(shared, 1, &deterministic_kv(shared, stride), Some(&state), &HashSet::new())
        .unwrap();

    // Pool has 2 Full slots so two lanes can both reserve concurrently.
    let pool = HostBlockPoolBackend::new(2, 1, stride, stride);
    let mut mgr = SpillManager::new(pool, store);
    mgr.index_existing_disk_blocks();

    let prep_a = mgr.prepare_working_set_restore(&[shared], &[]).unwrap();
    let prep_b = mgr.prepare_working_set_restore(&[shared], &[]).unwrap();
    assert_eq!(mgr.pool().used_slots(SpillBlockKind::Full), 2);

    // Lane A finishes restore first -> installs `shared` into slot A (refs = 1).
    let res_a = mgr.execute_working_set_restore(prep_a).unwrap();
    let slot_a = res_a.full_slots[0].1;

    // Lane B finishes restore second -> MUST deduplicate onto slot A (refs = 2)
    // and release its redundant pre-reserved slot so used_slots drops back to 1!
    let res_b = mgr.execute_working_set_restore(prep_b).unwrap();
    let slot_b = res_b.full_slots[0].1;
    assert_eq!(slot_a, slot_b, "concurrent restores of same block must share one slot");
    assert_eq!(mgr.pool().refs(slot_a).unwrap(), 2);
    assert_eq!(mgr.pool().used_slots(SpillBlockKind::Full), 1);
    assert_eq!(mgr.pool().free_slots(SpillBlockKind::Full), 1);
    assert_eq!(res_b.recurrent_states.get(&shared), Some(&state));

    // Unpin both lanes cleanly.
    assert_eq!(mgr.unpin(shared).unwrap(), 1);
    assert_eq!(mgr.unpin(shared).unwrap(), 0);
}

#[test]
fn full_scale_block_and_recurrent_state_roundtrip() {
    const FULL_STRIDE: usize = 2 * 1024 * 1024;
    let scratch = ScratchTestDir::new("full-scale");
    let dir = scratch.path().join("spill");
    // Real Layer 3 Full block (2 MiB) + Inkling 2 Mini recurrent state (~3.66 MiB).
    let cs_bytes = crate::engine::Engine::cs_image_bytes();
    let mut store = SpillStore::open(&dir, 32 * 1024 * 1024).unwrap();
    let key = SpillKey::full(4242);
    let kv = deterministic_kv(key, FULL_STRIDE);
    let st = deterministic_state(key, cs_bytes);

    let (out, evicted) = store
        .write_block(key, 9, &kv, Some(&st), &HashSet::new())
        .unwrap();
    assert!(evicted.is_empty());
    assert_eq!(
        out,
        WriteOutcome::Written {
            on_disk_bytes: (SPILL_HEADER_LEN + FULL_STRIDE + cs_bytes) as u64
        }
    );

    match store.read_block(key, Some(FULL_STRIDE)) {
        ReadOutcome::Hit(blk) => {
            assert_eq!(blk.key, key);
            assert_eq!(blk.generation, 9);
            assert_eq!(blk.kv_bytes, kv);
            assert_eq!(blk.recurrent_state.as_deref(), Some(st.as_slice()));
        }
        ReadOutcome::Miss(r) => panic!("expected full-scale hit, got {r:?}"),
    }
}

#[test]
fn kvb_mismatch_between_kv8_and_fp16_is_rejected_without_exposing_bytes() {
    let scratch = ScratchTestDir::new("kvb-mismatch");
    let dir = scratch.path().join("spill");

    // Reject invalid kvb widths at open time.
    assert!(matches!(SpillStore::open_with_kvb(&dir, 64 * 1024 * 1024, 0), Err(SpillError::InvalidKvb(0))));
    assert!(matches!(SpillStore::open_with_kvb(&dir, 64 * 1024 * 1024, 3), Err(SpillError::InvalidKvb(3))));

    let kv_len = 4096usize;
    let cs_len = 256usize;
    let k_kv8 = SpillKey::full(77);
    let k_cs_kv8 = SpillKey::full(78);

    // 1. Write K/V and recurrent-state-only blocks from a --kv8 (kvb=1) server.
    {
        let mut kv8_store = SpillStore::open_with_kvb(&dir, 64 * 1024 * 1024, 1).unwrap();
        assert_eq!(kv8_store.kvb(), 1);
        kv8_store
            .write_block(k_kv8, 1, &deterministic_kv(k_kv8, kv_len), None, &HashSet::new())
            .unwrap();
        kv8_store
            .write_block(k_cs_kv8, 1, &[], Some(&deterministic_state(k_cs_kv8, cs_len)), &HashSet::new())
            .unwrap();
        assert!(matches!(kv8_store.read_block(k_kv8, Some(kv_len)), ReadOutcome::Hit(_)));
        assert!(matches!(kv8_store.read_block(k_cs_kv8, Some(0)), ReadOutcome::Hit(_)));
    }

    // 2. Reopen as fp16 (kvb=2): must reject BOTH K/V and state-only blocks even if expected_kv_len is None/0!
    {
        let mut fp16_store = SpillStore::open_with_kvb(&dir, 64 * 1024 * 1024, 2).unwrap();
        assert_eq!(fp16_store.kvb(), 2);
        assert_eq!(fp16_store.read_block(k_kv8, None), ReadOutcome::Miss(MissReason::KvbMismatch));
        assert!(!fp16_store.block_path(k_kv8).exists());
        assert_eq!(fp16_store.read_block(k_cs_kv8, Some(0)), ReadOutcome::Miss(MissReason::KvbMismatch));
        assert!(!fp16_store.block_path(k_cs_kv8).exists());

        // Write an fp16 block (kvb=2) now.
        let k_fp16 = SpillKey::window(88);
        fp16_store
            .write_block(k_fp16, 2, &deterministic_kv(k_fp16, kv_len), None, &HashSet::new())
            .unwrap();
    }

    // 3. Reopen as --kv8 (kvb=1): must reject the fp16 block!
    let mut kv8_store = SpillStore::open_with_kvb(&dir, 64 * 1024 * 1024, 1).unwrap();
    let k_fp16 = SpillKey::window(88);
    assert_eq!(kv8_store.read_block(k_fp16, Some(kv_len)), ReadOutcome::Miss(MissReason::KvbMismatch));
    assert!(!kv8_store.block_path(k_fp16).exists());
}

#[test]
fn evict_one_lru_cold_releases_io_pin_when_pool_returns_error() {
    struct FailOncePool {
        inner: HostBlockPoolBackend,
        fail_read: bool,
    }
    impl SpillPoolBackend for FailOncePool {
        fn stride_bytes(&self, kind: SpillBlockKind) -> usize { self.inner.stride_bytes(kind) }
        fn capacity_slots(&self, kind: SpillBlockKind) -> usize { self.inner.capacity_slots(kind) }
        fn used_slots(&self, kind: SpillBlockKind) -> usize { self.inner.used_slots(kind) }
        fn free_slots(&self, kind: SpillBlockKind) -> usize { self.inner.free_slots(kind) }
        fn read_slot_bytes(&self, slot: ResidentSlot) -> Result<&[u8], SpillError> {
            if self.fail_read {
                return Err(SpillError::Pool("injected read failure".into()));
            }
            self.inner.read_slot_bytes(slot)
        }
        fn take_free_slot(&mut self, kind: SpillBlockKind) -> Result<ResidentSlot, SpillError> {
            self.inner.take_free_slot(kind)
        }
        fn release_cold_slot(&mut self, slot: ResidentSlot) -> Result<(), SpillError> {
            self.inner.release_cold_slot(slot)
        }
        fn install_restored_slot(&mut self, slot: ResidentSlot, kv_bytes: &[u8]) -> Result<(), SpillError> {
            self.inner.install_restored_slot(slot, kv_bytes)
        }
        fn add_ref(&mut self, slot: ResidentSlot) -> Result<u32, SpillError> { self.inner.add_ref(slot) }
        fn drop_ref(&mut self, slot: ResidentSlot) -> Result<u32, SpillError> { self.inner.drop_ref(slot) }
        fn refs(&self, slot: ResidentSlot) -> Result<u32, SpillError> { self.inner.refs(slot) }
    }

    let scratch = ScratchTestDir::new("evict-io-pin-rollback");
    let store = SpillStore::open(scratch.path(), 64 * 1024 * 1024).unwrap();
    let pool = FailOncePool { inner: HostBlockPoolBackend::new(1, 1, 64, 64), fail_read: false };
    let mut mgr = SpillManager::new(pool, store);
    let key = SpillKey::full(1);
    let slot = mgr.pool_mut().take_free_slot(SpillBlockKind::Full).unwrap();
    mgr.pool_mut().install_restored_slot(slot, &[7u8; 64]).unwrap();
    mgr.register_sealed_block(key, slot, None).unwrap();
    mgr.pool_mut().fail_read = true;

    // First eviction attempt fails during `read_slot_bytes`; `io_pins` must drop back to 0.
    assert!(mgr.evict_one_lru_cold(SpillBlockKind::Full).is_err());
    assert_eq!(mgr.blocks.get(&key).unwrap().io_pins, 0, "io_pins must not leak on pool error");

    // Once the transient failure clears, the block remains evictable and spills cleanly.
    mgr.pool_mut().fail_read = false;
    assert_eq!(mgr.evict_one_lru_cold(SpillBlockKind::Full).unwrap(), key);
    assert_eq!(mgr.blocks.get(&key).unwrap().io_pins, 0);
}

#[test]
fn kv4_spill_directory_refuses_mismatched_modes_and_dc_table_digests_cleanly() {
    use crate::blocks::{KvMode, KV4_FULL_STRIDE, KVB_KV4};

    let scratch = ScratchTestDir::new("kv4-spill-mode-mismatch");
    let kv4_dir = scratch.path().join("spill-kv4");

    // Simulate SHA-256 over the 98,304-byte calibrated K_DC_ROT table + codec flags.
    let mut h_default = Sha256::new();
    h_default.update(b"inky-kv4-codec-v1\0");
    h_default.update(&[1u8, 1u8, 1u8]);
    h_default.update(&vec![0x3cu8; 98_304]);
    let dc_digest_default = h_default.finalize();

    let mut h_no_dc = Sha256::new();
    h_no_dc.update(b"inky-kv4-codec-v1\0");
    h_no_dc.update(&[0u8, 1u8, 1u8]);
    h_no_dc.update(&vec![0x00u8; 98_304]);
    let dc_digest_no_dc = h_no_dc.finalize();

    // 1. Initialize a --kv4 spill directory stamped with `dc_digest_default`, write a KV4 block + exact 3.66 MiB FP32 cs state.
    let k_full = SpillKey::full(42);
    let k_cs = SpillKey::full(43);
    let kv4_payload = deterministic_kv(k_full, KV4_FULL_STRIDE as usize);
    let cs_f32 = deterministic_state(k_cs, 3_833_856);
    {
        let mut store =
            SpillStore::open_with_kv4_digest(&kv4_dir, 64 * 1024 * 1024, dc_digest_default).unwrap();
        assert_eq!(store.kvb(), KVB_KV4);
        store.write_block(k_full, 1, &kv4_payload, None, &HashSet::new()).unwrap();
        store.write_block(k_cs, 1, &[], Some(&cs_f32), &HashSet::new()).unwrap();
    }

    // 2. Attempting to open the --kv4 spill directory as FP16, --kv8, OR --kv4 with a mismatched
    //    `K_DC_ROT` digest (e.g. `INK_NO_KV4_DC=1` or `--no-mpp`) MUST fail closed at open time
    //    without unlinking or corrupting existing --kv4 blocks.
    assert!(matches!(
        SpillStore::open_with_kvb(&kv4_dir, 64 * 1024 * 1024, 2),
        Err(SpillError::ModeMismatch { expected: 2, found }) if found == KVB_KV4
    ));
    assert!(matches!(
        SpillStore::open_with_kvb(&kv4_dir, 64 * 1024 * 1024, 1),
        Err(SpillError::ModeMismatch { expected: 1, found }) if found == KVB_KV4
    ));
    assert!(matches!(
        SpillStore::open_with_mode(&kv4_dir, 64 * 1024 * 1024, KvMode::Fp16),
        Err(SpillError::ModeMismatch { expected: 2, found }) if found == KVB_KV4
    ));
    assert!(matches!(
        SpillStore::open_with_mode(&kv4_dir, 64 * 1024 * 1024, KvMode::Kv8),
        Err(SpillError::ModeMismatch { expected: 1, found }) if found == KVB_KV4
    ));
    let Err(mismatch_err) =
        SpillStore::open_with_kv4_digest(&kv4_dir, 64 * 1024 * 1024, dc_digest_no_dc)
    else {
        panic!("expected KV4 K_DC_ROT ModeMismatch");
    };
    assert!(
        matches!(mismatch_err, SpillError::ModeMismatch { expected, found } if expected == KVB_KV4 && found == KVB_KV4),
        "expected KV4 K_DC_ROT ModeMismatch, got {mismatch_err:?}"
    );
    assert!(mismatch_err.to_string().contains("K_DC_ROT digest mismatch"), "{mismatch_err}");

    // Also test deferred two-step verification (used by `inky serve` after `calibrate_kv4_dc_mean()`).
    {
        let mut store = SpillStore::open_with_mode(&kv4_dir, 64 * 1024 * 1024, KvMode::Kv4).unwrap();
        assert!(matches!(
            store.verify_or_stamp_kv4_digest(dc_digest_no_dc),
            Err(SpillError::ModeMismatch { expected, found }) if expected == KVB_KV4 && found == KVB_KV4
        ));
    }

    // 3. Reopening with the matching `dc_digest_default` succeeds and verifies both KV4 block and exact 3.66 MiB FP32 cs intact.
    {
        let mut store =
            SpillStore::open_with_kv4_digest(&kv4_dir, 64 * 1024 * 1024, dc_digest_default).unwrap();
        match store.read_block(k_full, Some(KV4_FULL_STRIDE as usize)) {
            ReadOutcome::Hit(blk) => assert_eq!(blk.kv_bytes, kv4_payload),
            other => panic!("expected KV4 block hit, got {other:?}"),
        }
        match store.read_block(k_cs, Some(0)) {
            ReadOutcome::Hit(blk) => assert_eq!(blk.recurrent_state.as_deref(), Some(cs_f32.as_slice())),
            other => panic!("expected KV4 cs hit, got {other:?}"),
        }
    }

    // 4. Conversely, opening an existing FP16 or --kv8 spill directory with --kv4 is also refused cleanly.
    let fp16_dir = scratch.path().join("spill-fp16");
    {
        let mut fp16_store = SpillStore::open_with_mode(&fp16_dir, 64 * 1024 * 1024, KvMode::Fp16).unwrap();
        fp16_store.write_block(k_full, 1, &deterministic_kv(k_full, 4096), None, &HashSet::new()).unwrap();
    }
    assert!(matches!(
        SpillStore::open_with_kv4_digest(&fp16_dir, 64 * 1024 * 1024, dc_digest_default),
        Err(SpillError::ModeMismatch { expected, found: 2 }) if expected == KVB_KV4
    ));
}

#[test]
fn serve_stale_spill_rotation_moves_dir_aside_intact_handles_collisions_logs_and_boots_clean() {
    use crate::blocks::{KvMode, KV4_FULL_STRIDE, KVB_KV4};

    let scratch = ScratchTestDir::new("serve-stale-spill-rotate");
    let spill_dir = scratch.path().join("cache-spill");

    let mut d1 = Sha256::new();
    d1.update(b"old-dc-calibration");
    let old_digest = d1.finalize();

    let mut d2 = Sha256::new();
    d2.update(b"new-dc-calibration");
    let new_digest = d2.finalize();

    // 1. Populate `--spill-dir` in `--kv4` mode with `old_digest`, a `.blk` file, and a sentinel file.
    let k_full = SpillKey::full(7);
    let old_payload = deterministic_kv(k_full, KV4_FULL_STRIDE as usize);
    {
        let mut store =
            SpillStore::open_with_kv4_digest(&spill_dir, 64 * 1024 * 1024, old_digest).unwrap();
        store.write_block(k_full, 1, &old_payload, None, &HashSet::new()).unwrap();
        fs::write(spill_dir.join("namespace.salt"), b"preserve-me").unwrap();
    }

    // Pre-create `<spill-dir>.stale-1700000000` with a sentinel file to prove collision handling
    // never overwrites or deletes an existing `.stale-*` backup!
    let colliding_stale = scratch.path().join("cache-spill.stale-1700000000");
    fs::create_dir_all(&colliding_stale).unwrap();
    fs::write(colliding_stale.join("prior-backup.txt"), b"untouched").unwrap();

    // 2. Simulate `inky serve` startup when `K_DC_ROT` / shader digest changed (`old_digest` -> `new_digest`):
    //    first `open_with_mode(..., KvMode::Kv4)` (pre-engine), then `verify_or_stamp_kv4_digest(new_digest)`
    //    hits `ModeMismatch`, drops lock, and `open_or_rotate_stale_at` moves the stale dir to `.stale-1700000000-1`!
    let rotated = {
        let mut pre_store = SpillStore::open_with_mode(&spill_dir, 64 * 1024 * 1024, KvMode::Kv4).unwrap();
        assert!(matches!(
            pre_store.verify_or_stamp_kv4_digest(new_digest),
            Err(SpillError::ModeMismatch { .. })
        ));
        drop(pre_store);
        let (fresh_store, rot) = SpillStore::open_or_rotate_stale_at(
            &spill_dir,
            64 * 1024 * 1024,
            KvMode::Kv4,
            Some(new_digest),
            1_700_000_000,
        )
        .expect("rotate stale KV4 digest spill dir cleanly");
        assert_eq!(fresh_store.kvb(), KVB_KV4);
        assert_eq!(fresh_store.entry_count(), 0, "freshly rotated SpillStore must start empty");
        assert_eq!(fresh_store.used_bytes(), 0);
        rot.expect("expected StaleSpillRotation receipt")
    };

    let expected_stale = scratch.path().join("cache-spill.stale-1700000000-1");
    assert_eq!(rotated.moved_to, expected_stale);
    let warn_line = rotated.format_warning(&spill_dir);
    assert!(warn_line.contains("[serve] WARNING:"), "{warn_line}");
    assert!(warn_line.contains("sha256="), "warning must report old and new digests: {warn_line}");
    assert!(warn_line.contains(&expected_stale.display().to_string()), "{warn_line}");

    // Verify the pre-existing colliding backup was untouched AND all files inside `.stale-1700000000-1` are intact!
    assert_eq!(fs::read(colliding_stale.join("prior-backup.txt")).unwrap(), b"untouched");
    assert_eq!(fs::read(expected_stale.join("namespace.salt")).unwrap(), b"preserve-me");
    assert!(expected_stale.join(SPILL_KV4_MARKER_FILENAME).is_file());
    {
        let mut moved_store =
            SpillStore::open_with_kv4_digest(&expected_stale, 64 * 1024 * 1024, old_digest).unwrap();
        match moved_store.read_block(k_full, Some(KV4_FULL_STRIDE as usize)) {
            ReadOutcome::Hit(blk) => assert_eq!(blk.kv_bytes, old_payload),
            other => panic!("expected intact old KV4 block inside moved-aside dir, got {other:?}"),
        }
    }

    // 3. Switching modes (`--kv4` -> `--kv8`) also rotates cleanly into `.stale-1700000001` and boots an empty `--kv8` cache!
    {
        let (kv8_store, rot_kv8) = SpillStore::open_or_rotate_stale_at(
            &spill_dir,
            64 * 1024 * 1024,
            KvMode::Kv8,
            None,
            1_700_000_001,
        )
        .expect("rotate KV4 -> KV8 spill dir cleanly");
        assert_eq!(kv8_store.kvb(), 1);
        assert_eq!(kv8_store.entry_count(), 0);
        let rot_kv8 = rot_kv8.expect("expected KV4 -> KV8 rotation receipt");
        let warn_kv8 = rot_kv8.format_warning(&spill_dir);
        assert!(warn_kv8.contains("kvb=66") && warn_kv8.contains("kvb=1 (kv8)"), "{warn_kv8}");
        assert!(scratch.path().join("cache-spill.stale-1700000001").join(SPILL_KV4_MARKER_FILENAME).is_file());
    }

    // 4. `verify_or_rotate_kv4_digest` (`serve_with_mode` path) rotates in-place without dropping the lock!
    {
        drop(SpillStore::open_or_rotate_stale_at(&spill_dir, 64 * 1024 * 1024, KvMode::Kv4, Some(old_digest), 1_700_000_002).unwrap());
        let pre_store = SpillStore::open_with_mode(&spill_dir, 64 * 1024 * 1024, KvMode::Kv4).unwrap();
        let (verified, rot_in_place) = pre_store.verify_or_rotate_kv4_digest(new_digest).unwrap();
        assert_eq!(verified.kvb(), KVB_KV4);
        let rot_in_place = rot_in_place.expect("expected in-place rotation on digest mismatch");
        assert!(rot_in_place.moved_to.exists());
    }
}

#[test]
fn stale_spill_rotation_retains_exclusive_lock_across_rename_and_refuses_active_opener() {
    use crate::blocks::{KvMode, KV4_FULL_STRIDE, KVB_KV4};
    use std::sync::{mpsc, Arc, Barrier, Mutex};

    static ROTATE_HOOK_TEST_GUARD: Mutex<()> = Mutex::new(());
    let _serial = ROTATE_HOOK_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());

    let mut h1 = Sha256::new();
    h1.update(b"kv4-digest-one");
    let d1 = h1.finalize();
    let mut h2 = Sha256::new();
    h2.update(b"kv4-digest-two");
    let d2 = h2.finalize();

    // ---- Subtest A: An active opener (`KvMode::Fp16` or `KvMode::Kv4`) holding `LOCK_EX` causes
    //      `open_or_rotate_stale` to fail immediately with `Err(SpillError::DirectoryLocked)` and
    //      leaves the live spill directory 100% untouched (never rotating an active store!).
    {
        let scratch = ScratchTestDir::new("active-opener-blocks-rotate");
        let dir = scratch.path().join("live-spill");
        let mut store_a = SpillStore::open_with_mode(&dir, 64 * 1024 * 1024, KvMode::Fp16).unwrap();
        let key_a = SpillKey::full(11);
        let payload_a = deterministic_kv(key_a, FULL_STRIDE);
        store_a.write_block(key_a, 1, &payload_a, None, &HashSet::new()).unwrap();

        let barrier = Arc::new(Barrier::new(2));
        let dir_bg = dir.clone();
        let bar_bg = Arc::clone(&barrier);
        let contender = std::thread::spawn(move || {
            bar_bg.wait();
            SpillStore::open_or_rotate_stale_at(&dir_bg, 64 * 1024 * 1024, KvMode::Kv4, Some(d1), 1_700_111_000)
        });
        barrier.wait();
        let contend_res = contender.join().unwrap();
        assert!(
            matches!(contend_res, Err(SpillError::DirectoryLocked(ref p)) if p == &dir),
            "competing open_or_rotate_stale against live Fp16 opener must return DirectoryLocked, got {:?}",
            contend_res.err()
        );
        assert!(
            !scratch.path().join("live-spill.stale-1700111000").exists(),
            "active opener's spill directory must never be rotated aside"
        );
        match store_a.read_block(key_a, Some(FULL_STRIDE)) {
            ReadOutcome::Hit(blk) => assert_eq!(blk.kv_bytes, payload_a),
            other => panic!("active store_a block must remain readable, got {other:?}"),
        }
        drop(store_a);
    }

    // ---- Subtest B: Deterministic rendezvous-channel test (zero `sleep`) proving `LOCK_EX` is
    //      retained continuously across BOTH mismatch paths (`scan_and_sweep` `kvb` mismatch AND
    //      `verify_or_stamp_kv4_digest` digest mismatch) right up to `fs::rename`, blocking any
    //      competing opener with `SpillError::DirectoryLocked`, and unlocking the old inode only
    //      after `fs::rename` completes!
    for (label, seed_kv4_d1) in [("fp16-to-kv4", false), ("kv4-digest-mismatch", true)] {
        let scratch = ScratchTestDir::new(&format!("lock-held-across-rename-{label}"));
        let dir = scratch.path().join("spill");
        let clean_target: PathBuf = dir.components().collect();
        let key = SpillKey::full(19);
        if seed_kv4_d1 {
            let mut s = SpillStore::open_with_kv4_digest(&dir, 64 * 1024 * 1024, d1).unwrap();
            s.write_block(key, 1, &deterministic_kv(key, KV4_FULL_STRIDE as usize), None, &HashSet::new())
                .unwrap();
        } else {
            let mut s = SpillStore::open_with_mode(&dir, 64 * 1024 * 1024, KvMode::Fp16).unwrap();
            s.write_block(key, 1, &deterministic_kv(key, FULL_STRIDE), None, &HashSet::new())
                .unwrap();
        }

        let (entered_tx, entered_rx) = mpsc::sync_channel::<()>(0);
        let (proceed_tx, proceed_rx) = mpsc::sync_channel::<()>(0);
        let proceed_rx = Mutex::new(proceed_rx);
        let hook_target = clean_target.clone();
        set_test_spill_rotate_hook(Some(Arc::new(move |p: &Path| {
            if p == hook_target {
                entered_tx.send(()).unwrap();
                proceed_rx.lock().unwrap().recv().unwrap();
            }
        })));

        let dir_rot = dir.clone();
        let rot_thread = std::thread::spawn(move || {
            SpillStore::open_or_rotate_stale_at(&dir_rot, 64 * 1024 * 1024, KvMode::Kv4, Some(d2), 1_700_222_000)
        });

        // Wait until `rot_thread` is deterministically paused inside `rotate_stale_spill_dir_locked`
        // AFTER mismatch detection and right before `fstat == symlink_metadata` + `fs::rename`.
        entered_rx.recv().unwrap();

        // While paused at the pre-rename point, `rot_thread` MUST still hold `flock(LOCK_EX)` on `dir`:
        // both `open_with_mode` and a second `open_or_rotate_stale_at` must immediately fail with `DirectoryLocked`!
        let contend_plain = SpillStore::open_with_mode(&dir, 64 * 1024 * 1024, KvMode::Fp16);
        assert!(
            matches!(contend_plain, Err(SpillError::DirectoryLocked(ref p)) if p == &dir),
            "[{label}] lock was dropped before rename! contend_plain={:?}",
            contend_plain.err()
        );
        let contend_rot =
            SpillStore::open_or_rotate_stale_at(&dir, 64 * 1024 * 1024, KvMode::Kv4, Some(d2), 1_700_222_001);
        assert!(
            matches!(contend_rot, Err(SpillError::DirectoryLocked(ref p)) if p == &dir),
            "[{label}] lock was dropped before rename! contend_rot={:?}",
            contend_rot.err()
        );

        // Clear hook and release `rot_thread` to complete `fstat` verification, `fs::rename`, unlock old fd, and open fresh `dir`.
        set_test_spill_rotate_hook(None);
        proceed_tx.send(()).unwrap();

        let (fresh_store, rot) = rot_thread.join().unwrap().expect("rotation must succeed");
        let rot = rot.expect("expected StaleSpillRotation");
        assert_eq!(fresh_store.kvb(), KVB_KV4);
        // Fresh `dir` is exclusively locked by `fresh_store`...
        assert!(matches!(
            SpillStore::open_with_kv4_digest(&dir, 64 * 1024 * 1024, d2),
            Err(SpillError::DirectoryLocked(_))
        ));
        // ...while the moved-aside backup directory's fd WAS unlocked right after `fs::rename`,
        // so inspecting/reopening `rot.moved_to` succeeds cleanly!
        if seed_kv4_d1 {
            let backup = SpillStore::open_with_kv4_digest(&rot.moved_to, 64 * 1024 * 1024, d1).unwrap();
            assert_eq!(backup.entry_count(), 1);
        } else {
            let backup = SpillStore::open_with_mode(&rot.moved_to, 64 * 1024 * 1024, KvMode::Fp16).unwrap();
            assert_eq!(backup.entry_count(), 1);
        }
        drop(fresh_store);
    }

    // ---- Subtest C: Pre-rename `(dev, ino)` verification refuses to rename if the path inode
    //      no longer matches `fstat(locked_fd)`!
    #[cfg(unix)]
    {
        let scratch = ScratchTestDir::new("inode-mismatch-refused");
        let dir = scratch.path().join("spill-swap");
        let displaced = scratch.path().join("displaced-original");
        let clean_target: PathBuf = dir.components().collect();
        {
            let mut s = SpillStore::open_with_kv4_digest(&dir, 64 * 1024 * 1024, d1).unwrap();
            let k = SpillKey::full(23);
            s.write_block(k, 1, &deterministic_kv(k, KV4_FULL_STRIDE as usize), None, &HashSet::new())
                .unwrap();
        }
        let hook_target = clean_target.clone();
        let displaced_in_hook = displaced.clone();
        set_test_spill_rotate_hook(Some(Arc::new(move |p: &Path| {
            if p == hook_target {
                // Externally swap the directory entry at `p` to a brand-new inode right before the check!
                fs::rename(p, &displaced_in_hook).unwrap();
                fs::create_dir(p).unwrap();
                fs::write(p.join("bystander.txt"), b"do-not-rename-me").unwrap();
            }
        })));
        let res = SpillStore::open_or_rotate_stale_at(&dir, 64 * 1024 * 1024, KvMode::Kv4, Some(d2), 1_700_333_000);
        set_test_spill_rotate_hook(None);
        match res {
            Err(SpillError::InvalidDir(msg)) => {
                assert!(msg.contains("inode changed while locked"), "unexpected error: {msg}");
            }
            other => panic!("expected InvalidDir inode-changed error, got {:?}", other.err()),
        }
        // The replacement bystander directory at `dir` was NOT renamed to `.stale-1700333000`!
        assert!(!scratch.path().join("spill-swap.stale-1700333000").exists());
        assert_eq!(fs::read(dir.join("bystander.txt")).unwrap(), b"do-not-rename-me");
    }
}

#[test]
fn spill_enforces_effective_backend_precision_and_layout_fallback_compatibility() {
    use crate::blocks::{KvMode, PrefillArithMode};
    use crate::engine::Engine;
    let scratch = ScratchTestDir::new("spill-effective-backend-arith");
    let budget = 64 * 1024 * 1024;

    // Verify `Engine` classifier binds `(use_mpp, hgemm, layout_ok, exact)` into distinct modes,
    // including the `engine/model.rs` `layout_ok == false` fallback (`MppTensorF32Simd`).
    let m_tc = Engine::prefill_arith_mode_from_parts(
        true,
        Engine::resolve_effective_hgemm(true, false, true),
        false,
        false,
    );
    let m_exact_mpp = Engine::prefill_arith_mode_from_parts(
        true,
        Engine::resolve_effective_hgemm(true, false, true),
        true,
        false,
    );
    let m_no_tc_attn = Engine::prefill_arith_mode_from_parts(
        true,
        Engine::resolve_effective_hgemm(true, false, true),
        false,
        true,
    );
    let m_layout_fallback = Engine::prefill_arith_mode_from_parts(
        true,
        Engine::resolve_effective_hgemm(true, false, false),
        true,
        false,
    );
    let m_no_hgemm_tc_req = Engine::prefill_arith_mode_from_parts(
        true,
        Engine::resolve_effective_hgemm(true, true, true),
        false,
        false,
    );
    let m_non_mpp = Engine::prefill_arith_mode_from_parts(
        false,
        Engine::resolve_effective_hgemm(false, false, true),
        true,
        false,
    );
    assert_eq!(m_tc, PrefillArithMode::MppHalfTensorCore);
    assert_eq!(m_no_tc_attn, PrefillArithMode::MppHalfSimd);
    assert_eq!(m_exact_mpp, PrefillArithMode::MppHalfSimd);
    assert_eq!(m_layout_fallback, PrefillArithMode::MppTensorF32Simd);
    assert_eq!(m_no_hgemm_tc_req, PrefillArithMode::MppTensorF32Simd);
    assert_eq!(m_non_mpp, PrefillArithMode::Metal3SimdF32);

    // Exhaustively test every ordered pair `(mode_a, mode_b)` across all 4 backend/precision modes:
    // - Same-backend reopen (`mode_a -> mode_a`) restores the spilled block intact.
    // - Cross-backend reopen (`mode_a -> mode_b` for `mode_a != mode_b`, covering both reopen directions)
    //   fails closed with `ModeMismatch` and rotates cleanly via `verify_or_rotate_prefill_arith_at`.
    let mut seq = 0u64;
    for (i, &mode_a) in PrefillArithMode::ALL.iter().enumerate() {
        for (j, &mode_b) in PrefillArithMode::ALL.iter().enumerate() {
            if i == j {
                continue;
            }
            seq += 1;
            let dir = scratch.path().join(format!("pair-{i}-to-{j}"));
            let k = SpillKey::full(100 + seq);
            let payload = deterministic_kv(k, 4096);
            {
                let mut s = SpillStore::open_with_mode(&dir, budget, KvMode::Fp16).unwrap();
                s.verify_or_stamp_prefill_arith(mode_a).unwrap();
                s.write_block(k, 1, &payload, None, &HashSet::new()).unwrap();
            }
            // Same-backend reopen restores `k` intact:
            {
                let mut s_same = SpillStore::open_with_mode(&dir, budget, KvMode::Fp16).unwrap();
                s_same.verify_or_stamp_prefill_arith(mode_a).unwrap();
                assert!(s_same.contains(k), "same-backend reopen failed for {mode_a:?}");
                assert!(matches!(s_same.read_block(k, None), ReadOutcome::Hit(b) if b.kv_bytes == payload));
            }
            // Cross-backend reopen refuses and rotates:
            {
                let mut s_cross = SpillStore::open_with_mode(&dir, budget, KvMode::Fp16).unwrap();
                assert!(
                    matches!(
                        s_cross.verify_or_stamp_prefill_arith(mode_b),
                        Err(SpillError::ModeMismatch { .. })
                    ),
                    "expected ModeMismatch reopening {mode_a:?} as {mode_b:?}"
                );
                let (mut fresh, rot) = s_cross
                    .verify_or_rotate_prefill_arith_at(KvMode::Fp16, None, mode_b, 1_700_400_000 + seq)
                    .unwrap();
                let rot = rot.unwrap_or_else(|| panic!("{mode_a:?} -> {mode_b:?} must rotate stale spill dir"));
                assert!(rot.moved_to.exists());
                assert!(!fresh.contains(k));
                assert_eq!(fresh.entry_count(), 0);
                // Subsequent write & same-backend reopen under `mode_b` succeeds:
                let k_b = SpillKey::full(200 + seq);
                let payload_b = deterministic_kv(k_b, 4096);
                fresh.write_block(k_b, 1, &payload_b, None, &HashSet::new()).unwrap();
                drop(fresh);
                let mut s_b_same = SpillStore::open_with_mode(&dir, budget, KvMode::Fp16).unwrap();
                s_b_same.verify_or_stamp_prefill_arith(mode_b).unwrap();
                assert!(matches!(s_b_same.read_block(k_b, None), ReadOutcome::Hit(b) if b.kv_bytes == payload_b));
            }
        }
    }

    // Legacy untagged FP16 directory (has surviving `.blk` without `prefill.arith`) -> every backend refuses & rotates!
    for (idx, &mode) in PrefillArithMode::ALL.iter().enumerate() {
        let dir_legacy = scratch.path().join(format!("fp16-legacy-untagged-{idx}"));
        let k_leg = SpillKey::full(500 + idx as u64);
        {
            let mut s = SpillStore::open_with_mode(&dir_legacy, budget, KvMode::Fp16).unwrap();
            s.write_block(k_leg, 1, &deterministic_kv(k_leg, 4096), None, &HashSet::new()).unwrap();
            assert!(!dir_legacy.join(SPILL_ARITH_MARKER_FILENAME).exists());
        }
        {
            let mut s_reopen = SpillStore::open_with_mode(&dir_legacy, budget, KvMode::Fp16).unwrap();
            assert!(matches!(
                s_reopen.verify_or_stamp_prefill_arith(mode),
                Err(SpillError::ModeMismatch { .. })
            ));
            let (fresh, rot) = s_reopen
                .verify_or_rotate_prefill_arith_at(KvMode::Fp16, None, mode, 1_700_401_000 + idx as u64)
                .unwrap();
            let rot = rot.expect("legacy untagged FP16 dir must rotate on reopen");
            assert!(rot.old_mode_desc.contains("untagged-legacy-prefill"), "got: {}", rot.old_mode_desc);
            assert!(!fresh.contains(k_leg));
        }
    }
}

#[test]
fn oversized_prefill_marker_rotates_with_fixed_reason() {
    use crate::blocks::{KvMode, PrefillArithMode};

    let scratch = ScratchTestDir::new("oversized-prefill-marker");
    let dir = scratch.path().join("fp16");
    let store = SpillStore::open_with_mode(&dir, 1 << 20, KvMode::Fp16).unwrap();
    let marker = [b'x'; 257];
    fs::write(dir.join(SPILL_ARITH_MARKER_FILENAME), marker).unwrap();

    let arith = PrefillArithMode::MppHalfSimd;
    let (_fresh, rotation) = store.verify_or_rotate_prefill_arith_at(KvMode::Fp16, None, arith, 123).unwrap();
    let rotation = rotation.unwrap();
    assert_eq!(rotation.old_mode_desc, "kvb=2 (fp16), invalid-prefill-arith");
    assert_eq!(fs::read(rotation.moved_to.join(SPILL_ARITH_MARKER_FILENAME)).unwrap(), marker);
    assert_eq!(fs::read_to_string(dir.join(SPILL_ARITH_MARKER_FILENAME)).unwrap().trim(), arith.spill_marker_line());
}

#[cfg(target_os = "macos")]
#[test]
fn rejected_prefill_marker_is_never_read_for_its_description() {
    use crate::blocks::{KvMode, PrefillArithMode};
    use std::io::Read;
    use std::os::fd::AsRawFd;
    use std::os::unix::fs::symlink;

    let scratch = ScratchTestDir::new("nonregular-prefill-marker");
    let dir = scratch.path().join("fp16");
    let store = SpillStore::open_with_mode(&dir, 1 << 20, KvMode::Fp16).unwrap();

    // Darwin's /dev/fd duplicates the pipe reader. A diagnostic reopen consumes
    // these bytes and immediately reaches EOF, so the check needs no timeout.
    let (mut reader, mut writer) = io::pipe().unwrap();
    writer.write_all(b"still unread").unwrap();
    drop(writer);
    symlink(format!("/dev/fd/{}", reader.as_raw_fd()), dir.join(SPILL_ARITH_MARKER_FILENAME)).unwrap();

    let (_, rotation) = store
        .verify_or_rotate_prefill_arith_at(KvMode::Fp16, None, PrefillArithMode::MppHalfTensorCore, 123)
        .unwrap();
    let mut remaining = Vec::new();
    reader.read_to_end(&mut remaining).unwrap();
    assert_eq!(remaining, b"still unread");
    assert_eq!(rotation.unwrap().old_mode_desc, "kvb=2 (fp16), invalid-prefill-arith");
}

#[test]
fn a_late_worker_read_never_brings_back_a_removed_block() {
    // The restore worker read this block for a restore that was then cancelled; the block was removed
    // (its start was restored by another lane, trimmed, or collected) before the read was applied.
    let scratch = ScratchTestDir::new("late-read");
    let two_blocks = 2 * (SPILL_HEADER_LEN + 64) as u64;
    let mut store = SpillStore::open(scratch.path(), two_blocks).unwrap();

    let gone = store.fresh_key(SpillBlockKind::Full);
    store.write_block(gone, 1, &[7u8; 64], None, &HashSet::new()).unwrap();
    let late = read_block_from_dir(store.dir(), store.kvb(), gone, Some(64));
    assert!(matches!(late.outcome, ReadOutcome::Hit(_)));
    assert!(store.remove_block(gone));
    assert_eq!(store.used_bytes(), 0);

    let _ = store.apply_raw_read(gone, late);
    assert!(!store.contains(gone), "a removed block stays removed");
    assert_eq!(store.used_bytes(), 0, "a file that is not on disk is not charged to the budget");

    // The budget holds exactly two blocks, and two real blocks are all that is on disk: neither is collected.
    let a = store.fresh_key(SpillBlockKind::Full);
    let (_, evicted) = store.write_block(a, 1, &[1u8; 64], None, &HashSet::new()).unwrap();
    assert!(evicted.is_empty());
    let b = store.fresh_key(SpillBlockKind::Full);
    let (outcome, evicted) = store.write_block(b, 1, &[2u8; 64], None, &HashSet::new()).unwrap();
    assert!(matches!(outcome, WriteOutcome::Written { .. }));
    assert!(evicted.is_empty(), "a block that is not there cost a real block its place: {evicted:?}");
    assert!(matches!(store.read_block(a, Some(64)), ReadOutcome::Hit(blk) if blk.kv_bytes == [1u8; 64]));
    assert_eq!(store.used_bytes(), two_blocks);
}