fusevm 0.14.0

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

//! Integration tests for the persistent on-disk native-JIT cache.
//!
//! These exercise the `jit-disk-cache` feature end-to-end: native compilation,
//! atomic disk persistence, mmap-based loading with relocation patching, and
//! the fingerprint/op_hash/corruption rejection paths.

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock};

use fusevm::{ChunkBuilder, JitCompiler, Op, VMResult, Value, VM};

/// The cache directory is a process-global override, so tests that configure it
/// must not run concurrently. Each such test holds this lock for its duration.
fn serial() -> MutexGuard<'static, ()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(|e| e.into_inner())
}

/// A unique temp directory per test, so concurrent test threads never collide.
fn fresh_dir(tag: &str) -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!(
        "fusevm_jit_cache_{}_{}_{}_{}",
        tag,
        std::process::id(),
        n,
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    dir
}

fn build(ops: &[(Op, u32)]) -> fusevm::Chunk {
    let mut b = ChunkBuilder::new();
    for (op, line) in ops {
        b.emit(op.clone(), *line);
    }
    b.build()
}

/// Run a chunk with the disk cache pointed at `dir`, returning the result.
/// A fresh `JitCompiler` is used each call so the per-thread in-memory cache
/// does not mask the disk path (note: TLS is per-thread, not per-compiler, so
/// distinct op_hashes are still required to force a disk hit — see the
/// dedicated roundtrip test which uses a subprocess-style fresh op set).
fn run_with_cache(chunk: &fusevm::Chunk, dir: &PathBuf, slots: &[i64]) -> Option<Value> {
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    let r = jit.try_run_linear(chunk, slots);
    jit.set_jit_cache_dir(None);
    r
}

#[test]
fn disk_cache_leaf_matches_interp() {
    let _g = serial();
    let dir = fresh_dir("leaf");
    // (2 + 3) * 4 = 20
    let chunk = build(&[
        (Op::LoadInt(2), 1),
        (Op::LoadInt(3), 1),
        (Op::Add, 1),
        (Op::LoadInt(4), 1),
        (Op::Mul, 1),
    ]);
    assert_eq!(run_with_cache(&chunk, &dir, &[]), Some(Value::Int(20)));
    // A file should have been written to the cache dir.
    let entries: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().map_or(false, |x| x == "fjit"))
        .collect();
    assert_eq!(entries.len(), 1, "expected exactly one cached .fjit file");
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_pow_uses_host_reloc() {
    let _g = serial();
    let dir = fresh_dir("pow");
    // 2 ** 10 = 1024 — Pow emits a call to a host helper, exercising the
    // Abs8 relocation patching path on load.
    let chunk = build(&[(Op::LoadInt(2), 1), (Op::LoadInt(10), 1), (Op::Pow, 1)]);
    assert_eq!(run_with_cache(&chunk, &dir, &[]), Some(Value::Int(1024)));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_float() {
    let _g = serial();
    let dir = fresh_dir("float");
    let chunk = build(&[
        (Op::LoadFloat(1.5), 1),
        (Op::LoadFloat(2.5), 1),
        (Op::Add, 1),
    ]);
    match run_with_cache(&chunk, &dir, &[]) {
        Some(Value::Float(f)) => assert!((f - 4.0).abs() < 1e-10),
        other => panic!("expected Float(4.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_slots() {
    let _g = serial();
    let dir = fresh_dir("slots");
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::GetSlot(1), 1), (Op::Add, 1)]);
    assert_eq!(
        run_with_cache(&chunk, &dir, &[100, 200]),
        Some(Value::Int(300))
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_roundtrip_second_load_from_disk() {
    let _g = serial();
    // First compiler builds + persists the blob. A *second* compiler in a
    // separate thread (fresh TLS in-memory cache) must load it back from disk
    // and produce the identical result, proving the file path works without
    // any in-memory state.
    let dir = fresh_dir("roundtrip");
    let chunk = build(&[(Op::LoadInt(7), 1), (Op::LoadInt(6), 1), (Op::Mul, 1)]);

    let first = run_with_cache(&chunk, &dir, &[]);
    assert_eq!(first, Some(Value::Int(42)));

    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let second = std::thread::spawn(move || run_with_cache(&chunk2, &dir2, &[]))
        .join()
        .unwrap();
    assert_eq!(second, Some(Value::Int(42)));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_corrupted_file_rejected() {
    let _g = serial();
    // A garbage cache file must be ignored (bad magic / truncated), the chunk
    // recompiled, and the correct result still returned — no crash.
    let dir = fresh_dir("corrupt");
    let chunk = build(&[(Op::LoadInt(40), 1), (Op::LoadInt(2), 1), (Op::Add, 1)]);

    // Pre-populate the would-be cache path with junk. The filename scheme is
    // "{op_hash:016x}.fjit"; we don't know the hash here, so instead seed a
    // wrong file AND verify a good run still works, then corrupt the real file.
    std::fs::create_dir_all(&dir).unwrap();

    // First good run writes the real file.
    assert_eq!(run_with_cache(&chunk, &dir, &[]), Some(Value::Int(42)));

    // Corrupt every .fjit file in place.
    for e in std::fs::read_dir(&dir).unwrap().flatten() {
        if e.path().extension().map_or(false, |x| x == "fjit") {
            std::fs::write(e.path(), b"not a real blob").unwrap();
        }
    }

    // A fresh thread (no TLS hit) must reject the corrupt file, recompile, and
    // overwrite it — still returning the correct value.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let r = std::thread::spawn(move || run_with_cache(&chunk2, &dir2, &[]))
        .join()
        .unwrap();
    assert_eq!(r, Some(Value::Int(42)));
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_on_by_default_and_opt_out() {
    let _g = serial();
    let jit = JitCompiler::new();
    // Clear any programmatic override left by another test.
    jit.set_jit_cache_dir(None);

    // Default-on: with no override and no env opt-out, a default dir resolves.
    let saved = std::env::var_os("FUSEVM_JIT_CACHE_DIR");
    std::env::remove_var("FUSEVM_JIT_CACHE_DIR");
    let def = jit.jit_cache_dir();
    assert!(
        def.as_ref().map_or(false, |p| p.ends_with("fusevm-jit")),
        "expected default dir ending in fusevm-jit, got {def:?}"
    );

    // Env opt-out disables caching entirely.
    std::env::set_var("FUSEVM_JIT_CACHE_DIR", "off");
    assert_eq!(jit.jit_cache_dir(), None);

    // Restore prior env state for other tests.
    match saved {
        Some(v) => std::env::set_var("FUSEVM_JIT_CACHE_DIR", v),
        None => std::env::remove_var("FUSEVM_JIT_CACHE_DIR"),
    }
}

#[test]
fn disk_cache_in_memory_still_correct_when_disabled() {
    let _g = serial();
    let jit = JitCompiler::new();
    let saved = std::env::var_os("FUSEVM_JIT_CACHE_DIR");
    std::env::set_var("FUSEVM_JIT_CACHE_DIR", "off");
    jit.set_jit_cache_dir(None);
    assert_eq!(jit.jit_cache_dir(), None);
    let chunk = build(&[(Op::LoadInt(21), 1), (Op::Dup, 1), (Op::Add, 1)]);
    assert_eq!(jit.try_run_linear(&chunk, &[]), Some(Value::Int(42)));
    match saved {
        Some(v) => std::env::set_var("FUSEVM_JIT_CACHE_DIR", v),
        None => std::env::remove_var("FUSEVM_JIT_CACHE_DIR"),
    }
}

#[test]
fn disk_cache_set_and_get_dir() {
    let _g = serial();
    let jit = JitCompiler::new();
    let dir = fresh_dir("api");
    jit.set_jit_cache_dir(Some(dir.clone()));
    assert_eq!(jit.jit_cache_dir(), Some(dir));
    jit.set_jit_cache_dir(None);
}

// ── Block tier ──

/// `sum = 0; i = 0; while (i < 100) { sum += i; i++ }` → 4950. Block-JIT
/// eligible (slot ops + a fused loop branch), so it exercises the block-tier
/// native compile + disk persist + mmap-load path.
fn block_sum_loop() -> fusevm::Chunk {
    let mut b = ChunkBuilder::new();
    b.emit(Op::PushFrame, 1);
    b.emit(Op::LoadInt(0), 1);
    b.emit(Op::SetSlot(0), 1);
    b.emit(Op::LoadInt(0), 1);
    b.emit(Op::SetSlot(1), 1);
    b.emit(Op::GetSlot(0), 1);
    b.emit(Op::GetSlot(1), 1);
    b.emit(Op::Add, 1);
    b.emit(Op::SetSlot(0), 1);
    b.emit(Op::PreIncSlotVoid(1), 1);
    b.emit(Op::SlotLtIntJumpIfFalse(1, 100, 12), 1);
    b.emit(Op::Jump(5), 1);
    b.emit(Op::GetSlot(0), 1);
    b.build()
}

/// True if `dir` contains at least one finalized cache file whose name carries
/// the given tier tag (e.g. `.blk.` or `.trc.`).
fn has_tagged_file(dir: &PathBuf, tag: &str) -> bool {
    let needle = format!(".{tag}.fjit");
    std::fs::read_dir(dir)
        .map(|rd| {
            rd.flatten()
                .any(|e| e.file_name().to_string_lossy().ends_with(needle.as_str()))
        })
        .unwrap_or(false)
}

fn run_block_with_cache(chunk: &fusevm::Chunk, dir: &PathBuf) -> Option<i64> {
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    let mut slots = vec![0i64; 4];
    let r = jit.try_run_block_eager(chunk, &mut slots);
    jit.set_jit_cache_dir(None);
    r
}

#[test]
fn disk_cache_block_matches_and_persists() {
    let _g = serial();
    let dir = fresh_dir("block");
    let chunk = block_sum_loop();

    assert_eq!(run_block_with_cache(&chunk, &dir), Some(4950));
    assert!(
        has_tagged_file(&dir, "blk"),
        "expected a .blk.fjit block cache file to be written"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_block_roundtrip_second_thread() {
    let _g = serial();
    // First thread compiles + persists the block blob; a second thread (fresh
    // per-thread cache) must load it from disk and produce the same result.
    let dir = fresh_dir("block_rt");
    let chunk = block_sum_loop();
    assert_eq!(run_block_with_cache(&chunk, &dir), Some(4950));

    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let second = std::thread::spawn(move || run_block_with_cache(&chunk2, &dir2))
        .join()
        .unwrap();
    assert_eq!(second, Some(4950));
    let _ = std::fs::remove_dir_all(&dir);
}

/// Tight do-while counter loop; returns (chunk, anchor_ip).
fn counter_loop(limit: i64) -> (fusevm::Chunk, usize) {
    let mut b = ChunkBuilder::new();
    b.emit(Op::LoadInt(0), 1);
    b.emit(Op::SetSlot(0), 1);
    let anchor = b.current_pos();
    b.emit(Op::PreIncSlotVoid(0), 1);
    b.emit(Op::GetSlot(0), 1);
    b.emit(Op::LoadInt(limit), 1);
    b.emit(Op::NumLt, 1);
    let jmp = b.emit(Op::JumpIfTrue(0), 1);
    b.patch_jump(jmp, anchor);
    b.emit(Op::GetSlot(0), 1);
    (b.build(), anchor)
}

fn run_trace_vm(chunk: &fusevm::Chunk) -> i64 {
    let mut vm = VM::new(chunk.clone());
    vm.enable_tracing_jit();
    {
        let frame = vm.frames.last_mut().unwrap();
        while frame.slots.len() < 1 {
            frame.slots.push(Value::Int(0));
        }
    }
    match vm.run() {
        VMResult::Ok(Value::Int(n)) => n,
        other => panic!("expected Int result, got {other:?}"),
    }
}

#[test]
fn disk_cache_trace_matches_and_persists() {
    let _g = serial();
    let dir = fresh_dir("trace");
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));

    let (chunk, _anchor) = counter_loop(200);
    // First run records + compiles the trace; with caching on this builds the
    // native blob, persists it, and runs the freshly-loaded native trace.
    assert_eq!(run_trace_vm(&chunk), 200);
    assert!(
        has_tagged_file(&dir, "trc"),
        "expected a .trc.fjit trace cache file to be written"
    );

    jit.set_jit_cache_dir(None);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn disk_cache_trace_roundtrip_second_thread() {
    let _g = serial();
    let dir = fresh_dir("trace_rt");
    let (chunk, _anchor) = counter_loop(200);

    let dir_a = dir.clone();
    let chunk_a = chunk.clone();
    let first = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir_a.clone()));
        let r = run_trace_vm(&chunk_a);
        jit.set_jit_cache_dir(None);
        r
    })
    .join()
    .unwrap();
    assert_eq!(first, 200);
    assert!(has_tagged_file(&dir, "trc"));

    // Second thread: empty trace TLS forces a fresh install, which must load
    // the native trace from disk and still produce the correct result.
    let dir_b = dir.clone();
    let chunk_b = chunk.clone();
    let second = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir_b.clone()));
        let r = run_trace_vm(&chunk_b);
        jit.set_jit_cache_dir(None);
        r
    })
    .join()
    .unwrap();
    assert_eq!(second, 200);
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cache_size_clear_and_max_bytes_api() {
    let _g = serial();
    let dir = fresh_dir("size_api");
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));

    // Populate the cache with several distinct linear chunks.
    for k in 0..6 {
        let chunk = build(&[(Op::LoadInt(k), 1), (Op::LoadInt(1), 1), (Op::Add, 1)]);
        let _ = jit.try_run_linear(&chunk, &[]);
    }
    let size = jit.jit_cache_size_bytes().expect("caching enabled");
    assert!(size > 0, "cache should have grown after compiling chunks");

    // Force a tiny cap and prune: size must drop to at most the cap.
    jit.set_jit_cache_max_bytes(Some(200));
    let freed = jit.prune_jit_cache();
    assert!(
        freed > 0,
        "prune should have evicted blobs to meet the 200B cap"
    );
    let after = jit.jit_cache_size_bytes().unwrap();
    assert!(after <= 200, "expected ≤200B after prune, got {after}");

    // clear() removes everything.
    let removed = jit.clear_jit_cache();
    assert!(removed > 0);
    assert_eq!(jit.jit_cache_size_bytes().unwrap(), 0);

    // Restore default cap resolution and detach the dir override.
    jit.set_jit_cache_max_bytes(None);
    jit.set_jit_cache_dir(None);
    let _ = std::fs::remove_dir_all(&dir);
}

/// New slot ops (PreDecSlot / PostIncSlot / PostDecSlot): block JIT must match
/// the interpreter. Builds a counted loop that exercises each op and compares
/// the native (eager block JIT) result against a pure-interpreter run.
#[test]
fn new_slot_ops_block_jit_matches_interp() {
    use fusevm::Op::*;
    // slots: 0=i (counter), 1=acc, 2=scratch
    // Loop: while i < 5 { acc += PostIncSlot(scratch-ish)... } — keep it simple:
    // acc = 0; i = 0; do { tmp = i++ (PostIncSlot i); acc = acc + tmp; } while i<5
    // Then j = 5; --j (PreDecSlot); k = j--; (PostDecSlot) push results to acc.
    let ops = vec![
        (PushFrame, 1),
        (LoadInt(0), 1),
        (SetSlot(1), 1), // acc = 0
        (LoadInt(0), 1),
        (SetSlot(0), 1), // i = 0
        // loop header @ ip 5
        (PostIncSlot(0), 1), // push old i, i++
        (GetSlot(1), 1),
        (Add, 1),
        (SetSlot(1), 1),                     // acc += old_i
        (SlotLtIntJumpIfFalse(0, 5, 14), 1), // if i<5 fallthrough else jump exit(14)
        (Jump(5), 1),
        (Nop, 1),
        (Nop, 1),
        (Nop, 1),
        // exit @ 14: j=10; --j; pre-dec pushes 9; acc+=9
        (LoadInt(10), 1),
        (SetSlot(2), 1),
        (PreDecSlot(2), 1), // push 9
        (GetSlot(1), 1),
        (Add, 1),
        (SetSlot(1), 1),
        // post-dec j(=9) -> push 9, j=8; acc+=9
        (PostDecSlot(2), 1),
        (GetSlot(1), 1),
        (Add, 1),
        (SetSlot(1), 1),
        (GetSlot(1), 1), // result = acc
    ];
    let chunk = build(&ops);

    // Interpreter result.
    let mut vm = VM::new(chunk.clone());
    let interp = match vm.run() {
        VMResult::Ok(v) => v.to_int(),
        other => panic!("interp failed: {:?}", other),
    };

    // Block JIT (eager) result via slot buffer.
    let jit = JitCompiler::new();
    let mut slots = vec![0i64; 4];
    let native = jit
        .try_run_block(&chunk, &mut slots)
        .or_else(|| jit.try_run_block(&chunk, &mut slots))
        .expect("block jit should compile new slot ops");
    // sum of 0..5 = 10, plus 9 + 9 = 28
    assert_eq!(interp, 28, "interp value");
    assert_eq!(native, interp, "block jit must match interpreter");
}

/// awkrs lowers an `int(x)` builtin call to the native `Op::AwkInt` (Cranelift
/// `trunc`). This verifies the end-to-end goal: a numeric chunk containing
/// `AwkDivJit` — the op a front-end's always-float `/` lowers to (e.g.
/// strykelang `$x / $y`) — now block-JIT-compiles AND persists a `blk` native
/// blob to the on-disk cache. Previously div/mod chunks skipped persistence
/// because the zero-divisor trap libcall was not a registered host helper;
/// registering it under `H_AWK_DIV_TRAP` makes float division reuse the native
/// disk cache across process restarts. The compiled result must equal the
/// interpreter's exact float (`7 / 2 == 3.5`).
#[test]
fn disk_cache_awk_div_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("awkdiv");

    // `$x / $y` with x = slot 0, y = slot 1: GetSlot(0); GetSlot(1); AwkDivJit.
    // Always-float division: 7 / 2 == 3.5 (not integer 3).
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::GetSlot(1), 1), (Op::AwkDivJit, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![7i64, 2i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 3.5, "7.0 / 2.0 must be exactly 3.5");
        }
        other => panic!("expected Float(3.5) from AwkDivJit block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the AwkDivJit chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread (fresh per-thread cache): the loader
    // must patch the `H_AWK_DIV_TRAP` relocation to the live trap-helper address
    // and reproduce the exact float, proving div chunks round-trip through the
    // native disk cache.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![7i64, 2i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 3.5, "reloaded blob must yield 3.5"),
        other => panic!("expected reloaded Float(3.5), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `PowFloat` — the op a front-end's always-float `**` lowers to (e.g.
/// strykelang `$x ** $y`) — block-JIT-compiles AND persists a `blk` native blob
/// to the on-disk cache. Unlike `Op::Pow` (whose JIT keeps an integer result
/// for two static-`Int` operands), `PowFloat` coerces both operands to f64 in
/// every tier, so the JIT result equals the interpreter's exact float
/// (`2 ** 10 == 1024.0`) and the chunk reuses the already-registered `pow_f64`
/// host helper — no schema bump or new host helper needed.
#[test]
fn disk_cache_pow_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("powfloat");

    // `$x ** $y` with x = slot 0, y = slot 1: GetSlot(0); GetSlot(1); PowFloat.
    // Always-float power: 2 ** 10 == 1024.0 (Float, not integer 1024).
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::GetSlot(1), 1), (Op::PowFloat, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![2i64, 10i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 1024.0, "2.0 ** 10.0 must be exactly 1024.0");
        }
        other => panic!("expected Float(1024.0) from PowFloat block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the PowFloat chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread: the loader must patch the pow_f64
    // host-helper relocation and reproduce the exact float, proving PowFloat
    // chunks round-trip through the native disk cache.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![2i64, 10i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 1024.0, "reloaded blob must yield 1024.0")
        }
        other => panic!("expected reloaded Float(1024.0), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `SqrtFloat` — the op a front-end's always-float `sqrt` lowers to (e.g.
/// strykelang `sqrt($x)`) — block-JIT-compiles AND persists a `blk` native blob
/// to the on-disk cache. It lowers to a native Cranelift `fsqrt` (no host helper
/// or relocation at all), so the JIT result equals the interpreter's exact float
/// (`sqrt(2.0) == 1.4142135623730951`) and the chunk round-trips through the disk
/// cache with no schema-helper dependency.
#[test]
fn disk_cache_sqrt_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("sqrtfloat");

    // `sqrt($x)` with x = slot 0: GetSlot(0); SqrtFloat. Always-float: the
    // perfect square 9 -> 3.0, and 2 -> 1.4142135623730951.
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::SqrtFloat, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![9i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 3.0, "sqrt(9.0) must be exactly 3.0");
        }
        other => panic!("expected Float(3.0) from SqrtFloat block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the SqrtFloat chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread: a native `fsqrt` carries no host-helper
    // relocation, so the blob must reproduce the exact float straight from disk.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![2i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 2.0_f64.sqrt(), "reloaded blob must yield sqrt(2.0)")
        }
        other => panic!("expected reloaded Float(sqrt(2.0)), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `SinFloat` — the op a front-end's always-float `sin` lowers to (e.g.
/// strykelang `sin($x)`) — block-JIT-compiles AND persists a `blk` native blob
/// to the on-disk cache. Unlike `SqrtFloat`, it calls the `fusevm_jit_sin_f64`
/// host helper (the same one `AwkSin` uses), so this exercises the host-helper
/// relocation round-trip: the reloaded blob must re-resolve the helper address
/// and reproduce the interpreter's exact float.
#[test]
fn disk_cache_sin_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("sinfloat");

    // `sin($x)` with x = slot 0: GetSlot(0); SinFloat. sin(0.0) == 0.0 exactly.
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::SinFloat, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![0i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 0.0, "sin(0.0) must be exactly 0.0");
        }
        other => panic!("expected Float(0.0) from SinFloat block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the SinFloat chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread: the `sin` host helper must be
    // re-resolved from its persisted id so the blob reproduces sin(1.0).
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![1i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 1.0_f64.sin(), "reloaded blob must yield sin(1.0)")
        }
        other => panic!("expected reloaded Float(sin(1.0)), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `LogFloat` — the op a front-end's always-float natural `log` lowers to (e.g.
/// strykelang `log($x)`) — block-JIT-compiles AND persists a `blk` native blob
/// to the on-disk cache. It calls a NEW `fusevm_jit_log_f64` host helper carried
/// through the chunk's `ext_helpers` (like the div/mod trap), exercising that
/// path's relocation round-trip: the reloaded blob must re-resolve the helper.
#[test]
fn disk_cache_log_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("logfloat");

    // `log($x)` with x = slot 0: GetSlot(0); LogFloat. log(1.0) == 0.0 exactly.
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::LogFloat, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![1i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 0.0, "log(1.0) must be exactly 0.0");
        }
        other => panic!("expected Float(0.0) from LogFloat block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the LogFloat chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread: the `log` host helper must be
    // re-resolved from its persisted id so the blob reproduces log(8.0).
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![8i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 8.0_f64.ln(), "reloaded blob must yield log(8.0)")
        }
        other => panic!("expected reloaded Float(log(8.0)), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `AbsFloat` — strykelang's always-float `abs` lowers to this native op (uses
/// Cranelift's `fabs`, no host helper, like `SqrtFloat`). The block native blob
/// must persist and reload across threads.
#[test]
fn disk_cache_abs_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("absfloat");

    // `abs($x)` with x = slot 0: GetSlot(0); AbsFloat. abs(0) == 0.0 exactly.
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::AbsFloat, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![0i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 0.0, "abs(0.0) must be exactly 0.0");
        }
        other => panic!("expected Float(0.0) from AbsFloat block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the AbsFloat chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread with a negative slot: the native blob
    // must reproduce abs(-7.0) == 7.0.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![-7i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Float(f)) => {
            assert_eq!(f, 7.0, "reloaded blob must yield abs(-7.0) == 7.0")
        }
        other => panic!("expected reloaded Float(7.0), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `TruncInt` — strykelang's `int(x)` lowers to this op, which converts a float
/// to a genuine i64 (via Cranelift `fcvt_to_sint_sat`, no host helper). Exercises
/// the float->int path by truncating a `SqrtFloat` result, and verifies the
/// integer block blob persists and reloads across threads.
#[test]
fn disk_cache_trunc_int_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("truncint");

    // `int(sqrt($x))` with x = slot 0: GetSlot(0); SqrtFloat; TruncInt.
    // int(sqrt(16)) == int(4.0) == 4.
    let chunk = build(&[(Op::GetSlot(0), 1), (Op::SqrtFloat, 1), (Op::TruncInt, 1)]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![16i64];
    assert_eq!(
        jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]),
        None,
        "below threshold"
    );
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Int(n)) => {
            assert_eq!(n, 4, "int(sqrt(16)) must be 4");
        }
        other => panic!("expected Int(4) from TruncInt block, got {other:?}"),
    }

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the TruncInt chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );

    // Reload from disk on a fresh thread: int(sqrt(81)) == int(9.0) == 9.
    let dir2 = dir.clone();
    let chunk2 = chunk.clone();
    let reloaded = std::thread::spawn(move || {
        let jit = JitCompiler::new();
        jit.set_jit_cache_dir(Some(dir2));
        jit.set_config(TraceJitConfig {
            block_threshold: 0,
            ..TraceJitConfig::defaults()
        });
        let mut slots = vec![81i64];
        jit.try_run_block_eager_typed_kinded(&chunk2, &mut slots, &[])
    })
    .join()
    .unwrap();
    match reloaded {
        Some(fusevm::BlockNum::Int(n)) => {
            assert_eq!(n, 9, "reloaded blob must yield int(sqrt(81)) == 9")
        }
        other => panic!("expected reloaded Int(9), got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
}

/// `AwkInt` — exactly the shape awkrs's `fusevm_bridge` emits for `x=int(x+c)`
/// per record — block-JIT-compiles AND persists a `blk` native blob to the
/// on-disk cache, so the JIT result is reused across process restarts.
#[test]
fn disk_cache_awk_int_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("awkint");

    // Mirror awkrs's per-record chunk for `{ x = int(x + 1.9) }` with x = slot 0:
    //   PushFrame; LoadFloat(seed); SetSlot(0);          (slot-init preamble)
    //   GetSlot(0); LoadFloat(1.9); Add; AwkInt; Dup; SetSlot(0); Pop
    let chunk = build(&[
        (Op::PushFrame, 1),
        (Op::LoadFloat(0.0), 1),
        (Op::SetSlot(0), 1),
        (Op::GetSlot(0), 1),
        (Op::LoadFloat(1.9), 1),
        (Op::Add, 1),
        (Op::AwkInt, 1),
        (Op::Dup, 1),
        (Op::SetSlot(0), 1),
        (Op::Pop, 1),
    ]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    // Compile on the 2nd invocation (mimics warmup across records).
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let mut slots = vec![0i64; 1];
    assert_eq!(
        jit.try_run_block(&chunk, &mut slots),
        None,
        "below threshold"
    );
    let _native = jit
        .try_run_block(&chunk, &mut slots)
        .expect("AwkInt chunk must block-JIT compile");
    // int(0 + 1.9) = 1, written back to slot 0.
    assert_eq!(slots[0], 1, "slot 0 should be int(1.9) == 1");

    jit.set_jit_cache_dir(None);

    // A `blk` native blob must have been persisted to disk.
    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the AwkInt chunk, found {:?}",
        std::fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| e.file_name())
            .collect::<Vec<_>>()
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// The REAL awkrs lowering: a stable per-record chunk (no PushFrame preamble)
/// whose accumulator slot holds an f64 BIT PATTERN (SlotKind::Float), seeded as
/// data before the run. The block JIT must bitcast the slot through f64 so the
/// arithmetic is real floating-point — not integer-add on the bit pattern.
/// This pins the f64-slot block-JIT fix that makes awkrs `x = int(x + c)` loops
/// compile-and-cache correctly under AWKRS_FUSEVM=1.
#[test]
fn disk_cache_awk_int_float_slot_block_persists() {
    use fusevm::{SlotKind, TraceJitConfig};
    let _g = serial();
    let dir = fresh_dir("awkint_float");

    // Stable chunk: GetSlot(0); LoadFloat(1.9); Add; AwkInt; Dup; SetSlot(0); Pop
    let chunk = build(&[
        (Op::GetSlot(0), 1),
        (Op::LoadFloat(1.9), 1),
        (Op::Add, 1),
        (Op::AwkInt, 1),
        (Op::Dup, 1),
        (Op::SetSlot(0), 1),
        (Op::Pop, 1),
    ]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let kinds = [SlotKind::Float];
    // Slot 0 holds the f64 bit pattern of 0.0 (== 0i64) initially.
    let mut slots = vec![0i64; 1];

    assert_eq!(
        jit.try_run_block_kinded(&chunk, &mut slots, &kinds),
        None,
        "below threshold"
    );
    let _native = jit
        .try_run_block_kinded(&chunk, &mut slots, &kinds)
        .expect("AwkInt float-slot chunk must block-JIT compile");
    // int(0.0 + 1.9) = 1.0; slot 0 now holds the f64 bit pattern of 1.0.
    assert_eq!(
        f64::from_bits(slots[0] as u64),
        1.0,
        "slot 0 should hold f64 1.0 == int(1.9)"
    );

    // Run again to prove the accumulation is real f64 arithmetic, not int-add
    // on bit patterns: int(1.0 + 1.9) = int(2.9) = 2.0.
    let _ = jit.try_run_block_kinded(&chunk, &mut slots, &kinds);
    assert_eq!(
        f64::from_bits(slots[0] as u64),
        2.0,
        "second pass must be real f64 arithmetic: int(2.9) == 2"
    );

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the float-slot AwkInt chunk"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A float-slot block chunk that calls a transcendental libcall op
/// (`Op::AwkSin`) must block-JIT compile, run real f64 arithmetic, and persist a
/// `.blk.fjit` whose relocation references the `H_SIN_F64` host helper. This
/// pins the awk transcendental libcalls flowing through the on-disk cache (the
/// `[Option<FuncId>; 8]` helper-id extension + SCHEMA_VERSION 4 bump).
#[test]
fn disk_cache_awk_sin_float_slot_block_persists() {
    use fusevm::{SlotKind, TraceJitConfig};
    let _g = serial();
    let dir = fresh_dir("awksin_float");

    // Stable chunk: GetSlot(0); AwkSin; LoadFloat(1.0); Add; Dup; SetSlot(0); Pop
    // i.e. x = sin(x) + 1.0
    let chunk = build(&[
        (Op::GetSlot(0), 1),
        (Op::AwkSin, 1),
        (Op::LoadFloat(1.0), 1),
        (Op::Add, 1),
        (Op::Dup, 1),
        (Op::SetSlot(0), 1),
        (Op::Pop, 1),
    ]);

    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig {
        block_threshold: 1,
        ..TraceJitConfig::defaults()
    });

    let kinds = [SlotKind::Float];
    let mut slots = vec![0i64; 1]; // f64 bit pattern of 0.0

    assert_eq!(
        jit.try_run_block_kinded(&chunk, &mut slots, &kinds),
        None,
        "below threshold"
    );
    let _native = jit
        .try_run_block_kinded(&chunk, &mut slots, &kinds)
        .expect("AwkSin float-slot chunk must block-JIT compile");
    // sin(0.0) + 1.0 = 1.0
    assert_eq!(
        f64::from_bits(slots[0] as u64),
        1.0,
        "slot 0 should hold f64 sin(0)+1 == 1.0"
    );

    // Second pass: sin(1.0) + 1.0 — must be real f64 arithmetic via the libcall.
    let _ = jit.try_run_block_kinded(&chunk, &mut slots, &kinds);
    let expected = 1.0f64.sin() + 1.0;
    assert_eq!(
        f64::from_bits(slots[0] as u64),
        expected,
        "second pass must call the sin libcall: sin(1)+1"
    );

    jit.set_jit_cache_dir(None);

    let blk: Vec<_> = std::fs::read_dir(&dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .file_name()
                .and_then(|n| n.to_str())
                .map_or(false, |n| n.contains(".blk.") && n.ends_with(".fjit"))
        })
        .collect();
    assert_eq!(
        blk.len(),
        1,
        "expected one persisted blk.fjit for the float-slot AwkSin chunk"
    );
    let _ = std::fs::remove_dir_all(&dir);
}


// ─── SCHEMA_VERSION 14 float ops ───

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_ceil_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("ceilfloat");
    let chunk = build(&[(Op::LoadFloat(2.3), 1), (Op::CeilFloat, 1)]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 3.0),
        other => panic!("expected Float(3.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_floor_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("floorfloat");
    let chunk = build(&[(Op::LoadFloat(2.7), 1), (Op::FloorFloat, 1)]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 2.0),
        other => panic!("expected Float(2.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_trunc_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("truncfloat");
    let chunk = build(&[(Op::LoadFloat(-2.7), 1), (Op::TruncFloat, 1)]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, -2.0),
        other => panic!("expected Float(-2.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_round_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("roundfloat");
    let chunk = build(&[(Op::LoadFloat(0.5), 1), (Op::RoundFloat, 1)]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 0.0, "ties-to-even: 0.5 -> 0.0"),
        other => panic!("expected Float(0.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_tan_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("tanfloat");
    let chunk = build(&[(Op::LoadFloat(0.0), 1), (Op::TanFloat, 1)]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 0.0),
        other => panic!("expected Float(0.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_asin_acos_atan_float_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("asinacosatan");
    let chunk = build(&[
        (Op::LoadFloat(0.0), 1), (Op::AsinFloat, 1),
        (Op::LoadFloat(0.0), 1), (Op::AcosFloat, 1), (Op::Add, 1),
        (Op::LoadFloat(0.0), 1), (Op::AtanFloat, 1), (Op::Add, 1),
    ]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => {
            let exp = std::f64::consts::FRAC_PI_2;
            assert!((f - exp).abs() < 1e-15, "got {f}");
        }
        other => panic!("expected Float(π/2), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_hyperbolic_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("hyperbolic");
    let chunk = build(&[
        (Op::LoadFloat(0.0), 1), (Op::SinhFloat, 1),
        (Op::LoadFloat(0.0), 1), (Op::CoshFloat, 1), (Op::Add, 1),
        (Op::LoadFloat(0.0), 1), (Op::TanhFloat, 1), (Op::Add, 1),
    ]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert_eq!(f, 1.0),
        other => panic!("expected Float(1.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}

#[cfg(feature = "jit-disk-cache")]
#[test]
fn disk_cache_log2_log10_block_persists() {
    use fusevm::TraceJitConfig;
    let _g = serial();
    let dir = fresh_dir("log2log10");
    let chunk = build(&[
        (Op::LoadFloat(8.0), 1), (Op::Log2Float, 1),
        (Op::LoadFloat(1000.0), 1), (Op::Log10Float, 1), (Op::Add, 1),
    ]);
    let jit = JitCompiler::new();
    jit.set_jit_cache_dir(Some(dir.clone()));
    jit.set_config(TraceJitConfig { block_threshold: 1, ..TraceJitConfig::defaults() });
    let mut slots: Vec<i64> = vec![];
    assert_eq!(jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]), None);
    match jit.try_run_block_typed_kinded(&chunk, &mut slots, &[]) {
        Some(fusevm::BlockNum::Float(f)) => assert!((f - 6.0).abs() < 1e-12, "got {f}"),
        other => panic!("expected Float(6.0), got {other:?}"),
    }
    let _ = std::fs::remove_dir_all(&dir);
}