polyplug 0.1.1

Universal high-performance zero-overhead cross-language plugin runtime
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
#![allow(clippy::expect_used)]

//! Regression tests for review findings reachable through the public
//! `RuntimeStore` surface and the `find_all_guest_contracts` HostApi callback.
//!
//! Findings that exercise the `pub(crate)` reload primitives (`begin_reload`,
//! `apply_reload_swap`, `abort_reload`) live as unit tests inside
//! `runtime_store.rs` because those methods are crate-private; see the tests
//! `pending_reload_slot_not_returned_by_find_by_bundle` and
//! `apply_reload_swap_bumps_consumed_new_slot_generation` there.
//!
//! Covered here (public surface):
//! 1. find_all alloc/free layout: the returned `Array.len` must equal the live
//!    provider count under a single registry guard (no shrink-between-locks UB),
//!    and `host->free` with `len * sizeof(T)` must round-trip.
//! 3. `DuplicateProvider` enforced for same-bundle/same-contract; different
//!    bundles registering the same contract stays allowed.
//! 4. `min_version` is a MAJOR-version floor (doc-rot pin).
//! 5. `get_guest_contract_descriptor` honours `handle.generation`.

use std::sync::Arc;

use polyplug::Runtime;
use polyplug::error::RegistryError;
use polyplug::runtime_store::RuntimeStore;
use polyplug_abi::runtime::RuntimeConfig;
use polyplug_abi::{
    Array, DispatchMechanisms, DispatchType, GuestContractHandle, GuestContractInterface, HostApi,
    NativeDispatch, PluginDescriptor, StringView, Version,
};
use polyplug_utils::BundleId;
use polyplug_utils::GuestContractId;

const MOCK_FUNCTIONS: [*const (); 0] = [];

/// No-op create_instance callback.
unsafe extern "C" fn noop_create_instance(
    _loader_data: polyplug_abi::dispatch::VmLoaderData,
    _host: *const HostApi,
    _args: *const (),
    out_instance: *mut polyplug_abi::GuestContractInstance,
) {
    if !out_instance.is_null() {
        // SAFETY: out_instance is non-null (just checked) and writable per the ABI contract.
        unsafe { out_instance.write(polyplug_abi::GuestContractInstance::null()) };
    }
}

/// No-op destroy_instance callback.
unsafe extern "C" fn noop_destroy_instance(
    _loader_data: polyplug_abi::dispatch::VmLoaderData,
    _host: *const HostApi,
    _instance: polyplug_abi::GuestContractInstance,
) {
}

fn make_interface(contract_id: u64, major: u32) -> GuestContractInterface {
    GuestContractInterface {
        contract_id: GuestContractId::from_u64(contract_id),
        contract_version: Version {
            major,
            minor: 0,
            patch: 0,
        },
        dispatch_type: DispatchType::Native,
        create_instance: noop_create_instance,
        destroy_instance: noop_destroy_instance,
        dispatch: DispatchMechanisms {
            native: NativeDispatch {
                function_count: 0,
                functions: MOCK_FUNCTIONS.as_ptr(),
            },
        },
    }
}

fn make_descriptor(name: &'static str, contract_name: &'static str) -> PluginDescriptor {
    PluginDescriptor {
        name: StringView::from_static(name.as_bytes()),
        contract_name: StringView::from_static(contract_name.as_bytes()),
        version: Version {
            major: 1,
            minor: 0,
            patch: 0,
        },
    }
}

// =============================================================================
// Finding 1 — collect_guest_contracts counts AND collects under ONE guard.
// =============================================================================

/// Finding 1 (unit): collect_guest_contracts filters by min_version, skips
/// vacancies left by an unload, and returns exactly the live providers.
#[test]
fn collect_guest_contracts_filters_versions_and_vacancies() {
    const CID: u64 = 0x1234_0000_0000_0001_u64;
    let registry: RuntimeStore = RuntimeStore::new();
    let contract_id: GuestContractId = GuestContractId::from_u64(CID);

    let iface_v1: GuestContractInterface = make_interface(CID, 1);
    let iface_v2: GuestContractInterface = make_interface(CID, 2);
    let iface_v3: GuestContractInterface = make_interface(CID, 3);

    let bundle_a: BundleId = BundleId::from_u64(0xA1);
    let bundle_b: BundleId = BundleId::from_u64(0xB2);
    let bundle_c: BundleId = BundleId::from_u64(0xC3);

    // SAFETY: interfaces are local values valid for this test's lifetime.
    unsafe {
        registry
            .register_guest_contract(
                make_descriptor("a", "multi.contract"),
                &iface_v1,
                "multi.contract".to_owned(),
                bundle_a,
            )
            .expect("register a");
        registry
            .register_guest_contract(
                make_descriptor("b", "multi.contract"),
                &iface_v2,
                "multi.contract".to_owned(),
                bundle_b,
            )
            .expect("register b");
        registry
            .register_guest_contract(
                make_descriptor("c", "multi.contract"),
                &iface_v3,
                "multi.contract".to_owned(),
                bundle_c,
            )
            .expect("register c");
    }

    // All three providers at min_version=0.
    let all: Vec<GuestContractHandle> = registry.collect_guest_contracts(contract_id, 0);
    assert_eq!(all.len(), 3, "three providers at min_version=0");

    // min_version filters by MAJOR: only v2 and v3 satisfy >= 2.
    let ge2: Vec<GuestContractHandle> = registry.collect_guest_contracts(contract_id, 2);
    assert_eq!(ge2.len(), 2, "two providers at min_version=2");

    // Unload bundle_b — its slot becomes a vacancy; collect must skip it.
    registry
        .invalidate_bundle(bundle_b)
        .expect("invalidate bundle_b");
    let after_unload: Vec<GuestContractHandle> = registry.collect_guest_contracts(contract_id, 0);
    assert_eq!(
        after_unload.len(),
        2,
        "two live providers after one unload (vacancy skipped)"
    );

    // No matches → empty vec (no allocation contract for callers).
    let none: Vec<GuestContractHandle> =
        registry.collect_guest_contracts(GuestContractId::from_u64(0xDEAD), 0);
    assert!(none.is_empty(), "unknown contract collects nothing");
}

/// Finding 1 (regression, end-to-end): register N providers, unload one bundle,
/// then call the HostApi `find_all_guest_contracts` callback. The returned
/// `Array.len` must equal the number of LIVE providers (not a stale pre-count),
/// and freeing `len * sizeof(T)` via `host->free` must round-trip cleanly.
#[test]
fn host_find_all_array_len_matches_live_providers_and_frees() {
    const CID: u64 = 0x9999_0000_0000_0001_u64;

    // SAFETY: null config is accepted (default runtime config).
    let host: *const HostApi =
        unsafe { polyplug::ffi::polyplug_runtime_create(core::ptr::null::<RuntimeConfig>()) };
    assert!(!host.is_null(), "runtime create must yield a host");

    // SAFETY: host is non-null and its runtime field points to a live Runtime.
    let runtime: &Runtime = unsafe { &*((*host).runtime as *const Runtime) };
    let registry: &Arc<RuntimeStore> = runtime.registry();

    let iface_a: GuestContractInterface = make_interface(CID, 1);
    let iface_b: GuestContractInterface = make_interface(CID, 1);
    let iface_c: GuestContractInterface = make_interface(CID, 1);

    let bundle_a: BundleId = BundleId::from_u64(0x501);
    let bundle_b: BundleId = BundleId::from_u64(0x502);
    let bundle_c: BundleId = BundleId::from_u64(0x503);

    // SAFETY: interfaces are local values valid for this test's lifetime.
    unsafe {
        registry
            .register_guest_contract(
                make_descriptor("a", "find.all"),
                &iface_a,
                "find.all".to_owned(),
                bundle_a,
            )
            .expect("register a");
        registry
            .register_guest_contract(
                make_descriptor("b", "find.all"),
                &iface_b,
                "find.all".to_owned(),
                bundle_b,
            )
            .expect("register b");
        registry
            .register_guest_contract(
                make_descriptor("c", "find.all"),
                &iface_c,
                "find.all".to_owned(),
                bundle_c,
            )
            .expect("register c");
    }

    // Unload one bundle so the live count is 2.
    registry
        .invalidate_bundle(bundle_b)
        .expect("invalidate bundle_b");

    // Invoke the HostApi callback exactly as a guest/host would.
    // SAFETY: host is a valid HostApi pointer from polyplug_runtime_create.
    let array: Array<GuestContractHandle> =
        unsafe { ((*host).find_all_guest_contracts)(host, CID, 0) };

    assert_eq!(
        array.len, 2,
        "Array.len must equal the live provider count (2), not a stale pre-count"
    );
    assert!(
        !array.items.is_null(),
        "non-empty array must carry a buffer"
    );

    // Free using the Array contract: len * sizeof(T) with align — must round-trip.
    let size: usize = array.len * core::mem::size_of::<GuestContractHandle>();
    // SAFETY: items was allocated by host->alloc with size == len * sizeof(T) and
    // matching alignment; freeing with the same size/align is the documented contract.
    unsafe {
        ((*host).free)(host, array.items as *mut u8, size, array.align);
    }

    // SAFETY: host was produced by polyplug_runtime_create and is destroyed once.
    unsafe { polyplug::ffi::polyplug_runtime_destroy(host) };
}

// =============================================================================
// Finding 3 — DuplicateProvider enforced (same bundle); multi-impl still OK.
// =============================================================================

/// Finding 3: same bundle registering the same contract twice → DuplicateProvider.
#[test]
fn same_bundle_same_contract_twice_is_duplicate_provider() {
    const CID: u64 = 0x4444_0000_0000_0001_u64;
    let registry: RuntimeStore = RuntimeStore::new();
    let bundle_id: BundleId = BundleId::from_u64(0x1010);

    let iface: GuestContractInterface = make_interface(CID, 1);
    // SAFETY: local value valid for this test's lifetime.
    unsafe {
        registry
            .register_guest_contract(
                make_descriptor("first", "dup.contract"),
                &iface,
                "dup.contract".to_owned(),
                bundle_id,
            )
            .expect("first register succeeds");
    }

    // SAFETY: local value valid for this test's lifetime.
    let result: Result<GuestContractHandle, RegistryError> = unsafe {
        registry.register_guest_contract(
            make_descriptor("second", "dup.contract"),
            &iface,
            "dup.contract".to_owned(),
            bundle_id,
        )
    };
    assert!(
        matches!(result, Err(RegistryError::DuplicateProvider { .. })),
        "same bundle + same contract must be DuplicateProvider, got {result:?}"
    );
}

/// Finding 3: different bundles registering the same contract → allowed (multi-impl).
#[test]
fn different_bundles_same_contract_allowed() {
    const CID: u64 = 0x4444_0000_0000_0002_u64;
    let registry: RuntimeStore = RuntimeStore::new();

    let iface_a: GuestContractInterface = make_interface(CID, 1);
    let iface_b: GuestContractInterface = make_interface(CID, 1);

    // SAFETY: local values valid for this test's lifetime.
    unsafe {
        registry
            .register_guest_contract(
                make_descriptor("a", "multi.ok"),
                &iface_a,
                "multi.ok".to_owned(),
                BundleId::from_u64(0x2020),
            )
            .expect("bundle a register");
        registry
            .register_guest_contract(
                make_descriptor("b", "multi.ok"),
                &iface_b,
                "multi.ok".to_owned(),
                BundleId::from_u64(0x3030),
            )
            .expect("bundle b register (different bundle, same contract is allowed)");
    }
}

// =============================================================================
// Finding 4 — min_version is a MAJOR-version floor (doc-rot pin).
// =============================================================================

/// Finding 4: `find`/`find_all` compare against the interface's MAJOR version.
/// A provider with major=2 satisfies min_version 0,1,2 but not 3.
#[test]
fn min_version_is_major_floor() {
    const CID: u64 = 0x5555_0000_0000_0001_u64;
    let registry: RuntimeStore = RuntimeStore::new();
    let contract_id: GuestContractId = GuestContractId::from_u64(CID);

    let iface: GuestContractInterface = make_interface(CID, 2);
    // SAFETY: local value valid for this test's lifetime.
    unsafe {
        registry
            .register_guest_contract(
                make_descriptor("p", "major.floor"),
                &iface,
                "major.floor".to_owned(),
                BundleId::from_u64(0x5050),
            )
            .expect("register");
    }

    assert!(
        registry.find(contract_id, 0).is_ok(),
        "major=2 satisfies min_version=0"
    );
    assert!(
        registry.find(contract_id, 2).is_ok(),
        "major=2 satisfies min_version=2 (floor is inclusive)"
    );
    assert!(
        registry.find(contract_id, 3).is_err(),
        "major=2 does NOT satisfy min_version=3"
    );
    assert_eq!(
        registry.collect_guest_contracts(contract_id, 3).len(),
        0,
        "collect honours the same MAJOR floor"
    );
}

// =============================================================================
// Finding 5 — get_guest_contract_descriptor honours handle.generation.
// =============================================================================

/// Finding 5: a stale handle (whose slot was retired and reused) must NOT return
/// the new occupant's descriptor.
#[test]
fn descriptor_honours_handle_generation() {
    const CID: u64 = 0x6666_0000_0000_0001_u64;
    let registry: RuntimeStore = RuntimeStore::new();
    let bundle_a: BundleId = BundleId::from_u64(0x6060);

    let iface_a: GuestContractInterface = make_interface(CID, 1);
    // SAFETY: local value valid for this test's lifetime.
    let stale_handle: GuestContractHandle = unsafe {
        registry
            .register_guest_contract(
                make_descriptor("original", "gen.contract"),
                &iface_a,
                "gen.contract".to_owned(),
                bundle_a,
            )
            .expect("register original")
    };

    // Unload bundle_a — the slot is retired (generation bumped, entry cleared).
    registry
        .invalidate_bundle(bundle_a)
        .expect("invalidate bundle_a");

    // Reuse the recycled slot with a NEW occupant.
    let bundle_b: BundleId = BundleId::from_u64(0x6061);
    let iface_b: GuestContractInterface = make_interface(0x6666_0000_0000_0002_u64, 1);
    // SAFETY: local value valid for this test's lifetime.
    let new_handle: GuestContractHandle = unsafe {
        registry
            .register_guest_contract(
                make_descriptor("replacement", "gen.contract.new"),
                &iface_b,
                "gen.contract.new".to_owned(),
                bundle_b,
            )
            .expect("register replacement")
    };
    assert_eq!(
        new_handle.index, stale_handle.index,
        "the recycled slot index must be reused"
    );

    // The stale handle must NOT resolve to the new occupant's descriptor.
    let descriptor = registry.get_guest_contract_descriptor(stale_handle);
    assert!(
        descriptor.is_none(),
        "stale handle must not return the new occupant's descriptor, got {descriptor:?}"
    );

    // The current handle still works.
    let current = registry.get_guest_contract_descriptor(new_handle);
    assert!(
        current.is_some(),
        "the current handle must return its descriptor"
    );
}