polyplug_lua 0.1.1

Lua loader for polyplug - loads LuaJIT plugins via mlua
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
//! Integration tests for LuaLoader and the Lua VM initialization / bundle loading pipeline.
//!
//! Registration shape: `polyplug_init` RETURNS `(registrations, abi_error)`; each
//! `registrations[<contract>]` entry carries a `factory(host_ptr) -> impl` (the
//! loader calls it to build the default impl and every per-instance impl) and a
//! `functions` table whose entries have the signature `(instance, args_ptr,
//! out_ptr, arena_ptr, arena_alloc)` — the loader passes the resolved per-instance
//! impl object as the first argument and threads the per-call arena + allocator.

#![allow(clippy::expect_used)]

use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use polyplug::error::LoaderError;
use polyplug::error::RuntimeError;
use polyplug::loader::BundleLoader;
use polyplug::loader::manifest::ManifestData;
use polyplug::runtime::Runtime;
use polyplug::runtime::RuntimeBuilder;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::GuestContractInterface;
use polyplug_abi::runtime::Compatibility;
use polyplug_abi::runtime::RuntimeConfig;
use polyplug_abi::types::LogLevel;
use polyplug_lua::LuaConfig;
use polyplug_lua::LuaLoader;
use polyplug_utils::GuestContractId;

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

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

/// Write `content` to a temp bundle directory with manifest.toml.
/// Returns the directory (to keep it alive) and the path to bundle.lua.
fn write_temp_bundle(name: &str, content: &[u8]) -> (tempfile::TempDir, PathBuf) {
    let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
    let path: PathBuf = dir.path().join("bundle.lua");
    std::fs::write(&path, content).expect("write bundle.lua");

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

    (dir, path)
}

/// A minimal valid Lua plugin script that implements the `test.loader@1`
/// contract with a single no-op function.
fn valid_plugin_script() -> &'static [u8] {
    br#"
local ffi = require("ffi")
local function impl_noop(_instance, _args_ptr, _out_ptr)
end
function polyplug_init(_registrar_ptr, _ctx_ptr)
    return {
        ["test.loader"] = {
            contract_version = 1,
            plugin_name      = "test-loader-unit",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_noop },
        },
    }, { code = 0 }
end
"#
}

/// A Lua plugin that defines two functions so we can verify function_count.
fn two_function_plugin_script() -> &'static [u8] {
    br#"
local ffi = require("ffi")
local function impl_a(_instance, _args_ptr, _out_ptr) end
local function impl_b(_instance, _args_ptr, _out_ptr) end
function polyplug_init(_registrar_ptr, _ctx_ptr)
    return {
        ["test.two"] = {
            contract_version = 1,
            plugin_name      = "test-two-unit",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_a, [1] = impl_b },
        },
    }, { code = 0 }
end
"#
}

/// A Lua plugin that registers TWO distinct contracts in one bundle. This is the
/// regression fixture for the multi-contract bug: the old flat `_polyplug_handlers`
/// table with a first-wins guard silently dropped the second contract.
fn two_contract_plugin_script() -> &'static [u8] {
    br#"
local ffi = require("ffi")
local function impl_first(_instance, _args_ptr, _out_ptr) end
local function impl_second_a(_instance, _args_ptr, _out_ptr) end
local function impl_second_b(_instance, _args_ptr, _out_ptr) end
function polyplug_init(_registrar_ptr, _ctx_ptr)
    return {
        ["test.first"] = {
            contract_version = 1,
            plugin_name      = "test-multi-first",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_first },
        },
        ["test.second"] = {
            contract_version = 1,
            plugin_name      = "test-multi-second",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_second_a, [1] = impl_second_b },
        },
    }, { code = 0 }
end
"#
}

/// Create a ManifestData for a Lua bundle at the given path.
fn make_manifest(path: &Path, name: &str) -> ManifestData {
    let bundle_id: u64 = polyplug_utils::bundle_id(name);
    ManifestData {
        id: bundle_id,
        name: name.to_owned(),
        loader: "lua".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(),
    }
}

/// Load the supplied Lua source via `LuaLoader::load` and return the result.
fn load_script(path: &Path, name: &str) -> Result<(), LoaderError> {
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(path, name);
    loader.load(
        &manifest,
        &polyplug::loader::BundleSource::Path(manifest.path.clone()),
        &runtime,
    )
}

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

// ── 1. Runtime name ──────────────────────────────────────────────────────────

#[test]
fn lua_loader_loader_name_is_lua() {
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    assert_eq!(loader.loader_name(), "lua");
}

// ── 2. Lua state initialization ──────────────────────────────────────────────

/// Loading a valid bundle must succeed — which implicitly verifies that the
/// LuaJIT VM was initialized correctly.
#[test]
fn lua_state_initializes_on_first_load() {
    let (_dir, path) = write_temp_bundle("lua_loader_init_test", valid_plugin_script());
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_init_test");
    assert!(
        result.is_ok(),
        "Lua VM must initialize and bundle must load: {:?}",
        result.err()
    );
}

/// Calling `LuaLoader::load` a second time re-uses the same VM without
/// panicking (idempotent initialization).
#[test]
fn lua_state_init_is_idempotent() {
    let (_dir, path) = write_temp_bundle("lua_loader_idempotent", valid_plugin_script());
    load_script(&path, "lua_loader_idempotent").expect("first load must succeed");
    // Second load of the same file: VM is already initialized — must not panic.
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_idempotent");
    assert!(
        result.is_ok(),
        "second load must succeed (idempotent VM init): {:?}",
        result.err()
    );
}

// ── 3. Bundle loading — valid script ─────────────────────────────────────────

#[test]
fn load_valid_bundle_succeeds() {
    let (_dir, path) = write_temp_bundle("lua_loader_valid", valid_plugin_script());
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_valid");
    assert!(result.is_ok(), "valid bundle must load: {:?}", result.err());
}

// ── 4. Bundle loading — syntax error ─────────────────────────────────────────

/// A Lua script with a syntax error must produce a `LoaderError::InitFailed` error.
#[test]
fn load_syntax_error_returns_script_load_failed() {
    let (_dir, path) = write_temp_bundle(
        "lua_loader_syntax_error",
        b"function polyplug_init( -- SYNTAX ERROR: unclosed paren\n",
    );
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_syntax_error");
    assert!(result.is_err(), "syntax error must produce an Err");
    let err: LoaderError = result.expect_err("expected Err for syntax error");
    assert!(
        matches!(err, LoaderError::InitFailed { .. }),
        "expected InitFailed for syntax error, got: {:?}",
        err
    );
}

// ── 5. Bundle loading — runtime error in polyplug_init ───────────────────────

/// A script where `polyplug_init` raises a Lua error at runtime must produce
/// `LoaderError::InitFailed`.
#[test]
fn load_runtime_error_in_init_returns_init_raised_error() {
    let (_dir, path) = write_temp_bundle(
        "lua_loader_runtime_err",
        b"function polyplug_init(_reg, _ctx)\n  error('deliberate runtime error')\nend\n",
    );
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_runtime_err");
    assert!(result.is_err(), "runtime error in init must produce Err");
    let err: LoaderError = result.expect_err("expected Err for runtime error in init");
    assert!(
        matches!(err, LoaderError::InitFailed { .. }),
        "expected InitFailed for runtime error in init, got: {:?}",
        err
    );
}

// ── 6. Missing polyplug_init ─────────────────────────────────────────────────

/// A script that does not define `polyplug_init` must return
/// `LoaderError::InitFailed`.
#[test]
fn load_missing_polyplug_init_returns_typed_error() {
    let (_dir, path) =
        write_temp_bundle("lua_loader_no_init", b"local x = 1  -- no polyplug_init\n");
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_no_init");
    assert!(result.is_err(), "missing init must produce Err");
    let err: LoaderError = result.expect_err("expected Err for missing polyplug_init");
    assert!(
        matches!(err, LoaderError::InitFailed { .. }),
        "expected InitFailed for missing polyplug_init, got: {:?}",
        err
    );
}

// ── 7. Non-existent file ──────────────────────────────────────────────────────

#[test]
fn load_nonexistent_path_returns_script_load_failed() {
    let dir: tempfile::TempDir = tempfile::tempdir().expect("tempdir");
    let path: PathBuf = dir.path().join("this_file_does_not_exist_42.lua");
    let result: Result<(), LoaderError> = load_script(&path, "nonexistent");
    assert!(result.is_err(), "missing file must produce Err");
    let err: LoaderError = result.expect_err("expected Err for nonexistent file");
    assert!(
        matches!(err, LoaderError::InitFailed { .. }),
        "expected InitFailed for missing file, got: {:?}",
        err
    );
}

// ── 8. VTable registration ────────────────────────────────────────────────────

/// After a successful load, the registry must contain a plugin for the
/// expected contract_id with the correct function count.
#[test]
fn vtable_is_registered_after_load() {
    let (_dir, path) = write_temp_bundle("lua_loader_vtable", valid_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_vtable");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("valid bundle must load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let handle: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0);
    assert!(
        handle.is_ok(),
        "registry must contain test.loader@1 after load"
    );
    let handle: GuestContractHandle = handle.expect("handle must be Ok");
    let vtable_ptr: Result<*const GuestContractInterface, polyplug::error::RegistryError> =
        runtime.registry().resolve_guest_contract(handle);
    assert!(vtable_ptr.is_ok(), "handle must resolve to a vtable");
    // SAFETY: vtable_ptr is a 'static pointer produced by LuaLoader; the Lua VM
    // and leaked GuestContractInterface outlive this test.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr.expect("vtable must resolve") };
    // valid_plugin_script has exactly one function: fn_id 0 must dispatch to Ok,
    // and fn_id 1 must report FunctionNotAvailable.
    assert_function_count(vtable, 1);
}

/// After a successful load, the contract must be attributed to the bundle's REAL
/// id in the registry — not bundle 0. The registration runs after Lua
/// `polyplug_init` RETURNS its `(registrations, abi_error)` pair, so the
/// init-bundle window must stay open across the registration loop for
/// `host_register_guest_contract` to attribute it correctly. Invalidating by the
/// real id must then remove it.
#[test]
fn registrations_attributed_to_real_bundle_id() {
    let (_dir, path) = write_temp_bundle("lua_loader_attribution", valid_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_attribution");
    let bundle_id: u64 = manifest.id;
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("valid bundle must load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);

    // The contract must be findable under the REAL bundle id.
    let by_real: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.find_guest_contract_by_bundle(bundle_id, contract_id, 0);
    assert!(
        by_real.is_ok(),
        "contract must be attributed to the real bundle id {bundle_id}, not bundle 0"
    );

    // And it must NOT be attributed to bundle 0.
    let by_zero: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.find_guest_contract_by_bundle(0, contract_id, 0);
    assert!(
        by_zero.is_err(),
        "contract must not be attributed to bundle 0"
    );

    // Invalidating by the real bundle id must remove the contract from the registry.
    runtime
        .registry()
        .invalidate_bundle(polyplug_utils::BundleId::from_u64(bundle_id))
        .expect("invalidate by real bundle id must succeed");
    let after: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0);
    assert!(
        after.is_err(),
        "contract must be gone after invalidating the real bundle id"
    );
}

/// Verify a VM-dispatch vtable exposes exactly `expected` functions by probing
/// fn_ids: indices `0..expected` must return `Ok`, and index `expected` must
/// return `FunctionNotAvailable`.
fn assert_function_count(vtable: &GuestContractInterface, expected: u32) {
    assert_eq!(
        vtable.dispatch_type,
        polyplug_abi::DispatchType::VirtualMachine,
        "Lua loader must use VM dispatch"
    );
    for fn_id in 0..expected {
        let mut result: AbiError = AbiError::ok();
        // SAFETY: dispatch.vm.call is a valid function pointer; the noop functions
        // ignore the null args/out pointers.
        unsafe {
            (vtable.dispatch.vm.call)(
                vtable.dispatch.vm.loader_data,
                GuestContractInstance::null(),
                fn_id,
                core::ptr::null::<()>(),
                core::ptr::null_mut::<()>(),
                core::ptr::null_mut(),
                &mut result as *mut AbiError,
            );
        }
        assert_eq!(
            result.code,
            AbiErrorCode::Ok as u32,
            "fn_id {fn_id} must dispatch to Ok"
        );
    }
    let mut missing: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is a valid function pointer.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            expected,
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut missing as *mut AbiError,
        );
    }
    assert_eq!(
        missing.code,
        AbiErrorCode::FunctionNotAvailable as u32,
        "fn_id {expected} must report FunctionNotAvailable"
    );
}

/// After loading the two-function plugin, function_count must equal 2.
#[test]
fn vtable_function_count_matches_script() {
    let (_dir, path) = write_temp_bundle("lua_loader_two_fn", two_function_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_two_fn");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("two-function bundle must load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.two", 1);
    let handle: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0);
    let handle: GuestContractHandle = handle.expect("test.two@1 must be registered");
    let vtable_ptr: Result<*const GuestContractInterface, polyplug::error::RegistryError> =
        runtime.registry().resolve_guest_contract(handle);
    // SAFETY: see vtable_is_registered_after_load.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr.expect("vtable must resolve") };
    // two_function_plugin_script must register exactly 2 functions.
    assert_function_count(vtable, 2);
}

/// The contract_id stored in the vtable must match the FNV-1a hash computed
/// from the contract name and version declared in the script.
#[test]
fn vtable_contract_id_matches_computed_hash() {
    let (_dir, path) = write_temp_bundle("lua_loader_cid", valid_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_cid");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("valid bundle must load");

    let expected_cid: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let handle: Result<GuestContractHandle, polyplug::error::RegistryError> = runtime
        .registry()
        .find(GuestContractId::from_u64(expected_cid), 0);
    let handle: GuestContractHandle = handle.expect("test.loader@1 must be registered");
    let vtable_ptr: Result<*const GuestContractInterface, polyplug::error::RegistryError> =
        runtime.registry().resolve_guest_contract(handle);
    // SAFETY: see vtable_is_registered_after_load.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr.expect("vtable must resolve") };
    assert_eq!(
        vtable.contract_id,
        GuestContractId::from_u64(expected_cid),
        "contract_id in vtable must match FNV-1a hash of 'test.loader@1'"
    );
}

// ── 9. Stack management — sequential loads ────────────────────────────────────

/// Load two different plugins in sequence: each must succeed and register its
/// own contract.
#[test]
fn sequential_loads_both_succeed() {
    let (_dir1, path1) = write_temp_bundle("lua_loader_seq1", valid_plugin_script());
    let (_dir2, path2) = write_temp_bundle("lua_loader_seq2", two_function_plugin_script());

    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest1: ManifestData = make_manifest(&path1, "lua_loader_seq1");
    let manifest2: ManifestData = make_manifest(&path2, "lua_loader_seq2");
    loader
        .load(
            &manifest1,
            &polyplug::loader::BundleSource::Path(manifest1.path.clone()),
            &runtime,
        )
        .expect("first sequential load must succeed");
    loader
        .load(
            &manifest2,
            &polyplug::loader::BundleSource::Path(manifest2.path.clone()),
            &runtime,
        )
        .expect("second sequential load must succeed");

    // Both contracts must be visible.
    let cid1: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let cid2: u64 = polyplug_utils::guest_contract_id("test.two", 1);

    let handle1: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.registry().find(GuestContractId::from_u64(cid1), 0);
    assert!(handle1.is_ok(), "test.loader must be registered");

    let handle2: Result<GuestContractHandle, polyplug::error::RegistryError> =
        runtime.registry().find(GuestContractId::from_u64(cid2), 0);
    assert!(handle2.is_ok(), "test.two must be registered");
}

// ── 9b. Multi-contract bundle ─────────────────────────────────────────────────

/// Regression test: a single Lua bundle that declares two contracts must
/// register BOTH. The previous flat `_polyplug_handlers` table with a first-wins
/// guard silently dropped every contract after the first.
#[test]
fn multi_contract_bundle_registers_all_contracts() {
    let (_dir, path) = write_temp_bundle("lua_loader_multi", two_contract_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_multi");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("multi-contract bundle must load");

    // Both contracts must be registered and resolvable.
    let first_cid: u64 = polyplug_utils::guest_contract_id("test.first", 1);
    let second_cid: u64 = polyplug_utils::guest_contract_id("test.second", 1);

    let first_handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(first_cid), 0)
        .expect("test.first@1 must be registered");
    let second_handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(second_cid), 0)
        .expect("test.second@1 must be registered");

    // Each contract must resolve to a vtable with the correct function count:
    // test.first has 1 function, test.second has 2.
    let first_vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(first_handle)
        .expect("test.first handle must resolve");
    let second_vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(second_handle)
        .expect("test.second handle must resolve");
    // SAFETY: first_vtable_ptr is a 'static leaked GuestContractInterface from
    // LuaLoader; the shared Lua VM and leaked interface outlive this test.
    let first_vtable: &GuestContractInterface = unsafe { &*first_vtable_ptr };
    // SAFETY: second_vtable_ptr is a 'static leaked GuestContractInterface from
    // LuaLoader; the shared Lua VM and leaked interface outlive this test.
    let second_vtable: &GuestContractInterface = unsafe { &*second_vtable_ptr };
    assert_function_count(first_vtable, 1);
    assert_function_count(second_vtable, 2);
}

// ── 10. Thread safety ─────────────────────────────────────────────────────────

/// Spawn multiple threads, each loading the same valid plugin.  The global
/// Mutex inside `LuaLoader` must prevent data races and every load must
/// either succeed or produce a recognized `RuntimeError` (no panics,
/// no UB).
///
/// Each bundle gets its own isolated Lua VM, so parallel loads are safe.
#[test]
fn concurrent_loaders_do_not_race() {
    let (_dir, path) = write_temp_bundle("lua_loader_thread_safety", valid_plugin_script());

    // Spawn 4 threads that all call LuaLoader::load on the same path.
    let path_arc: std::sync::Arc<PathBuf> = std::sync::Arc::new(path);
    let handles: Vec<std::thread::JoinHandle<Result<(), LoaderError>>> = (0_u32..4_u32)
        .map(|_| {
            let p: std::sync::Arc<PathBuf> = std::sync::Arc::clone(&path_arc);
            std::thread::spawn(move || {
                let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
                let runtime: Arc<Runtime> = RuntimeBuilder::new()
                    .loader(LuaLoader::new(LuaConfig::default()))
                    .build()
                    .expect("runtime build must succeed");
                let manifest: ManifestData = ManifestData {
                    id: polyplug_utils::bundle_id("lua_loader_thread_safety"),
                    name: "lua_loader_thread_safety".to_owned(),
                    loader: "lua".to_owned(),
                    file: p
                        .file_name()
                        .expect("bundle path must have a file name")
                        .to_string_lossy()
                        .into_owned(),
                    path: p
                        .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(),
                };
                loader.load(
                    &manifest,
                    &polyplug::loader::BundleSource::Path(manifest.path.clone()),
                    &runtime,
                )
            })
        })
        .collect::<Vec<std::thread::JoinHandle<Result<(), LoaderError>>>>();

    for handle in handles {
        // Each thread must not panic. Errors (e.g. DuplicateProvider inside
        // the callback) are acceptable — panics are not.
        let result: Result<(), LoaderError> = handle
            .join()
            .expect("thread must not panic during concurrent load");
        // The result may be Ok or a recognized RuntimeError.
        // We simply assert it is a valid discriminant (no silent UB).
        let _ = result;
    }
}

// ── 11. Dispatch — calling a registered Lua function ─────────────────────────

/// Load the valid plugin and invoke its single function through the vtable.
/// The noop function must return `AbiErrorCode::Ok` without panicking.
#[test]
fn vtable_function_dispatch_returns_abi_ok() {
    let (_dir, path) = write_temp_bundle("lua_loader_dispatch", valid_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let runtime: Arc<Runtime> = make_runtime();
    let manifest: ManifestData = make_manifest(&path, "lua_loader_dispatch");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("valid bundle must load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("test.loader@1 must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("handle must resolve to vtable");
    // SAFETY: vtable_ptr is a 'static leaked GuestContractInterface from LuaLoader.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr };

    // With VM dispatch, we call through the dispatch.vm.call function.
    assert_eq!(
        vtable.dispatch_type,
        polyplug_abi::DispatchType::VirtualMachine,
        "Lua loader must use VM dispatch"
    );

    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is a valid function pointer, loader_data is valid,
    // and we pass null pointers for args/out which the noop function ignores.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0, // fn_id = 0 (first function)
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(
        result.code,
        AbiErrorCode::Ok as u32,
        "noop function must return Ok, got code={}",
        result.code
    );
}

// ── 12. Hot-reload ────────────────────────────────────────────────────────────

/// Build a runtime with the given hot-reload setting and a registered LuaLoader.
fn make_runtime_with_hot_reload(enabled: bool) -> Arc<Runtime> {
    RuntimeBuilder::new()
        .config(RuntimeConfig {
            compatibility: Compatibility::Strict,
            hot_reload_enabled: enabled,
            on_reload: None,
            on_reload_user_data: core::ptr::null_mut(),
            ..Default::default()
        })
        .loader(LuaLoader::new(LuaConfig::default()))
        .build()
        .expect("runtime build must succeed")
}

/// When hot-reload is disabled in the runtime config, the runtime gate (which now
/// owns the hot-reload check — the lua loader's `reload` no longer inspects config)
/// must return `RuntimeError::HotReloadDisabled` without invoking the loader. The
/// loader still advertises `supports_hot_reload() == true`, so the config flag is the
/// sole reason the reload is refused here.
#[test]
fn lua_reload_disabled_returns_error() {
    let (_dir, path) = write_temp_bundle("lua_reload_disabled", valid_plugin_script());
    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    assert!(
        loader.supports_hot_reload(),
        "the lua loader supports hot-reload; only the config flag must gate it here"
    );
    let runtime: Arc<Runtime> = make_runtime_with_hot_reload(false);

    let result: Result<(), RuntimeError> = runtime.reload_bundle(path.as_path());
    assert!(
        matches!(result, Err(RuntimeError::HotReloadDisabled)),
        "reload_bundle with hot_reload_enabled=false must return HotReloadDisabled, got: {:?}",
        result
    );
}

// ── 13. BundleSource::Code / Bytes — in-memory source loading ────────────────

/// Absolute path to the on-disk Lua fixture bundle directory.
fn lua_fixture_dir() -> PathBuf {
    // CARGO_MANIFEST_DIR = crates/polyplug_lua; the fixture lives at the workspace
    // root under tests/fixtures/test_plugin_lua.
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("crates/ parent must exist")
        .parent()
        .expect("workspace root must exist")
        .join("tests")
        .join("fixtures")
        .join("test_plugin_lua")
}

/// Build a ManifestData for the `test.add@1` fixture contract. `path` is the
/// bundle directory used for Path loading; in-memory sources ignore it for
/// package.path provisioning but still carry it as a stable identifier.
fn fixture_manifest(path: &Path) -> ManifestData {
    let name: &str = "test_plugin_lua";
    ManifestData {
        id: polyplug_utils::bundle_id(name),
        name: name.to_owned(),
        loader: "lua".to_owned(),
        file: "test_plugin.lua".to_owned(),
        path: path.to_path_buf(),
        version: "1.0.0".to_owned(),
        // Leave `provides` empty so manifest validation skips the per-contract
        // function-count check; the loader registers test.add@1 from the
        // registrations the script's `polyplug_init` returns regardless. This
        // mirrors the other tests' manifests.
        provides: Vec::new(),
        function_count: HashMap::new(),
        dependencies: Vec::new(),
        needs_reinit_on_dep_reload: false,
        bundle_dependencies: Vec::new(),
    }
}

/// Dispatch `add(a, b) -> u32` (fn_id 0) on the `test.add@1` contract registered
/// in `runtime`, returning the u32 result.
fn dispatch_add(runtime: &Runtime, a: u32, b: u32) -> u32 {
    let contract_id: u64 = polyplug_utils::guest_contract_id("test.add", 1);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("test.add@1 must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("handle must resolve to a vtable");
    // SAFETY: vtable_ptr is a 'static leaked GuestContractInterface from LuaLoader;
    // the shared Lua VM and leaked interface outlive this call.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr };

    // The fixture's impl_add reads two u32 from args and writes one u32 to out.
    let args: [u32; 2] = [a, b];
    let mut out: u32 = 0;
    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is a valid function pointer; args points at two
    // contiguous u32 and out at one u32, matching what impl_add reads/writes.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            args.as_ptr() as *const (),
            &mut out as *mut u32 as *mut (),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(
        result.code,
        AbiErrorCode::Ok as u32,
        "add dispatch must return Ok, got code={}",
        result.code
    );
    out
}

/// Loading the fixture's Lua source through `BundleSource::Code` must register and
/// dispatch the `test.add@1` contract identically to Path loading.
///
/// The fixture only `require`s loader-provisioned SDK modules (`ffi`,
/// `polyplug_guest`, `polyplug_abi`) — never a bundle-dir-vendored sibling — so a
/// Code-sourced load (which has no bundle directory) can satisfy every require.
#[test]
fn code_source_loads_and_dispatches_like_path() {
    let fixture_dir: PathBuf = lua_fixture_dir();
    let entry: PathBuf = fixture_dir.join("test_plugin.lua");
    let source_text: String =
        std::fs::read_to_string(&entry).expect("fixture test_plugin.lua must be readable");

    // Path-loaded baseline in its own runtime.
    let path_runtime: Arc<Runtime> = make_runtime();
    path_runtime
        .load_bundle_from_source(
            fixture_manifest(&fixture_dir),
            polyplug::loader::BundleSource::Path(fixture_dir.clone()),
        )
        .expect("path-sourced fixture load must succeed");
    let path_result: u32 = dispatch_add(&path_runtime, 7, 35);

    // Code-loaded equivalent in a separate runtime: no bundle directory at all.
    let code_runtime: Arc<Runtime> = make_runtime();
    code_runtime
        .load_bundle_from_source(
            fixture_manifest(&fixture_dir),
            polyplug::loader::BundleSource::Code(source_text),
        )
        .expect("code-sourced fixture load must succeed");
    let code_result: u32 = dispatch_add(&code_runtime, 7, 35);

    assert_eq!(
        code_result, 42,
        "code-sourced add(7, 35) must compute 42, got {code_result}"
    );
    assert_eq!(
        code_result, path_result,
        "code-sourced dispatch must match path-sourced dispatch"
    );
}

/// `BundleSource::Bytes` carrying valid UTF-8 Lua source must load via the same
/// path as `Code` and dispatch identically.
#[test]
fn bytes_source_with_valid_utf8_loads_and_dispatches() {
    let fixture_dir: PathBuf = lua_fixture_dir();
    let entry: PathBuf = fixture_dir.join("test_plugin.lua");
    let source_bytes: Vec<u8> =
        std::fs::read(&entry).expect("fixture test_plugin.lua must be readable");

    let runtime: Arc<Runtime> = make_runtime();
    runtime
        .load_bundle_from_source(
            fixture_manifest(&fixture_dir),
            polyplug::loader::BundleSource::Bytes(source_bytes),
        )
        .expect("bytes-sourced fixture load must succeed");

    let result: u32 = dispatch_add(&runtime, 20, 22);
    assert_eq!(result, 42, "bytes-sourced add(20, 22) must compute 42");
}

/// `BundleSource::Bytes` carrying invalid UTF-8 must fail with the unified
/// `LoaderError::InvalidSourceEncoding` — never a panic and never a string-only
/// error.
#[test]
fn bytes_source_with_invalid_utf8_returns_structured_error() {
    let fixture_dir: PathBuf = lua_fixture_dir();
    // 0xFF is never a valid UTF-8 byte.
    let invalid: Vec<u8> = vec![0x66, 0x6e, 0xFF, 0xFE, 0x00];

    let runtime: Arc<Runtime> = make_runtime();
    let result: Result<(), RuntimeError> = runtime.load_bundle_from_source(
        fixture_manifest(&fixture_dir),
        polyplug::loader::BundleSource::Bytes(invalid),
    );
    assert!(result.is_err(), "invalid UTF-8 bytes must produce Err");
    let err: RuntimeError = result.expect_err("expected Err for invalid UTF-8 bytes");
    match err {
        RuntimeError::Loader(LoaderError::InvalidSourceEncoding {
            loader,
            source_kind,
            bundle,
        }) => {
            assert_eq!(loader, "lua", "loader must be the Lua runtime name");
            assert_eq!(source_kind, "bytes", "source_kind must be bytes");
            assert_eq!(
                bundle, "test_plugin_lua",
                "bundle must be the manifest bundle name"
            );
        }
        other => panic!("expected LoaderError::InvalidSourceEncoding, got: {other:?}"),
    }
}

/// With hot-reload enabled, reloading a loaded bundle must succeed and the
/// contract must remain resolvable through the registry afterwards.
#[test]
fn lua_reload_reinitializes_contracts() {
    let (dir, _path) = write_temp_bundle("lua_reload_reinit", valid_plugin_script());
    let runtime: Arc<Runtime> = make_runtime_with_hot_reload(true);

    let bundle_dir: PathBuf = dir.path().to_path_buf();
    runtime
        .load_bundle(&bundle_dir)
        .expect("initial bundle load must succeed");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    runtime
        .find_guest_contract(contract_id, 0)
        .expect("contract must resolve after initial load");

    runtime
        .reload_bundle(&bundle_dir)
        .expect("reload must succeed when hot-reload is enabled");

    runtime
        .find_guest_contract(contract_id, 0)
        .expect("contract must remain resolvable after reload");
}

// ── 16. Logger — dispatch failures route through the host logger ─────────────

/// A Lua plugin whose single function always raises a Lua error.
fn failing_plugin_script() -> &'static [u8] {
    br#"
local function impl_fail(_instance, _args_ptr, _out_ptr)
    error("boom from lua guest")
end
function polyplug_init(_registrar_ptr, _ctx_ptr)
    return {
        ["test.loader"] = {
            contract_version = 1,
            plugin_name      = "test-loader-fail",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_fail },
        },
    }, { code = 0 }
end
"#
}

/// A failed Lua guest dispatch must deliver an (Error, "loader.lua", ...) record
/// through the host logger installed via `RuntimeBuilder::logger`: the per-VM
/// `LuaLoaderData` carries an instance-owned copy of the runtime's handle, taken
/// at load time, and the dispatch error path logs AFTER the per-VM dispatch lock
/// has been released.
#[test]
fn dispatch_failure_is_logged_through_host_logger() {
    let (_dir, path) = write_temp_bundle("lua_loader_dispatch_log", failing_plugin_script());

    let records: Arc<std::sync::Mutex<Vec<(LogLevel, String, String)>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let records_clone: Arc<std::sync::Mutex<Vec<(LogLevel, String, String)>>> =
        Arc::clone(&records);
    let runtime: Arc<Runtime> = RuntimeBuilder::new()
        .logger(move |level: LogLevel, scope: &str, msg: &str| {
            records_clone.lock().expect("records lock").push((
                level,
                scope.to_owned(),
                msg.to_owned(),
            ));
        })
        .build()
        .expect("runtime build must succeed");

    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let manifest: ManifestData = make_manifest(&path, "lua_loader_dispatch_log");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("failing-function bundle must still load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("test.loader@1 must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("handle must resolve to vtable");
    // SAFETY: vtable_ptr is a 'static leaked GuestContractInterface from LuaLoader.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr };

    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is a valid function pointer, loader_data is valid,
    // and the failing function never reads its (args, out) pointers.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(
        result.code,
        AbiErrorCode::Generic as u32,
        "failing guest function must return Generic, got code={}",
        result.code
    );

    let captured: Vec<(LogLevel, String, String)> = records.lock().expect("records lock").clone();
    assert!(
        captured.iter().any(|(level, scope, msg)| {
            *level == LogLevel::Error
                && scope == "loader.lua"
                && msg.starts_with("Lua function call failed")
                && msg.contains("boom from lua guest")
        }),
        "expected an (Error, \"loader.lua\", \"Lua function call failed: ...boom...\") record, got: {captured:?}"
    );
}

// ── 17. Guest logging — direct `HostApi.log` through the threaded host pointer ─

/// A Lua plugin whose single function logs through the polyplug_guest SDK helper
/// `pg.log(host, ...)`, which calls `HostApi.log` directly via FFI (no
/// loader-injected `_polyplug_log` global — Rule 12). The host pointer is threaded
/// in through the author factory. The second call passes an out-of-range level so
/// the host funnel's clamp-to-Error is exercised.
fn logging_plugin_script() -> &'static [u8] {
    br#"
local pg = require("polyplug_guest")
local function new_logger(host)
    local self = {}
    function self:log_fn(_args_ptr, _out_ptr)
        pg.log(host, pg.LogLevel.Info, "guest.test-log", "hello from lua guest")
        pg.log(host, 99, "guest.test-log", "out of range level")
    end
    return self
end
function polyplug_init(_host_ptr, _ctx_ptr)
    return {
        ["test.loader"] = {
            contract_version = 1,
            plugin_name      = "test-loader-guest-log",
            factory          = new_logger,
            functions        = { [0] = function(instance, a, o) instance:log_fn(a, o) end },
        },
    }, { code = 0 }
end
"#
}

/// A guest calling `HostApi.log` (via the SDK `pg.log(host, ...)` helper)
/// mid-dispatch must deliver (level, scope, message) verbatim through the host
/// logger installed via `RuntimeBuilder::logger`, and an out-of-range level
/// must clamp to `LogLevel::Error`. The log call happens while `lua_dispatch`
/// holds the per-VM dispatch lock — this test also proves that path is
/// deadlock-free.
#[test]
fn guest_log_bridge_delivers_records_and_clamps_level() {
    let (_dir, path) = write_temp_bundle("lua_loader_guest_log", logging_plugin_script());

    let records: Arc<std::sync::Mutex<Vec<(LogLevel, String, String)>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));
    let records_clone: Arc<std::sync::Mutex<Vec<(LogLevel, String, String)>>> =
        Arc::clone(&records);
    let runtime: Arc<Runtime> = RuntimeBuilder::new()
        .logger(move |level: LogLevel, scope: &str, msg: &str| {
            records_clone.lock().expect("records lock").push((
                level,
                scope.to_owned(),
                msg.to_owned(),
            ));
        })
        .build()
        .expect("runtime build must succeed");

    let loader: LuaLoader = LuaLoader::new(LuaConfig::default());
    let manifest: ManifestData = make_manifest(&path, "lua_loader_guest_log");
    loader
        .load(
            &manifest,
            &polyplug::loader::BundleSource::Path(manifest.path.clone()),
            &runtime,
        )
        .expect("logging bundle must load");

    let contract_id: u64 = polyplug_utils::guest_contract_id("test.loader", 1);
    let handle: GuestContractHandle = runtime
        .registry()
        .find(GuestContractId::from_u64(contract_id), 0)
        .expect("test.loader@1 must be registered");
    let vtable_ptr: *const GuestContractInterface = runtime
        .registry()
        .resolve_guest_contract(handle)
        .expect("handle must resolve to vtable");
    // SAFETY: vtable_ptr is a valid GuestContractInterface owned by the registry.
    let vtable: &GuestContractInterface = unsafe { &*vtable_ptr };

    let mut result: AbiError = AbiError::ok();
    // SAFETY: dispatch.vm.call is a valid function pointer, loader_data is valid,
    // and the logging function never reads its (args, out) pointers.
    unsafe {
        (vtable.dispatch.vm.call)(
            vtable.dispatch.vm.loader_data,
            GuestContractInstance::null(),
            0,
            core::ptr::null::<()>(),
            core::ptr::null_mut::<()>(),
            core::ptr::null_mut(),
            &mut result as *mut AbiError,
        );
    }
    assert_eq!(
        result.code,
        AbiErrorCode::Ok as u32,
        "logging guest function must dispatch Ok, got code={}",
        result.code
    );

    let captured: Vec<(LogLevel, String, String)> = records.lock().expect("records lock").clone();
    assert!(
        captured.contains(&(
            LogLevel::Info,
            String::from("guest.test-log"),
            String::from("hello from lua guest"),
        )),
        "expected verbatim (Info, \"guest.test-log\", \"hello from lua guest\") record, got: {captured:?}"
    );
    assert!(
        captured.contains(&(
            LogLevel::Error,
            String::from("guest.test-log"),
            String::from("out of range level"),
        )),
        "expected out-of-range level 99 to clamp to Error, got: {captured:?}"
    );
}

// ── polyplug_init returned AbiError code ──────────────────────────────────────

/// A plugin whose `polyplug_init` registers handlers but returns a non-zero
/// AbiErrorCode must FAIL to load with that code in the error message.
/// Before the fix the loader discarded the return value and treated the
/// bundle as loaded.
#[test]
fn load_init_returning_error_code_fails_load() {
    let (_dir, path) = write_temp_bundle(
        "lua_loader_init_err_code",
        br#"
local function impl_noop(_instance, _args_ptr, _out_ptr) end
function polyplug_init(_reg, _ctx)
    return {
        ["test.initerr"] = {
            contract_version = 1,
            plugin_name      = "test-init-err",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_noop },
        },
    }, { code = 1 }  -- AbiErrorCode.Generic
end
"#,
    );
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_init_err_code");
    assert!(result.is_err(), "non-zero init code must fail the load");
    let err: LoaderError = result.expect_err("expected Err for non-zero init code");
    match &err {
        LoaderError::InitFailed { error, .. } => {
            assert!(
                error.contains("returned error code 1"),
                "error must carry the returned code, got: {error}"
            );
        }
        other => panic!("expected InitFailed, got: {other:?}"),
    }
}

/// A plugin whose `polyplug_init` explicitly returns AbiErrorCode.Ok (0)
/// must load successfully — the return-value check must not reject success.
#[test]
fn load_init_returning_ok_code_succeeds() {
    let (_dir, path) = write_temp_bundle(
        "lua_loader_init_ok_code",
        br#"
local function impl_noop(_instance, _args_ptr, _out_ptr) end
function polyplug_init(_reg, _ctx)
    return {
        ["test.initok"] = {
            contract_version = 1,
            plugin_name      = "test-init-ok",
            factory          = function(_host) return {} end,
            functions        = { [0] = impl_noop },
        },
    }, { code = 0 }  -- AbiErrorCode.Ok
end
"#,
    );
    let result: Result<(), LoaderError> = load_script(&path, "lua_loader_init_ok_code");
    assert!(result.is_ok(), "explicit Ok return must load: {result:?}");
}