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
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
#![allow(clippy::expect_used)]

// THIS IS A BENCHMARK FILE — do not add #[test] functions here
// Run with: cargo bench -p polyplug --bench ffi_resolve
//
// Benchmark: HostApi.resolve_guest_contract path
// Measures: Time from FFI call to interface pointer return (direct, no allocation)

use core::cell::RefCell;
use core::hint::black_box;

use criterion::BenchmarkId;
use criterion::Criterion;
use criterion::Throughput;
use criterion::criterion_group;
use criterion::criterion_main;

use polyplug::runtime_store::RuntimeStore;
use polyplug_abi::AbiError;
use polyplug_abi::AbiErrorCode;
use polyplug_abi::Array;
use polyplug_abi::DispatchMechanisms;
use polyplug_abi::DispatchType;
use polyplug_abi::GuestContractHandle;
use polyplug_abi::GuestContractInstance;
use polyplug_abi::GuestContractInterface;
use polyplug_abi::HostApi;
use polyplug_abi::NativeDispatch;
use polyplug_abi::PluginDescriptor;
use polyplug_abi::StringView;
use polyplug_abi::ffi::polyplug_host_alloc;
use polyplug_abi::ffi::polyplug_host_free;
use polyplug_abi::types::Version;
use polyplug_utils::BundleId;
use polyplug_utils::GuestContractId;

// ─── Plugin paths from build.rs ──────────────────────────────────────────────

const TEST_PLUGIN_SO: &str = env!("TEST_PLUGIN_SO");

// ─── Thread-local registry and captured interface state ────────────────────────

thread_local! {
    static BENCH_REGISTRY: RefCell<Option<RuntimeStore>> = RefCell::new(Some(RuntimeStore::new()));
    static LAST_CONTRACT_ID: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
}

/// Registration callback — registers the guest contract into BENCH_REGISTRY.
///
/// # Safety
/// `descriptor` and `interface` must be valid pointers for the call duration.
/// `out_err` must be non-null and writable.
unsafe extern "C" fn bench_register_callback(
    _this: *const HostApi,
    descriptor: *const PluginDescriptor,
    interface: *const GuestContractInterface,
    out_err: *mut AbiError,
) {
    if descriptor.is_null() || interface.is_null() {
        if !out_err.is_null() {
            // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
            unsafe {
                out_err.write(AbiError {
                    code: AbiErrorCode::Generic as u32,
                    message: StringView::null(),
                })
            };
        }
        return;
    }

    // SAFETY: descriptor is valid for this call per ABI contract.
    let desc: &PluginDescriptor = unsafe { &*descriptor };
    // SAFETY: interface is valid for this call per ABI contract.
    let iface: &GuestContractInterface = unsafe { &*interface };

    // SAFETY: desc.contract_name is set from a &'static str in the benchmark fixture.
    // The bytes are valid UTF-8 by construction.
    let contract_name: &str = unsafe {
        let bytes: &[u8] =
            core::slice::from_raw_parts(desc.contract_name.ptr, desc.contract_name.len);
        core::str::from_utf8_unchecked(bytes) // SAFETY: see comment above
    };

    let result: Result<GuestContractHandle, _> =
        BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
            let borrowed = cell.borrow();
            let registry = borrowed.as_ref().expect("registry not initialized");
            // SAFETY: interface pointer is 'static — extracted from a loaded library that outlives registry.
            unsafe {
                registry.register_guest_contract(
                    *desc,
                    interface,
                    contract_name.to_owned(),
                    BundleId::from_u64(iface.contract_id.id()),
                )
            }
        });

    let err: AbiError = match result {
        Ok(_) => {
            LAST_CONTRACT_ID.with(|cell| cell.set(iface.contract_id.id()));
            AbiError::ok()
        }
        Err(_) => AbiError {
            code: AbiErrorCode::Generic as u32,
            message: StringView::null(),
        },
    };
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe { out_err.write(err) };
    }
}

// ─── Stub HostApi functions ─────────────────────────────────────────────

/// Finds a guest contract by contract_id in the thread-local BENCH_REGISTRY.
///
/// # Safety
/// Must only be called from a bench thread where BENCH_REGISTRY is initialised.
unsafe extern "C" fn bench_find_guest_contract(
    _this: *const HostApi,
    contract_id: u64,
    min_version: u32,
) -> GuestContractHandle {
    BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
        let registry = cell.borrow();
        let reg = registry.as_ref().expect("registry not initialized");
        reg.find(GuestContractId::from_u64(contract_id), min_version)
            .unwrap_or_else(|_| GuestContractHandle::null())
    })
}

/// find_all stub — returns empty array (not used in this bench).
///
/// # Safety
/// Always safe to call; returns empty array.
unsafe extern "C" fn bench_find_all_guest_contracts(
    _this: *const HostApi,
    _contract_id: u64,
    _min_version: u32,
) -> Array<GuestContractHandle> {
    Array::empty()
}

/// Resolves a guest contract handle to an interface pointer via BENCH_REGISTRY.
///
/// # Safety
/// The returned pointer is valid and 'static — the library is kept alive via mem::forget.
unsafe extern "C" fn bench_resolve_guest_contract(
    _this: *const HostApi,
    handle: GuestContractHandle,
) -> *const GuestContractInterface {
    BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
        cell.borrow()
            .as_ref()
            .expect("registry not initialized")
            .resolve_guest_contract(handle)
            .unwrap_or(core::ptr::null())
    })
}

unsafe extern "C" fn bench_get_host_contract(
    _this: *const HostApi,
    _contract_id: u64,
    _min_version: u32,
) -> polyplug_abi::HostContractInstance {
    polyplug_abi::HostContractInstance::null()
}

unsafe extern "C" fn bench_resolve_host_contract_interface(
    _this: *const HostApi,
    _contract_id: u64,
    _min_version: u32,
) -> *const polyplug_abi::HostContractInterface {
    core::ptr::null()
}

unsafe extern "C" fn bench_list_bundles(_this: *const HostApi) -> Array<BundleId> {
    Array::empty()
}

unsafe extern "C" fn bench_get_dependencies(
    _this: *const HostApi,
) -> Array<polyplug_abi::DependencyInfo> {
    Array::empty()
}

/// Alloc wrapper that ignores this (uses global allocator).
///
/// # Safety
/// Delegates to polyplug_host_alloc which is safe for any size/align.
unsafe extern "C" fn bench_alloc(_this: *const HostApi, size: usize, align: usize) -> *mut u8 {
    polyplug_host_alloc(size, align)
}

/// Free wrapper that ignores this (uses global allocator).
///
/// # Safety
/// Delegates to polyplug_host_free which requires ptr was allocated by polyplug_host_alloc.
unsafe extern "C" fn bench_free(_this: *const HostApi, ptr: *mut u8, size: usize, align: usize) {
    // SAFETY: ptr was allocated by polyplug_host_alloc (caller's responsibility).
    unsafe { polyplug_host_free(ptr, size, align) };
}

unsafe extern "C" fn bench_load_bundle(
    _this: *const HostApi,
    _path: *const u8,
    _path_len: usize,
    out_err: *mut AbiError,
) {
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe {
            out_err.write(AbiError {
                code: AbiErrorCode::Generic as u32,
                message: StringView::null(),
            })
        };
    }
}

unsafe extern "C" fn bench_reload_bundle(
    _this: *const HostApi,
    _path: *const u8,
    _path_len: usize,
    out_err: *mut AbiError,
) {
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe {
            out_err.write(AbiError {
                code: AbiErrorCode::Generic as u32,
                message: StringView::null(),
            })
        };
    }
}

unsafe extern "C" fn bench_register_host_contract(
    _this: *const HostApi,
    _interface: *const polyplug_abi::HostContractInterface,
    out_err: *mut AbiError,
) {
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe {
            out_err.write(AbiError {
                code: AbiErrorCode::Generic as u32,
                message: StringView::null(),
            })
        };
    }
}

unsafe extern "C" fn bench_register_loader(
    _this: *const HostApi,
    _loader_ptr: *mut core::ffi::c_void,
    out_err: *mut AbiError,
) {
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe {
            out_err.write(AbiError {
                code: AbiErrorCode::Generic as u32,
                message: StringView::null(),
            })
        };
    }
}

unsafe extern "C" fn bench_get_last_error(
    _this: *const HostApi,
    _buf: *mut u8,
    _buf_len: usize,
) -> usize {
    0
}

unsafe extern "C" fn bench_get_error_len(_this: *const HostApi) -> usize {
    0
}

unsafe extern "C" fn bench_unload_bundle(
    _this: *const HostApi,
    _bundle_id: BundleId,
    out_err: *mut AbiError,
) {
    if !out_err.is_null() {
        // SAFETY: out_err is non-null (just checked) and writable per the ABI contract.
        unsafe { out_err.write(AbiError::ok()) };
    }
}

// ─── Setup helper ────────────────────────────────────────────────────────────

/// Build a HostApi backed by the thread-local BENCH_REGISTRY.
fn build_host_interface() -> HostApi {
    HostApi {
        runtime: core::ptr::null_mut(),
        register_guest_contract: bench_register_callback,
        alloc: bench_alloc,
        free: bench_free,
        find_guest_contract: bench_find_guest_contract,
        find_all_guest_contracts: bench_find_all_guest_contracts,
        resolve_guest_contract: bench_resolve_guest_contract,
        get_host_contract: bench_get_host_contract,
        resolve_host_contract_interface: bench_resolve_host_contract_interface,
        list_bundles: bench_list_bundles,
        get_dependencies: bench_get_dependencies,
        load_bundle: bench_load_bundle,
        reload_bundle: bench_reload_bundle,
        register_host_contract: bench_register_host_contract,
        register_loader: bench_register_loader,
        get_last_error: bench_get_last_error,
        get_error_len: bench_get_error_len,
        unload_bundle: bench_unload_bundle,
        log: stub_host_log,
        create_guest_instance: stub_create_guest_instance,
        destroy_guest_instance: stub_destroy_guest_instance,
        revision_counter: stub_revision_counter,
        reserved: core::ptr::null(),
    }
}

/// Load the test plugin cdylib, call `polyplug_init`, and register into BENCH_REGISTRY.
/// Returns the loaded library (kept alive via never-drop invariant) and the
/// registered contract_id.
fn load_and_init_plugin(host_interface: &HostApi) -> (libloading::Library, u64) {
    // SAFETY: path is a valid compiled cdylib built by build.rs.
    let library: libloading::Library =
        unsafe { libloading::Library::new(TEST_PLUGIN_SO).expect("failed to load plugin") };

    // SAFETY: polyplug_init matches the expected 2-arg ABI.
    let init_fn: libloading::Symbol<
        '_,
        unsafe extern "C" fn(*const HostApi, *const polyplug_abi::BundleInitContext) -> AbiError,
    > = unsafe {
        library
            .get(b"polyplug_init\0")
            .expect("polyplug_init not found")
    };

    let plugin_ctx: polyplug_abi::BundleInitContext = polyplug_abi::BundleInitContext {
        bundle_path: StringView::null(),
        bundle_id: 0,
    };

    // SAFETY: init_fn is a valid function; host_interface and plugin_ctx live for the call duration.
    let result: AbiError = unsafe {
        init_fn(
            host_interface as *const HostApi,
            &plugin_ctx as *const polyplug_abi::BundleInitContext,
        )
    };
    assert!(
        result.is_ok(),
        "polyplug_init failed for {}",
        TEST_PLUGIN_SO
    );

    let contract_id: u64 = LAST_CONTRACT_ID.with(|cell| cell.get());
    assert_ne!(contract_id, 0, "plugin contract_id was not captured");

    (library, contract_id)
}

// ─── Benchmark: resolve_guest_contract (direct interface, no allocation) ───────

fn bench_ffi_resolve_plugin(c: &mut Criterion) {
    BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
        *cell.borrow_mut() = Some(RuntimeStore::new());
    });

    let host_interface: HostApi = build_host_interface();
    let (library, contract_id): (libloading::Library, u64) = load_and_init_plugin(&host_interface);

    // SAFETY: bench_find_guest_contract is a valid extern C fn backed by BENCH_REGISTRY.
    let handle: GuestContractHandle = unsafe {
        (host_interface.find_guest_contract)(&host_interface as *const HostApi, contract_id, 0)
    };

    let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
        c.benchmark_group("ffi");
    group.throughput(Throughput::Elements(1));

    group.bench_function(
        BenchmarkId::new("resolve_plugin", "direct_interface"),
        |b| {
            b.iter(|| {
                // SAFETY: bench_resolve_guest_contract returns a 'static interface pointer.
                let interface_ptr: *const GuestContractInterface = unsafe {
                    (host_interface.resolve_guest_contract)(
                        black_box(&host_interface as *const HostApi),
                        black_box(handle),
                    )
                };
                black_box(interface_ptr);
            });
        },
    );

    group.finish();
    // Keep library alive for the process lifetime (never-drop invariant).
    core::mem::forget(library);
}

// ─── Benchmark: resolve_guest_contract with null handle (early return path) ────

fn bench_ffi_resolve_null_handle(c: &mut Criterion) {
    BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
        *cell.borrow_mut() = Some(RuntimeStore::new());
    });

    let host_interface: HostApi = build_host_interface();
    let (library, _contract_id): (libloading::Library, u64) = load_and_init_plugin(&host_interface);

    let null_handle: GuestContractHandle = GuestContractHandle::null();

    let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
        c.benchmark_group("ffi");
    group.throughput(Throughput::Elements(1));

    group.bench_function(BenchmarkId::new("resolve_plugin", "null_handle"), |b| {
        b.iter(|| {
            // SAFETY: bench_resolve_guest_contract handles the null sentinel handle.
            let interface_ptr: *const GuestContractInterface = unsafe {
                (host_interface.resolve_guest_contract)(
                    black_box(&host_interface as *const HostApi),
                    black_box(null_handle),
                )
            };
            black_box(interface_ptr);
        });
    });

    group.finish();
    core::mem::forget(library);
}

// ─── Synthetic-interface helpers for the registry scale sweep ─────────────────

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

/// Stub destroy_instance for the synthetic sweep interfaces.
unsafe extern "C" fn sweep_destroy_instance(
    _loader_data: polyplug_abi::dispatch::VmLoaderData,
    _host: *const HostApi,
    _instance: GuestContractInstance,
) {
}

/// Build a leaked `'static` native interface for `contract_id` (no functions —
/// the sweep only resolves the interface pointer, it never dispatches).
fn leak_sweep_interface(contract_id: u64) -> &'static GuestContractInterface {
    Box::leak(Box::new(GuestContractInterface {
        contract_id: GuestContractId::from_u64(contract_id),
        contract_version: Version {
            major: 1,
            minor: 0,
            patch: 0,
        },
        dispatch_type: DispatchType::Native,
        create_instance: sweep_create_instance,
        destroy_instance: sweep_destroy_instance,
        dispatch: DispatchMechanisms {
            native: NativeDispatch {
                function_count: 0,
                functions: core::ptr::null(),
            },
        },
    }))
}

// ─── Benchmark: resolve scaling across registry sizes (10 / 100 / 1000) ───────

/// Registers `size` distinct contracts into BENCH_REGISTRY, then times the FFI
/// `resolve_guest_contract` of a middle handle. `resolve` is a generation-checked
/// slot index, so the cost should be flat across registry sizes — this sweep is
/// the evidence that resolve does NOT scale with the number of registered
/// contracts (unlike a linear scan would).
fn bench_ffi_resolve_registry_sweep(c: &mut Criterion) {
    let host_interface: HostApi = build_host_interface();
    let sizes: [u64; 3] = [10, 100, 1000];

    let mut group: criterion::BenchmarkGroup<'_, criterion::measurement::WallTime> =
        c.benchmark_group("ffi");
    group.throughput(Throughput::Elements(1));

    for &size in &sizes {
        // Fresh registry holding exactly `size` distinct contracts.
        BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
            *cell.borrow_mut() = Some(RuntimeStore::new());
        });

        let base_id: u64 = 0x5000_0000_0000_0000_u64;
        for i in 0..size {
            let interface: &'static GuestContractInterface = leak_sweep_interface(base_id + i);
            let descriptor: PluginDescriptor = PluginDescriptor {
                name: StringView::from_static(b"sweep_plugin"),
                contract_name: StringView::from_static(b"sweep.contract"),
                version: Version {
                    major: 1,
                    minor: 0,
                    patch: 0,
                },
            };
            BENCH_REGISTRY.with(|cell: &core::cell::RefCell<Option<RuntimeStore>>| {
                let borrowed = cell.borrow();
                let registry: &RuntimeStore = borrowed.as_ref().expect("registry not initialized");
                // SAFETY: interface is leaked ('static), valid for the registry lifetime.
                unsafe {
                    registry
                        .register_guest_contract(
                            descriptor,
                            interface,
                            format!("sweep.contract.{}", i),
                            BundleId::from_u64(i),
                        )
                        .expect("registration should succeed");
                }
            });
        }

        // Resolve a middle contract's handle once (find is not timed here).
        let middle_id: u64 = base_id + size / 2;
        // SAFETY: bench_find_guest_contract is backed by BENCH_REGISTRY.
        let handle: GuestContractHandle = unsafe {
            (host_interface.find_guest_contract)(&host_interface as *const HostApi, middle_id, 0)
        };

        group.bench_with_input(
            BenchmarkId::new("resolve_plugin", format!("registry_{}", size)),
            &handle,
            |b, &handle| {
                b.iter(|| {
                    // SAFETY: bench_resolve_guest_contract returns a 'static pointer.
                    let interface_ptr: *const GuestContractInterface = unsafe {
                        (host_interface.resolve_guest_contract)(
                            black_box(&host_interface as *const HostApi),
                            black_box(handle),
                        )
                    };
                    black_box(interface_ptr);
                });
            },
        );
    }

    group.finish();
}

// ─── criterion_group / criterion_main ────────────────────────────────────────

criterion_group!(
    benches,
    bench_ffi_resolve_plugin,
    bench_ffi_resolve_null_handle,
    bench_ffi_resolve_registry_sweep,
);
criterion_main!(benches);

/// `HostApi.log` stub for test hosts — drops the record.
unsafe extern "C" fn stub_host_log(
    _this: *const polyplug_abi::HostApi,
    _level: u32,
    _scope: polyplug_abi::StringView,
    _message: polyplug_abi::StringView,
) {
}

unsafe extern "C" fn stub_create_guest_instance(
    _this: *const polyplug_abi::HostApi,
    _interface: *const polyplug_abi::GuestContractInterface,
    _args: *const core::ffi::c_void,
    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()) };
    }
}

unsafe extern "C" fn stub_destroy_guest_instance(
    _this: *const polyplug_abi::HostApi,
    _interface: *const polyplug_abi::GuestContractInterface,
    _instance: polyplug_abi::GuestContractInstance,
) {
}

unsafe extern "C" fn stub_revision_counter(_this: *const polyplug_abi::HostApi) -> *const u64 {
    core::ptr::null()
}