polyplug_python 0.1.1

Python loader for polyplug - loads Python plugins via PyO3
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
// Integration tests for the polyplug_python PythonLoader (VM dispatch model).
//
// Python guests are VM-dispatch (like Lua/JS): the guest RETURNS its contract
// registrations from `polyplug_init` as a `(registrations, AbiError)` tuple, and
// the loader registers each contract with DispatchType::VirtualMachine, routing
// per-call invocations through the `vm.call` transport. Nothing is deposited into
// any module namespace.
//
// Return shape (the spec the generator/SDK must emit):
//
//   def polyplug_init(host_ptr, ctx_ptr):
//       return [
//           {
//               "contract": "name@major" | "name@major.minor",
//               "plugin_name": "optional",          # defaults to bundle name
//               "factory": factory,                 # factory(host_ptr) -> impl
//               "functions": [callable, ...],       # ordered by fn_id
//           },
//       ], abi_error   # abi_error.code == AbiErrorCode.Ok on success
//
// The loader calls `factory(host_ptr)` once per create_instance (and once at load
// for the stateless default impl) and passes the resolved impl as the first
// argument of each callable, plus the per-bundle arena allocator as the last, so
// each callable is invoked as
// fn(impl, args_ptr_int, out_ptr_int, arena_ptr_int, arena_alloc). The stateless
// plugins below take `impl` and ignore it.
#![allow(clippy::expect_used)]

use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::TempDir;

use polyplug::error::LoaderError;
use polyplug::loader::BundleLoader;
use polyplug::loader::ManifestData;
use polyplug::runtime::Runtime;
use polyplug::runtime_builder::RuntimeBuilder;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::dispatch::DispatchType;
use polyplug_python::PythonConfig;
use polyplug_python::PythonLoader;
use polyplug_utils::BundleId;
use polyplug_utils::GuestContractId;
use polyplug_utils::bundle_id;
use pyo3::Python;
use pyo3::types::PyAnyMethods;
use pyo3::types::PyDict;
use pyo3::types::PyDictMethods;
use pyo3::types::PyModule;

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Write `content` into a temp bundle directory with manifest.toml.
fn write_bundle(name: &str, content: &str) -> (TempDir, PathBuf) {
    let dir: TempDir = TempDir::new().expect("tempdir");
    let path: PathBuf = dir.path().join("bundle.py");
    fs::write(&path, content).expect("write bundle.py");

    let bundle_id: u64 = bundle_id(name);
    let manifest: String = format!(
        r#"id = {}
name = "{}"
loader = "python"
file = "bundle.py"
"#,
        bundle_id, name
    );
    fs::write(dir.path().join("manifest.toml"), &manifest).expect("write manifest.toml");

    (dir, path)
}

fn make_runtime() -> Arc<Runtime> {
    RuntimeBuilder::new()
        .loader(PythonLoader::default())
        .build()
        .expect("runtime build must succeed")
}

fn make_manifest(path: &Path, name: &str) -> ManifestData {
    ManifestData {
        id: bundle_id(name),
        name: name.to_owned(),
        loader: "python".to_owned(),
        file: path
            .file_name()
            .expect("bundle path must have a file name")
            .to_string_lossy()
            .into_owned(),
        path: path
            .parent()
            .expect("bundle path must have a parent directory")
            .to_path_buf(),
        version: String::new(),
        provides: Vec::new(),
        function_count: HashMap::new(),
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    }
}

/// Resolve a registered contract's interface and call its VM dispatch for
/// `fn_id` with the given `args`/`out`/`arena` pointers.
///
/// # Safety
/// `out`/`args`/`arena` must be valid for whatever the guest callable does with
/// them; the test callables below only write to `out`.
unsafe fn dispatch(
    runtime: &Runtime,
    contract_id: u64,
    fn_id: u32,
    args: *const (),
    out: *mut (),
) -> AbiError {
    let cid: GuestContractId = GuestContractId::from_u64(contract_id);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(cid, 0)
        .expect("contract must be registered");
    let interface_ptr: *const polyplug_abi::GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("contract must resolve to an interface");
    // SAFETY: resolved interface is a non-null, runtime-owned GuestContractInterface
    // leaked for the runtime lifetime; reading it and its VM dispatch fields is sound.
    let interface: &polyplug_abi::GuestContractInterface = unsafe { &*interface_ptr };
    assert_eq!(
        interface.dispatch_type,
        DispatchType::VirtualMachine,
        "Python contracts must register VM dispatch"
    );
    // SAFETY: dispatch_type == VirtualMachine guarantees the `vm` union arm is
    // active, so reading it is sound.
    let vm: polyplug_abi::dispatch::vm_dispatch::VmDispatch = unsafe { interface.dispatch.vm };
    let mut err: AbiError = AbiError::ok();
    // SAFETY: the call function is the loader's python_vm_dispatch; loader_data
    // wraps a live leaked PythonLoaderData; args/out are caller-provided.
    unsafe {
        (vm.call)(
            vm.loader_data,
            GuestContractInstance::null(),
            fn_id,
            args,
            out,
            core::ptr::null_mut(),
            &mut err as *mut AbiError,
        );
    }
    err
}

/// Like [`dispatch`], but passes a real per-call `arena` pointer through to the
/// guest callable (the third dispatch argument). Used by the arena-isolation
/// tests to verify each call's allocations come from its OWN arena.
///
/// # Safety
/// `args`/`out` must be valid for the callable; `arena` must point at a valid,
/// caller-reset [`CallArena`] for this call.
unsafe fn dispatch_with_arena(
    runtime: &Runtime,
    contract_id: u64,
    fn_id: u32,
    args: *const (),
    out: *mut (),
    arena: *mut polyplug_abi::CallArena,
) -> AbiError {
    let cid: GuestContractId = GuestContractId::from_u64(contract_id);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(cid, 0)
        .expect("contract must be registered");
    let interface_ptr: *const polyplug_abi::GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("contract must resolve to an interface");
    // SAFETY: resolved interface is a non-null, runtime-owned interface.
    let interface: &polyplug_abi::GuestContractInterface = unsafe { &*interface_ptr };
    // SAFETY: Python contracts always register VM dispatch.
    let vm: polyplug_abi::dispatch::vm_dispatch::VmDispatch = unsafe { interface.dispatch.vm };
    let mut err: AbiError = AbiError::ok();
    // SAFETY: loader_data wraps a live leaked PythonLoaderData; args/out/arena are
    // caller-provided and valid for this call.
    unsafe {
        (vm.call)(
            vm.loader_data,
            GuestContractInstance::null(),
            fn_id,
            args,
            out,
            arena,
            &mut err as *mut AbiError,
        );
    }
    err
}

// ─── Plugin sources (VM dispatch / polyplug_init returns registrations) ──────────
//
// Each inline source defines `_ABI_OK = type("AbiError", (), {"code": 0})()`, a
// minimal stand-in for the SDK AbiError: the loader reads only `.code` (Ok == 0)
// from the second element of the `(registrations, AbiError)` tuple that
// polyplug_init returns.

/// A plugin that registers one contract whose function 0 writes 0x2A into the
/// 4-byte int at `out` (via ctypes) and ignores `args`/`arena`.
const WRITE_OUT_PLUGIN_SRC: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int32))[0] = 0x2A

def polyplug_init(host_interface: int, ctx: int):
    return [
        {
            "contract": "writeout@1",
            "plugin_name": "writeout_plugin",
            "factory": lambda host_ptr: None,
            "functions": [_fn0],
        },
    ], _ABI_OK
"#;

/// Contract id for `writeout@1`.
fn writeout_contract_id() -> u64 {
    GuestContractId::new("writeout", 1).id()
}

/// A plugin whose function 0 raises a Python exception.
const RAISING_FN_PLUGIN_SRC: &str = r#"
_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    raise ValueError("dispatch boom")

def polyplug_init(host_interface: int, ctx: int):
    return [
        {"contract": "raiser@1", "factory": lambda host_ptr: None, "functions": [_fn0]},
    ], _ABI_OK
"#;

fn raiser_contract_id() -> u64 {
    GuestContractId::new("raiser", 1).id()
}

/// A plugin whose function 0 forwards the arena pointer it received into `out`
/// (as an i64) so the test can assert the arena pointer is forwarded verbatim.
const ARENA_FORWARD_PLUGIN_SRC: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int64))[0] = arena_ptr

def polyplug_init(host_interface: int, ctx: int):
    return [
        {"contract": "arenafwd@1", "factory": lambda host_ptr: None, "functions": [_fn0]},
    ], _ABI_OK
"#;

fn arenafwd_contract_id() -> u64 {
    GuestContractId::new("arenafwd", 1).id()
}

/// `polyplug_init` raises an exception.
const RAISING_INIT_PLUGIN_SRC: &str = r#"
def polyplug_init(_host_interface: int, _ctx: int) -> None:
    raise RuntimeError("intentional test error")
"#;

/// Missing `polyplug_init` entirely.
const MISSING_INIT_PLUGIN_SRC: &str = r#"
def not_polyplug_init():
    pass
"#;

/// `polyplug_init` returns `None` instead of a `(registrations, AbiError)` tuple.
const NO_REGISTRATIONS_PLUGIN_SRC: &str = r#"
def polyplug_init(_host_interface: int, _ctx: int):
    return None
"#;

/// `polyplug_init` returns an empty registrations list (no contracts).
const EMPTY_REGISTRATIONS_PLUGIN_SRC: &str = r#"
_ABI_OK = type("AbiError", (), {"code": 0})()

def polyplug_init(_host_interface: int, _ctx: int):
    return [], _ABI_OK
"#;

/// Syntax error.
const SYNTAX_ERROR_PLUGIN_SRC: &str = r#"
def polyplug_init(:
    pass
"#;

/// Imports a nonexistent module.
const IMPORT_ERROR_PLUGIN_SRC: &str = r#"
import _polyplug_nonexistent_module_xyz_123456

def polyplug_init(_host_interface: int, _ctx: int) -> None:
    pass
"#;

// ─── Tests ────────────────────────────────────────────────────────────────────

#[test]
fn test_interpreter_initializes_without_panic() {
    let (_dir, path) = write_bundle("noop_init", WRITE_OUT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "noop_init");
    let result: Result<(), LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "unexpected error: {result:?}");
}

#[test]
fn test_default_config_version_check_passes() {
    let (_dir, path) = write_bundle("ver_check", WRITE_OUT_PLUGIN_SRC);
    let runtime: Arc<Runtime> = RuntimeBuilder::new()
        .loader(PythonLoader::new(PythonConfig::default()))
        .build()
        .expect("runtime build must succeed");
    let manifest: ManifestData = make_manifest(&path, "ver_check");
    let result: Result<(), LoaderError> = PythonLoader::new(PythonConfig::default()).load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "version check failed: {result:?}");
}

#[test]
fn test_version_too_old_returns_version_mismatch() {
    let (_dir, path) = write_bundle("ver_mismatch", WRITE_OUT_PLUGIN_SRC);
    let config: PythonConfig = PythonConfig {
        min_version: (99, 0),
    };
    let runtime: Arc<Runtime> = RuntimeBuilder::new()
        .loader(PythonLoader::new(config.clone()))
        .build()
        .expect("runtime build must succeed");
    let manifest: ManifestData = make_manifest(&path, "ver_mismatch");
    let err: LoaderError = PythonLoader::new(config)
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected version mismatch");
    match err {
        LoaderError::InitFailed { bundle, error } => {
            assert_eq!(bundle, "python");
            assert!(
                error.contains("version"),
                "error should mention version: {error}"
            );
            assert!(
                error.contains("99"),
                "error should mention required version: {error}"
            );
        }
        other => panic!("expected InitFailed for version mismatch, got: {other:?}"),
    }
}

/// Loading a valid plugin registers its contract with VM dispatch.
#[test]
fn test_valid_plugin_registers_vm_contract() {
    let (_dir, path) = write_bundle("valid_plugin", WRITE_OUT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "valid_plugin");
    let result: Result<(), LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "load failed: {result:?}");

    let cid: GuestContractId = GuestContractId::from_u64(writeout_contract_id());
    let handle: GuestContractHandle = runtime
        .registry()
        .find(cid, 0)
        .expect("contract must be registered");
    let interface_ptr: *const polyplug_abi::GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("contract must resolve");
    // SAFETY: runtime-owned interface; reading dispatch_type is sound.
    let interface: &polyplug_abi::GuestContractInterface = unsafe { &*interface_ptr };
    assert_eq!(
        interface.dispatch_type,
        DispatchType::VirtualMachine,
        "Python must register VM dispatch"
    );
}

/// VM dispatch happy path: the callable writes into `out` and returns Ok.
#[test]
fn test_vm_dispatch_writes_out_and_returns_ok() {
    let (_dir, path) = write_bundle("writeout_disp", WRITE_OUT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "writeout_disp");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    let mut out_buf: i32 = 0;
    // SAFETY: out points at a valid i32; the callable writes a 4-byte int there.
    let err: AbiError = unsafe {
        dispatch(
            &runtime,
            writeout_contract_id(),
            0,
            core::ptr::null(),
            &mut out_buf as *mut i32 as *mut (),
        )
    };
    assert!(
        err.is_ok(),
        "dispatch should return Ok, got code {}",
        err.code
    );
    assert_eq!(out_buf, 0x2A, "callable must have written 0x2A into out");
}

/// A Python exception inside the callable maps to AbiErrorCode::Generic.
#[test]
fn test_vm_dispatch_exception_maps_to_generic() {
    let (_dir, path) = write_bundle("raiser_disp", RAISING_FN_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "raiser_disp");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // SAFETY: the callable ignores args/out, so null is sound.
    let err: AbiError = unsafe {
        dispatch(
            &runtime,
            raiser_contract_id(),
            0,
            core::ptr::null(),
            core::ptr::null_mut(),
        )
    };
    assert_eq!(
        err.code,
        AbiErrorCode::Generic as u32,
        "a guest exception must map to Generic"
    );
}

/// An out-of-range fn_id maps to AbiErrorCode::FunctionNotAvailable.
#[test]
fn test_vm_dispatch_fn_id_out_of_range() {
    let (_dir, path) = write_bundle("range_disp", WRITE_OUT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "range_disp");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // Only fn_id 0 exists; fn_id 5 is out of range.
    // SAFETY: out-of-range fn_id returns before touching args/out.
    let err: AbiError = unsafe {
        dispatch(
            &runtime,
            writeout_contract_id(),
            5,
            core::ptr::null(),
            core::ptr::null_mut(),
        )
    };
    assert_eq!(
        err.code,
        AbiErrorCode::FunctionNotAvailable as u32,
        "out-of-range fn_id must map to FunctionNotAvailable"
    );
}

/// The arena pointer is forwarded to the callable; when null it arrives as 0.
#[test]
fn test_vm_dispatch_arena_forwarded_zero_when_null() {
    let (_dir, path) = write_bundle("arena_disp", ARENA_FORWARD_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "arena_disp");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    let mut out_buf: i64 = -1;
    // `dispatch` always passes a null arena, so the callable must observe 0.
    // SAFETY: out points at a valid i64; callable writes the arena int there.
    let err: AbiError = unsafe {
        dispatch(
            &runtime,
            arenafwd_contract_id(),
            0,
            core::ptr::null(),
            &mut out_buf as *mut i64 as *mut (),
        )
    };
    assert!(
        err.is_ok(),
        "dispatch should return Ok, got code {}",
        err.code
    );
    assert_eq!(out_buf, 0, "null arena must be forwarded as integer 0");
}

#[test]
fn test_syntax_error_returns_init_failed() {
    let (_dir, path) = write_bundle("syntax_err", SYNTAX_ERROR_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "syntax_err");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure for syntax error plugin");
    assert!(matches!(err, LoaderError::InitFailed { .. }));
}

#[test]
fn test_import_error_returns_init_failed() {
    let (_dir, path) = write_bundle("import_err", IMPORT_ERROR_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "import_err");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure for import-error plugin");
    assert!(matches!(err, LoaderError::InitFailed { .. }));
}

#[test]
fn test_missing_init_returns_init_symbol_missing() {
    let (_dir, path) = write_bundle("no_init", MISSING_INIT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "no_init");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure");
    assert!(matches!(err, LoaderError::InitSymbolMissing { .. }));
}

#[test]
fn test_raising_init_returns_init_failed() {
    let (_dir, path) = write_bundle("raising_init", RAISING_INIT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "raising_init");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure");
    match err {
        LoaderError::InitFailed { error, .. } => {
            assert!(
                error.contains("intentional test error"),
                "error should contain the Python exception text; got: {error}"
            );
        }
        other => panic!("expected InitFailed, got: {other:?}"),
    }
}

/// A plugin whose `polyplug_init` returns `None` (not a tuple) fails.
#[test]
fn test_missing_registrations_attr_fails() {
    let (_dir, path) = write_bundle("no_regs", NO_REGISTRATIONS_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "no_regs");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure for non-tuple polyplug_init return");
    match err {
        LoaderError::InitFailed { error, .. } => {
            assert!(
                error.contains("polyplug_init must return"),
                "error should mention the bad return; got: {error}"
            );
        }
        other => panic!("expected InitFailed, got: {other:?}"),
    }
}

/// An empty registrations list registers no contracts and fails.
#[test]
fn test_empty_registrations_fails() {
    let (_dir, path) = write_bundle("empty_regs", EMPTY_REGISTRATIONS_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "empty_regs");
    let err: LoaderError = loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect_err("expected failure for empty registrations");
    assert!(matches!(err, LoaderError::InitFailed { .. }));
}

#[test]
fn test_loader_name() {
    let loader: PythonLoader = PythonLoader::default();
    assert_eq!(loader.loader_name(), "python");
}

#[test]
fn test_loader_is_send_sync() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<PythonLoader>();
}

/// Sequential loads on the same loader all succeed (no GIL leak / state leak).
#[test]
fn test_many_sequential_loads() {
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    for i in 0u32..8u32 {
        let name: String = format!("seq_{i}");
        let (_dir, path) = write_bundle(&name, WRITE_OUT_PLUGIN_SRC);
        let manifest: ManifestData = make_manifest(&path, &name);
        let result: Result<(), LoaderError> = loader.load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        );
        // Only the first load registers `writeout@1`; later loads collide on the
        // contract id. The point of this test is interpreter stability, so accept
        // either Ok or a duplicate-registration InitFailed without panicking.
        assert!(
            result.is_ok() || matches!(result, Err(LoaderError::InitFailed { .. })),
            "sequential load {i} produced an unexpected error: {result:?}"
        );
    }
}

/// After a failed load, a subsequent valid load still succeeds.
#[test]
fn test_valid_load_after_failed_load_succeeds() {
    let (_dir1, bad_path) = write_bundle("bad_recover", SYNTAX_ERROR_PLUGIN_SRC);
    let (_dir2, good_path) = write_bundle("good_after_bad", WRITE_OUT_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();

    let bad_manifest: ManifestData = make_manifest(&bad_path, "bad_recover");
    let good_manifest: ManifestData = make_manifest(&good_path, "good_after_bad");

    assert!(
        loader
            .load(
                &bad_manifest,
                &polyplug::loader::BundleSource::Path(bad_manifest.path.clone()),
                &runtime
            )
            .is_err(),
        "bad load should fail"
    );

    let result: Result<(), LoaderError> = loader.load(
        &good_manifest,
        &polyplug::loader::BundleSource::Path(good_manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "recovery load failed: {result:?}");
}

/// `BundleInitContext.bundle_path` is a valid non-empty string for path loads.
#[test]
fn test_plugin_context_bundle_path_accessible() {
    let plugin_src: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

class _StringView(ctypes.Structure):
    _fields_ = [("ptr", ctypes.c_void_p), ("len", ctypes.c_size_t)]

class _BundleInitContext(ctypes.Structure):
    _fields_ = [("bundle_id", ctypes.c_uint64), ("bundle_path", _StringView)]

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    pass

def polyplug_init(_host_interface: int, ctx_addr: int):
    ctx = _BundleInitContext.from_address(ctx_addr)
    assert ctx.bundle_path.ptr is not None and ctx.bundle_path.ptr != 0
    assert ctx.bundle_path.len > 0
    return [{"contract": "ctxcheck@1", "factory": lambda host_ptr: None, "functions": [_fn0]}], _ABI_OK
"#;

    let (_dir, path) = write_bundle("ctx_check", plugin_src);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "ctx_check");
    let result: Result<(), LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "context check plugin failed: {result:?}");
}

/// Split-module bundle: a helper module defines `polyplug_init` (which RETURNS
/// its registrations) and the entry module only `from helper import
/// polyplug_init`. This mirrors the generated layout, where the entry file
/// imports `polyplug_init` from `generated/guest/contracts.py`.
///
/// Because the registrations flow through `polyplug_init`'s return value (not a
/// module namespace), the split-module and single-file layouts register
/// identically — load + register + dispatch must all work.
#[test]
fn test_split_module_registrations_via_init_globals() {
    // The helper's callable calls `arena_alloc(16, arena_ptr)` during dispatch,
    // using the allocator the loader passed as the final argument (no module
    // injection). The dispatch passes a null arena, so the allocator takes the
    // host-alloc fallback and must return a nonzero address; the callable writes
    // that address (truthiness) into `out`.
    let helper_src: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    buf = arena_alloc(16, arena_ptr)
    if buf == 0:
        raise RuntimeError("arena_alloc returned 0")
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int32))[0] = 0x2A

def polyplug_init(host_interface: int, ctx: int):
    return [
        {
            "contract": "splitmod@1",
            "plugin_name": "splitmod_plugin",
            "factory": lambda host_ptr: None,
            "functions": [_fn0],
        },
    ], _ABI_OK
"#;
    let entry_src: &str = r#"
from _splitmod_helper import polyplug_init
"#;

    let dir: TempDir = TempDir::new().expect("tempdir");
    fs::write(dir.path().join("_splitmod_helper.py"), helper_src).expect("write helper module");
    let entry_path: PathBuf = dir.path().join("bundle.py");
    fs::write(&entry_path, entry_src).expect("write entry module");

    let manifest: ManifestData = make_manifest(&entry_path, "splitmod");
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();

    let result: Result<(), LoaderError> = loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    );
    assert!(result.is_ok(), "split-module load failed: {result:?}");

    let mut out_buf: i32 = 0;
    // SAFETY: out points at a valid i32; the callable writes a 4-byte int there.
    let err: AbiError = unsafe {
        dispatch(
            &runtime,
            GuestContractId::new("splitmod", 1).id(),
            0,
            core::ptr::null(),
            &mut out_buf as *mut i32 as *mut (),
        )
    };
    assert_eq!(err.code, AbiErrorCode::Ok as u32, "dispatch should succeed");
    assert_eq!(out_buf, 0x2A, "callable should write 0x2A into out");
}

// ─── Unload: sys.modules purge ───────────────────────────────────────────────────

/// Count `sys.modules` keys that are re-keyed bundle modules (prefix
/// `__polyplug_bundle_`) AND reference `helper_substr` (the bundle's sibling
/// module name), holding the GIL via `Python::attach` to mirror the crate.
fn count_bundle_modules(helper_substr: &str) -> usize {
    Python::attach(|py: Python<'_>| -> usize {
        let sys_mod: pyo3::Bound<'_, PyModule> = PyModule::import(py, "sys").expect("sys import");
        let modules: pyo3::Bound<'_, pyo3::PyAny> =
            sys_mod.getattr("modules").expect("sys.modules");
        let dict: pyo3::Bound<'_, PyDict> =
            modules.cast_into::<PyDict>().expect("sys.modules dict");
        let mut count: usize = 0;
        for (key, _value) in dict.iter() {
            let key_str: String = match key.extract::<String>() {
                Ok(s) => s,
                Err(_) => continue,
            };
            if key_str.starts_with("__polyplug_bundle_") && key_str.contains(helper_substr) {
                count += 1;
            }
        }
        count
    })
}

/// Write a split-module bundle (entry imports a sibling helper that physically
/// lives under the bundle dir) so the isolation pass actually re-keys at least one
/// in-bundle module into `sys.modules`. Returns the temp dir and entry path.
fn write_split_bundle(name: &str, helper_module: &str, contract: &str) -> (TempDir, PathBuf) {
    let helper_src: String = format!(
        r#"
_ABI_OK = type("AbiError", (), {{"code": 0}})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    pass

def polyplug_init(host_interface: int, ctx: int):
    return [
        {{
            "contract": "{contract}",
            "plugin_name": "{name}_plugin",
            "factory": lambda host_ptr: None,
            "functions": [_fn0],
        }},
    ], _ABI_OK
"#
    );
    let entry_src: String = format!("from {helper_module} import polyplug_init\n");

    let dir: TempDir = TempDir::new().expect("tempdir");
    fs::write(dir.path().join(format!("{helper_module}.py")), helper_src).expect("write helper");
    let entry_path: PathBuf = dir.path().join("bundle.py");
    fs::write(&entry_path, entry_src).expect("write entry");
    (dir, entry_path)
}

/// Unloading a bundle ALWAYS purges its re-keyed `sys.modules` entries so a later
/// load re-imports fresh source. Purge is uniform: unload always reclaims the import
/// cache rather than parking it alive.
#[test]
fn unload_purges_bundle_modules_from_sys_modules() {
    let bundle_name: &str = "reclaim_purge";
    let helper_module: &str = "_reclaim_purge_helper";
    let (_dir, path) = write_split_bundle(bundle_name, helper_module, "reclaimpurge@1");

    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, bundle_name);

    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    let before: usize = count_bundle_modules(helper_module);
    assert!(
        before > 0,
        "bundle's helper module must be re-keyed into sys.modules after load"
    );

    loader
        .unload(BundleId::from_u64(bundle_id(bundle_name)), &runtime)
        .expect("unload must succeed");

    let after: usize = count_bundle_modules(helper_module);
    assert_eq!(
        after, 0,
        "unload must purge the bundle's re-keyed sys.modules entries"
    );
}

// ─── Arena isolation (parameterized-arena protocol) ─────────────────────────────

/// Plugin for the nested-reentrancy arena test.
///
/// fn_id 0 (OUTER) re-enters the SAME bundle through `python_vm_dispatch` to run
/// fn_id 1 (INNER) — a genuine same-thread nested dispatch — by calling the
/// test-injected builtin `__polyplug_test_nested_dispatch()` (a Rust closure that
/// resolves this contract and calls its VM dispatch with a NULL arena). After the
/// nested call returns, OUTER allocates a 64-byte buffer from its OWN `arena_ptr`
/// via `arena_alloc(size, arena)` and writes the address into `out_ptr`.
/// fn_id 1 (INNER) allocates from its own (null) arena and ignores `out`.
///
/// Going through a real `python_vm_dispatch` reentry — rather than a plain Python
/// call — is what would have triggered the old shared-cell bug: the INNER call's
/// exit-time clear-to-0 wiped the cell, so OUTER's post-nested allocation (reading
/// the cell) fell back to host->alloc and escaped the outer arena. With the arena
/// (and its allocator) threaded as explicit arguments, OUTER always uses its own
/// `arena_ptr`.
///
/// The nested re-entry is driven from Rust (no ctypes struct-return calls, which
/// are UB on some targets) so the test exercises the loader's actual dispatch path.
const NESTED_ARENA_PLUGIN_SRC: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

def _inner(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    arena_alloc(16, arena_ptr)

def _outer(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    # Real nested dispatch into fn_id 1 via the test-injected Rust trampoline.
    __polyplug_test_nested_dispatch()
    # After the nested call returned, allocate from the OUTER arena_ptr and report.
    addr = arena_alloc(64, arena_ptr)
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int64))[0] = addr

def polyplug_init(host_interface: int, ctx: int):
    return [
        {"contract": "nestedarena@1", "factory": lambda host_ptr: None, "functions": [_outer, _inner]},
    ], _ABI_OK
"#;

fn nestedarena_contract_id() -> u64 {
    GuestContractId::new("nestedarena", 1).id()
}

/// Nested same-thread cross-call must NOT corrupt the outer call's arena.
///
/// The outer guest fn re-enters the same bundle (a real `python_vm_dispatch`
/// nested dispatch of fn_id 1 via a Rust trampoline injected into `builtins`),
/// then allocates from its OWN `arena_ptr`. With the arena threaded explicitly
/// (not via a shared cell), the post-nested allocation lands inside the OUTER
/// arena's buffer. Under the old shared-cell protocol the nested call's
/// clear-to-0 wiped the cell and the outer allocation fell back to host->alloc
/// (outside the arena buffer) — the bug this test pins.
#[test]
fn test_nested_dispatch_preserves_outer_arena() {
    let contract_id: u64 = nestedarena_contract_id();
    let (_dir, path) = write_bundle("nested_arena", NESTED_ARENA_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "nested_arena");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // Inject a builtin `__polyplug_test_nested_dispatch()` that performs a real
    // nested VM dispatch of fn_id 1 (null arena) from Rust. Putting it in
    // `builtins` makes it reachable from the bundle module without touching the
    // bundle's re-keyed sys.modules entry. The runtime pointer is captured as a
    // usize (raw pointers are not Send, but it stays valid for the test).
    let runtime_addr: usize = Arc::as_ptr(&runtime) as usize;
    Python::attach(|py: Python<'_>| {
        let trampoline = pyo3::types::PyCFunction::new_closure(
            py,
            None,
            None,
            move |_args: &pyo3::Bound<'_, pyo3::types::PyTuple>,
                  _kwargs: Option<&pyo3::Bound<'_, PyDict>>|
                  -> i64 {
                // SAFETY: runtime_addr is the live Runtime for the test's lifetime.
                let rt: &Runtime = unsafe { &*(runtime_addr as *const Runtime) };
                // SAFETY: fn_id 1 (inner) only allocates from its (null) arena.
                let err: AbiError = unsafe {
                    dispatch_with_arena(
                        rt,
                        contract_id,
                        1,
                        core::ptr::null(),
                        core::ptr::null_mut(),
                        core::ptr::null_mut(),
                    )
                };
                err.code as i64
            },
        )
        .expect("trampoline creation must succeed");
        let builtins: pyo3::Bound<'_, PyModule> =
            PyModule::import(py, "builtins").expect("builtins import");
        builtins
            .setattr("__polyplug_test_nested_dispatch", trampoline)
            .expect("inject trampoline builtin");
    });

    // Outer arena over a 4 KiB buffer (null host: 64-byte alloc fits the primary
    // region, so no overflow / host needed). The buffer must outlive the dispatch.
    let mut buf: Vec<u8> = vec![0_u8; 4096];
    let lo: usize = buf.as_ptr() as usize;
    let hi: usize = lo + buf.len();
    let mut arena: polyplug_abi::CallArena =
        polyplug_abi::CallArena::new(&mut buf, core::ptr::null());

    let mut out: i64 = 0;
    // SAFETY: out is a valid local i64; arena is a valid CallArena over `buf`,
    // which outlives this call; the guest writes the allocated address into out.
    let err: AbiError = unsafe {
        dispatch_with_arena(
            &runtime,
            contract_id,
            0,
            core::ptr::null(),
            &mut out as *mut i64 as *mut (),
            &mut arena as *mut polyplug_abi::CallArena,
        )
    };
    assert!(
        err.is_ok(),
        "outer dispatch must succeed: code={}",
        err.code
    );

    let p: usize = out as usize;
    assert!(
        p >= lo && p < hi,
        "outer allocation {p:#x} must land inside the OUTER arena buffer [{lo:#x}, {hi:#x}); a value outside means the nested call's clear wiped the outer arena (shared-cell bug)"
    );
}

/// Plugin for the two-thread arena test: one fn that allocates 64 bytes from its
/// `arena_ptr` and writes the address into `out_ptr`.
const ARENA_ECHO_PLUGIN_SRC: &str = r#"
import ctypes

_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    addr = arena_alloc(64, arena_ptr)
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int64))[0] = addr

def polyplug_init(host_interface: int, ctx: int):
    return [
        {"contract": "arenaecho@1", "factory": lambda host_ptr: None, "functions": [_fn0]},
    ], _ABI_OK
"#;

fn arenaecho_contract_id() -> u64 {
    GuestContractId::new("arenaecho", 1).id()
}

/// Two threads dispatching into the SAME bundle with DISTINCT arenas must each
/// allocate from their OWN arena.
///
/// CPython's GIL serializes Python execution, so the threads do not truly run the
/// guest body in parallel; the invariant this pins is that allocation reads the
/// arena from the per-call ARGUMENT (which differs per thread) and never from a
/// shared cell that the other thread could have overwritten. Each thread runs
/// many iterations resetting its own arena and asserts every allocation lands in
/// its own buffer. The two buffers are disjoint so a misattribution is detectable.
#[test]
fn test_concurrent_dispatch_distinct_arenas_isolated() {
    let contract_id: u64 = arenaecho_contract_id();
    let (_dir, path) = write_bundle("arena_echo", ARENA_ECHO_PLUGIN_SRC);
    let loader: PythonLoader = PythonLoader::default();
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "arena_echo");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("load must succeed");

    // Two disjoint 4 KiB buffers + arenas, leaked so their addresses are valid
    // across both worker threads (null host: 64-byte allocs fit the primary region).
    let buf_a: &'static mut [u8] = Box::leak(vec![0_u8; 4096].into_boxed_slice());
    let buf_b: &'static mut [u8] = Box::leak(vec![0_u8; 4096].into_boxed_slice());
    let a_lo: usize = buf_a.as_ptr() as usize;
    let a_hi: usize = a_lo + buf_a.len();
    let b_lo: usize = buf_b.as_ptr() as usize;
    let b_hi: usize = b_lo + buf_b.len();
    let arena_a: &'static mut polyplug_abi::CallArena = Box::leak(Box::new(
        polyplug_abi::CallArena::new(buf_a, core::ptr::null()),
    ));
    let arena_b: &'static mut polyplug_abi::CallArena = Box::leak(Box::new(
        polyplug_abi::CallArena::new(buf_b, core::ptr::null()),
    ));
    let arena_a_addr: usize = arena_a as *mut polyplug_abi::CallArena as usize;
    let arena_b_addr: usize = arena_b as *mut polyplug_abi::CallArena as usize;

    const ITERS: usize = 500;
    let runtime_a: Arc<Runtime> = Arc::clone(&runtime);
    let runtime_b: Arc<Runtime> = Arc::clone(&runtime);

    let handle_a: std::thread::JoinHandle<Result<(), String>> = std::thread::spawn(move || {
        for i in 0..ITERS {
            // SAFETY: arena_a_addr is the live leaked arena for this worker.
            let arena: &mut polyplug_abi::CallArena =
                unsafe { &mut *(arena_a_addr as *mut polyplug_abi::CallArena) };
            arena.reset();
            let mut out: i64 = 0;
            // SAFETY: out is a valid local; arena_a is valid; contract is loaded.
            let err: AbiError = unsafe {
                dispatch_with_arena(
                    &runtime_a,
                    contract_id,
                    0,
                    core::ptr::null(),
                    &mut out as *mut i64 as *mut (),
                    arena_a_addr as *mut polyplug_abi::CallArena,
                )
            };
            if !err.is_ok() {
                return Err(format!("A iter {i}: dispatch failed code={}", err.code));
            }
            let p: usize = out as usize;
            if !(p >= a_lo && p < a_hi) {
                return Err(format!(
                    "A iter {i}: allocation {p:#x} escaped arena A buffer [{a_lo:#x}, {a_hi:#x})"
                ));
            }
        }
        Ok(())
    });

    let handle_b: std::thread::JoinHandle<Result<(), String>> = std::thread::spawn(move || {
        for i in 0..ITERS {
            // SAFETY: arena_b_addr is the live leaked arena for this worker.
            let arena: &mut polyplug_abi::CallArena =
                unsafe { &mut *(arena_b_addr as *mut polyplug_abi::CallArena) };
            arena.reset();
            let mut out: i64 = 0;
            // SAFETY: out is a valid local; arena_b is valid; contract is loaded.
            let err: AbiError = unsafe {
                dispatch_with_arena(
                    &runtime_b,
                    contract_id,
                    0,
                    core::ptr::null(),
                    &mut out as *mut i64 as *mut (),
                    arena_b_addr as *mut polyplug_abi::CallArena,
                )
            };
            if !err.is_ok() {
                return Err(format!("B iter {i}: dispatch failed code={}", err.code));
            }
            let p: usize = out as usize;
            if !(p >= b_lo && p < b_hi) {
                return Err(format!(
                    "B iter {i}: allocation {p:#x} escaped arena B buffer [{b_lo:#x}, {b_hi:#x})"
                ));
            }
        }
        Ok(())
    });

    let a_outcome: Result<(), String> = handle_a.join().expect("thread A must not panic");
    let b_outcome: Result<(), String> = handle_b.join().expect("thread B must not panic");
    if let Err(e) = a_outcome {
        panic!("{e}");
    }
    if let Err(e) = b_outcome {
        panic!("{e}");
    }
}

// ─── Multi-runtime isolation proof (process-global SharedState / nonce) ──────────

/// Entry-module source for a bundle whose contract function 0 writes the integer
/// returned by a **bundle-local** sibling module `shared_helper.VALUE` into `out`.
///
/// Two runtimes load two different bundles that share the *same name* (hence the
/// same `bundle_id` name-hash) and each ship their *own* `shared_helper.py` with
/// a different `VALUE`. Because CPython's `sys.modules` is process-global, the
/// per-bundle module-isolation pass must re-key each bundle's `shared_helper`
/// under a prefix made unique by the runtime-vended nonce — otherwise the second
/// runtime would import the first's cached `shared_helper` and observe the wrong
/// value. The `{contract}` placeholder lets each runtime register a distinct
/// contract id so both contracts coexist in the (separate) registries.
const SHARED_NAME_ENTRY_SRC: &str = r#"
import ctypes
from shared_helper import VALUE

_ABI_OK = type("AbiError", (), {"code": 0})()

def _fn0(impl, args_ptr, out_ptr, arena_ptr, arena_alloc):
    ctypes.cast(out_ptr, ctypes.POINTER(ctypes.c_int32))[0] = VALUE

def polyplug_init(host_interface: int, ctx: int):
    return [
        {"contract": "{contract}", "factory": lambda host_ptr: None, "functions": [_fn0]},
    ], _ABI_OK
"#;

/// Write a same-named bundle whose `shared_helper.VALUE == value` and whose
/// contract is `"{contract_name}@1"`. Returns the temp dir (kept alive by the
/// caller) and the entry-file path.
fn write_shared_name_bundle(contract_name: &str, value: i32) -> (TempDir, PathBuf) {
    let dir: TempDir = TempDir::new().expect("tempdir");
    let entry: PathBuf = dir.path().join("bundle.py");
    let entry_src: String =
        SHARED_NAME_ENTRY_SRC.replace("{contract}", &format!("{contract_name}@1"));
    fs::write(&entry, entry_src).expect("write bundle.py");
    fs::write(
        dir.path().join("shared_helper.py"),
        format!("VALUE = {value}\n"),
    )
    .expect("write shared_helper.py");

    // Both bundles deliberately share the SAME name so their bundle_id collides.
    let name: &str = "shared_name";
    let manifest: String = format!(
        r#"id = {}
name = "{}"
loader = "python"
file = "bundle.py"
"#,
        bundle_id(name),
        name
    );
    fs::write(dir.path().join("manifest.toml"), &manifest).expect("write manifest.toml");

    (dir, entry)
}

/// Two `Runtime` instances in ONE process each load a same-named Python bundle
/// (identical `bundle_id`) carrying its own `shared_helper.py`, then dispatch.
///
/// This is the runtime proof for Wave C1's static-free Python loader:
/// - A double `Py_Initialize` (if the once-per-process init guard regressed)
///   would panic/abort here.
/// - A nonce collision (if the per-bundle `sys.modules` re-key prefix were not
///   made unique by the runtime-vended nonce) would make runtime B import
///   runtime A's cached `shared_helper`, so B would observe A's `VALUE`.
///
/// Both must dispatch their OWN value, proving the process-global `SharedState`
/// vends a unique nonce per load across distinct runtimes.
#[test]
fn two_runtimes_same_named_bundle_do_not_collide_in_sys_modules() {
    let name: &str = "shared_name";

    let (_dir_a, path_a) = write_shared_name_bundle("alpha_contract", 0x11);
    let (_dir_b, path_b) = write_shared_name_bundle("beta_contract", 0x22);

    let loader_a: PythonLoader = PythonLoader::default();
    let loader_b: PythonLoader = PythonLoader::default();
    let runtime_a: Arc<Runtime> = make_runtime();
    let runtime_b: Arc<Runtime> = make_runtime();

    let manifest_a: ManifestData = make_manifest(&path_a, name);
    let manifest_b: ManifestData = make_manifest(&path_b, name);

    loader_a
        .load(
            &manifest_a,
            &polyplug::loader::BundleSource::Path(manifest_a.path.clone()),
            &runtime_a,
        )
        .expect("runtime A load must succeed");
    loader_b
        .load(
            &manifest_b,
            &polyplug::loader::BundleSource::Path(manifest_b.path.clone()),
            &runtime_b,
        )
        .expect("runtime B load must succeed");

    let alpha_cid: u64 = GuestContractId::new("alpha_contract", 1).id();
    let beta_cid: u64 = GuestContractId::new("beta_contract", 1).id();

    let mut out_a: i32 = 0;
    // SAFETY: out_a is a valid i32; the callable writes a 4-byte int there.
    let err_a: AbiError = unsafe {
        dispatch(
            &runtime_a,
            alpha_cid,
            0,
            core::ptr::null(),
            &mut out_a as *mut i32 as *mut (),
        )
    };
    assert!(err_a.is_ok(), "A dispatch failed code={}", err_a.code);

    let mut out_b: i32 = 0;
    // SAFETY: out_b is a valid i32; the callable writes a 4-byte int there.
    let err_b: AbiError = unsafe {
        dispatch(
            &runtime_b,
            beta_cid,
            0,
            core::ptr::null(),
            &mut out_b as *mut i32 as *mut (),
        )
    };
    assert!(err_b.is_ok(), "B dispatch failed code={}", err_b.code);

    assert_eq!(
        out_a, 0x11,
        "runtime A must read its OWN shared_helper.VALUE (0x11)"
    );
    assert_eq!(
        out_b, 0x22,
        "runtime B must read its OWN shared_helper.VALUE (0x22), not A's cached module"
    );
}