numcodecs_wasm_host_reproducible/
engine.rs

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
use wasm_runtime_layer::{
    backend::{
        AsContext, AsContextMut, Export, Extern, Imports, Value, WasmEngine, WasmExternRef,
        WasmFunc, WasmGlobal, WasmInstance, WasmMemory, WasmModule, WasmStore, WasmStoreContext,
        WasmStoreContextMut, WasmTable,
    },
    ExportType, ExternType, FuncType, GlobalType, ImportType, MemoryType, TableType,
};

use crate::transform::{
    instcnt::{InstructionCounterInjecter, PerfWitInterfaces},
    nan::NaNCanonicaliser,
};

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleEngine<E: WasmEngine>(E);

impl<E: WasmEngine> WasmEngine for ReproducibleEngine<E> {
    type ExternRef = ReproducibleExternRef<E>;
    type Func = ReproducibleFunc<E>;
    type Global = ReproducibleGlobal<E>;
    type Instance = ReproducibleInstance<E>;
    type Memory = ReproducibleMemory<E>;
    type Module = ReproducibleModule<E>;
    type Store<T> = ReproducibleStore<T, E>;
    type StoreContext<'a, T: 'a> = ReproducibleStoreContext<'a, T, E>;
    type StoreContextMut<'a, T: 'a> = ReproducibleStoreContextMut<'a, T, E>;
    type Table = ReproducibleTable<E>;
}

impl<E: WasmEngine> ReproducibleEngine<E> {
    pub const fn new(engine: E) -> Self {
        Self(engine)
    }

    const fn as_ref(&self) -> &E {
        &self.0
    }

    const fn from_ref(engine: &E) -> &Self {
        // Safety: Self is a transparent newtype around E
        #[expect(unsafe_code)]
        unsafe {
            &*std::ptr::from_ref(engine).cast()
        }
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleExternRef<E: WasmEngine>(E::ExternRef);

impl<E: WasmEngine> WasmExternRef<ReproducibleEngine<E>> for ReproducibleExternRef<E> {
    fn new<T: 'static + Send + Sync>(
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        object: T,
    ) -> Self {
        Self(<E::ExternRef as WasmExternRef<E>>::new(
            ctx.as_context_mut().as_inner_context_mut(),
            object,
        ))
    }

    fn downcast<'a, 's: 'a, T: 'static, S: 'a>(
        &'a self,
        store: ReproducibleStoreContext<'s, S, E>,
    ) -> anyhow::Result<&'a T> {
        WasmExternRef::downcast(&self.0, store.0)
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleFunc<E: WasmEngine>(E::Func);

impl<E: WasmEngine> WasmFunc<ReproducibleEngine<E>> for ReproducibleFunc<E> {
    fn new<T>(
        mut ctx: impl AsContextMut<ReproducibleEngine<E>, UserState = T>,
        ty: FuncType,
        func: impl 'static
            + Send
            + Sync
            + Fn(
                ReproducibleStoreContextMut<T, E>,
                &[Value<ReproducibleEngine<E>>],
                &mut [Value<ReproducibleEngine<E>>],
            ) -> anyhow::Result<()>,
    ) -> Self {
        Self(<E::Func as WasmFunc<E>>::new(
            ctx.as_context_mut().as_inner_context_mut(),
            ty,
            move |ctx, args, results| {
                func(
                    ReproducibleStoreContextMut(ctx),
                    from_values(args),
                    from_values_mut(results),
                )
            },
        ))
    }

    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> FuncType {
        WasmFunc::ty(&self.0, ctx.as_context().as_inner_context())
    }

    fn call<T>(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        args: &[Value<ReproducibleEngine<E>>],
        results: &mut [Value<ReproducibleEngine<E>>],
    ) -> anyhow::Result<()> {
        WasmFunc::call::<T>(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            as_values(args),
            as_values_mut(results),
        )
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleGlobal<E: WasmEngine>(E::Global);

impl<E: WasmEngine> WasmGlobal<ReproducibleEngine<E>> for ReproducibleGlobal<E> {
    fn new(
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        value: Value<ReproducibleEngine<E>>,
        mutable: bool,
    ) -> Self {
        Self(<E::Global as WasmGlobal<E>>::new(
            ctx.as_context_mut().as_inner_context_mut(),
            into_value(value),
            mutable,
        ))
    }

    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> GlobalType {
        WasmGlobal::ty(&self.0, ctx.as_context().as_inner_context())
    }

    fn set(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        new_value: Value<ReproducibleEngine<E>>,
    ) -> anyhow::Result<()> {
        WasmGlobal::set(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            into_value(new_value),
        )
    }

    fn get(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
    ) -> Value<ReproducibleEngine<E>> {
        from_value(WasmGlobal::get(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
        ))
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleInstance<E: WasmEngine>(E::Instance);

impl<E: WasmEngine> WasmInstance<ReproducibleEngine<E>> for ReproducibleInstance<E> {
    fn new(
        mut store: impl AsContextMut<ReproducibleEngine<E>>,
        module: &ReproducibleModule<E>,
        imports: &Imports<ReproducibleEngine<E>>,
    ) -> anyhow::Result<Self> {
        let mut new_imports = Imports::new();
        new_imports.extend(
            imports
                .into_iter()
                .map(|((module, name), value)| ((module, name), into_extern(value))),
        );

        let PerfWitInterfaces {
            perf: perf_interface,
            instruction_counter,
        } = PerfWitInterfaces::get();
        new_imports.define(
            &format!("{perf_interface}"),
            instruction_counter,
            Extern::Global(
                store
                    .as_context_mut()
                    .get_instruction_counter_global()
                    .0
                    .clone(),
            ),
        );

        Ok(Self(<E::Instance as WasmInstance<E>>::new(
            store.as_context_mut().as_inner_context_mut(),
            &module.0,
            &new_imports,
        )?))
    }

    fn exports(
        &self,
        store: impl AsContext<ReproducibleEngine<E>>,
    ) -> Box<dyn Iterator<Item = Export<ReproducibleEngine<E>>>> {
        Box::new(
            WasmInstance::exports(&self.0, store.as_context().as_inner_context()).map(
                |Export { name, value }| Export {
                    name,
                    value: from_extern(value),
                },
            ),
        )
    }

    fn get_export(
        &self,
        store: impl AsContext<ReproducibleEngine<E>>,
        name: &str,
    ) -> Option<Extern<ReproducibleEngine<E>>> {
        WasmInstance::get_export(&self.0, store.as_context().as_inner_context(), name)
            .map(from_extern)
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleMemory<E: WasmEngine>(E::Memory);

impl<E: WasmEngine> WasmMemory<ReproducibleEngine<E>> for ReproducibleMemory<E> {
    fn new(
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        ty: MemoryType,
    ) -> anyhow::Result<Self> {
        Ok(Self(<E::Memory as WasmMemory<E>>::new(
            ctx.as_context_mut().as_inner_context_mut(),
            ty,
        )?))
    }

    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> MemoryType {
        WasmMemory::ty(&self.0, ctx.as_context().as_inner_context())
    }

    fn grow(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        additional: u32,
    ) -> anyhow::Result<u32> {
        WasmMemory::grow(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            additional,
        )
    }

    fn current_pages(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> u32 {
        WasmMemory::current_pages(&self.0, ctx.as_context().as_inner_context())
    }

    fn read(
        &self,
        ctx: impl AsContext<ReproducibleEngine<E>>,
        offset: usize,
        buffer: &mut [u8],
    ) -> anyhow::Result<()> {
        WasmMemory::read(&self.0, ctx.as_context().as_inner_context(), offset, buffer)
    }

    fn write(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        offset: usize,
        buffer: &[u8],
    ) -> anyhow::Result<()> {
        WasmMemory::write(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            offset,
            buffer,
        )
    }
}

pub const DETERMINISTIC_WASM_MODULE_FEATURES: wasmparser::WasmFeaturesInflated =
    wasmparser::WasmFeaturesInflated {
        // MUST: mutable globals do not introduce non-determinism, as long
        //       as the host does not change their value to be non-
        //       deterministic
        mutable_global: true,
        // OK: saturating float -> int conversions only produce finite values
        saturating_float_to_int: true,
        // MUST: arithmetic sign extension operators are deterministic
        sign_extension: true,
        // (unsure): disabled for now, needs further research
        reference_types: false,
        // OK: returning multiple values does not interact with determinism
        multi_value: true,
        // MUST: operations like memcpy and memset are deterministic
        bulk_memory: true,
        // (ok): fixed-width SIMD replicates scalar float semantics
        simd: true,
        // BAD: exposes platform-dependent behaviour and non-determinism
        relaxed_simd: false,
        // BAD: allows non-deterministic concurrency and race conditions
        threads: false,
        // BAD: allows non-deterministic concurrency and race conditions
        shared_everything_threads: false,
        // (ok): using tail calls does not interact with determinism
        //       but support is not universal yet:
        //       https://webassembly.org/features/
        tail_call: false,
        // BAD: float operations can introduce non-deterministic NaNs
        floats: false,
        // MUST: using multiple memories does not interact with determinism
        multi_memory: true,
        // (unsure): disabled for now, needs further research
        exceptions: false,
        // (nope): using a 64bit memory space does not interact with
        //         determinism but encourages large memory usage
        memory64: false,
        // (ok): const i[32|64] add, sub, and mul are deterministic
        //       but support is not universal yet:
        //       https://webassembly.org/features/
        extended_const: false,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model: false,
        // (unsure): disabled for now, needs further research
        function_references: false,
        // (unsure): disabled for now, needs further research
        memory_control: false,
        // (unsure): disabled for now, needs further research
        gc: false,
        // (ok): statically declaring a custom page size is deterministic
        //       and could reduce resource consumption
        //       but there is no support yet
        custom_page_sizes: false,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model_values: false,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model_nested_names: false,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model_more_flags: false,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model_multiple_returns: false,
        // (unsure): disabled for now, needs further research
        legacy_exceptions: false,
        // (unsure): disabled for now, depends on reference types and gc,
        //           needs further research
        gc_types: false,
        // (unsure): disabled for now, not needed since codecs are sync for now
        stack_switching: false,
        // OK: wide integer add, sub, and mul are deterministic
        wide_arithmetic: true,
        // NO-CORE: components must have been translated into core WASM
        //          modules by now
        component_model_async: false,
    };

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleModule<E: WasmEngine>(E::Module);

impl<E: WasmEngine> WasmModule<ReproducibleEngine<E>> for ReproducibleModule<E> {
    fn new(engine: &ReproducibleEngine<E>, mut stream: impl std::io::Read) -> anyhow::Result<Self> {
        let features = wasmparser::WasmFeatures::from(wasmparser::WasmFeaturesInflated {
            // MUST: floats are required and we are running the NaN
            //       canonicalisation transform to make them deterministic
            floats: true,
            ..DETERMINISTIC_WASM_MODULE_FEATURES
        });

        let mut bytes = Vec::new();
        stream.read_to_end(&mut bytes)?;

        wasmparser::Validator::new_with_features(features).validate_all(&bytes)?;

        // Inject an instruction counter into the WASM module
        let bytes = InstructionCounterInjecter::apply_to_module(&bytes, features)?;

        // Normalise NaNs to ensure floating point operations are deterministic
        let bytes = NaNCanonicaliser::apply_to_module(&bytes, features)?;

        Ok(Self(<E::Module as WasmModule<E>>::new(
            engine.as_ref(),
            bytes.as_slice(),
        )?))
    }

    fn exports(&self) -> Box<dyn '_ + Iterator<Item = ExportType<'_>>> {
        WasmModule::exports(&self.0)
    }

    fn get_export(&self, name: &str) -> Option<ExternType> {
        WasmModule::get_export(&self.0, name)
    }

    fn imports(&self) -> Box<dyn '_ + Iterator<Item = ImportType<'_>>> {
        WasmModule::imports(&self.0)
    }
}

struct StoreData<T, E: WasmEngine> {
    data: T,
    instruction_counter: Option<ReproducibleGlobal<E>>,
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleStore<T, E: WasmEngine>(E::Store<StoreData<T, E>>);

impl<T, E: WasmEngine> WasmStore<T, ReproducibleEngine<E>> for ReproducibleStore<T, E> {
    fn new(engine: &ReproducibleEngine<E>, data: T) -> Self {
        Self(<E::Store<StoreData<T, E>> as WasmStore<
            StoreData<T, E>,
            E,
        >>::new(
            engine.as_ref(),
            StoreData {
                data,
                instruction_counter: None,
            },
        ))
    }

    fn engine(&self) -> &ReproducibleEngine<E> {
        ReproducibleEngine::from_ref(WasmStore::engine(&self.0))
    }

    fn data(&self) -> &T {
        &WasmStore::data(&self.0).data
    }

    fn data_mut(&mut self) -> &mut T {
        &mut WasmStore::data_mut(&mut self.0).data
    }

    fn into_data(self) -> T {
        WasmStore::into_data(self.0).data
    }
}

impl<T, E: WasmEngine> AsContext<ReproducibleEngine<E>> for ReproducibleStore<T, E> {
    type UserState = T;

    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
        ReproducibleStoreContext(AsContext::as_context(&self.0))
    }
}

impl<T, E: WasmEngine> AsContextMut<ReproducibleEngine<E>> for ReproducibleStore<T, E> {
    fn as_context_mut(&mut self) -> ReproducibleStoreContextMut<'_, Self::UserState, E> {
        ReproducibleStoreContextMut(AsContextMut::as_context_mut(&mut self.0))
    }
}

#[repr(transparent)]
pub struct ReproducibleStoreContext<'a, T: 'a, E: WasmEngine>(E::StoreContext<'a, StoreData<T, E>>);

impl<'a, T: 'a, E: WasmEngine> WasmStoreContext<'a, T, ReproducibleEngine<E>>
    for ReproducibleStoreContext<'a, T, E>
{
    fn engine(&self) -> &ReproducibleEngine<E> {
        ReproducibleEngine::from_ref(WasmStoreContext::engine(&self.0))
    }

    fn data(&self) -> &T {
        &WasmStoreContext::data(&self.0).data
    }
}

impl<'a, T: 'a, E: WasmEngine> AsContext<ReproducibleEngine<E>>
    for ReproducibleStoreContext<'a, T, E>
{
    type UserState = T;

    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
        ReproducibleStoreContext(AsContext::as_context(&self.0))
    }
}

impl<'a, T: 'a, E: WasmEngine> ReproducibleStoreContext<'a, T, E> {
    fn as_inner_context(&self) -> E::StoreContext<'_, StoreData<T, E>> {
        self.0.as_context()
    }
}

#[repr(transparent)]
pub struct ReproducibleStoreContextMut<'a, T: 'a, E: WasmEngine>(
    E::StoreContextMut<'a, StoreData<T, E>>,
);

impl<'a, T: 'a, E: WasmEngine> WasmStoreContext<'a, T, ReproducibleEngine<E>>
    for ReproducibleStoreContextMut<'a, T, E>
{
    fn engine(&self) -> &ReproducibleEngine<E> {
        ReproducibleEngine::from_ref(WasmStoreContext::engine(&self.0))
    }

    fn data(&self) -> &T {
        &WasmStoreContext::data(&self.0).data
    }
}

impl<'a, T: 'a, E: WasmEngine> WasmStoreContextMut<'a, T, ReproducibleEngine<E>>
    for ReproducibleStoreContextMut<'a, T, E>
{
    fn data_mut(&mut self) -> &mut T {
        &mut WasmStoreContextMut::data_mut(&mut self.0).data
    }
}

impl<'a, T: 'a, E: WasmEngine> AsContext<ReproducibleEngine<E>>
    for ReproducibleStoreContextMut<'a, T, E>
{
    type UserState = T;

    fn as_context(&self) -> ReproducibleStoreContext<'_, Self::UserState, E> {
        ReproducibleStoreContext(AsContext::as_context(&self.0))
    }
}

impl<'a, T: 'a, E: WasmEngine> AsContextMut<ReproducibleEngine<E>>
    for ReproducibleStoreContextMut<'a, T, E>
{
    fn as_context_mut(&mut self) -> ReproducibleStoreContextMut<'_, Self::UserState, E> {
        ReproducibleStoreContextMut(AsContextMut::as_context_mut(&mut self.0))
    }
}

impl<'a, T: 'a, E: WasmEngine> ReproducibleStoreContextMut<'a, T, E> {
    fn as_inner_context_mut(&mut self) -> E::StoreContextMut<'_, StoreData<T, E>> {
        self.0.as_context_mut()
    }

    fn get_instruction_counter_global(&mut self) -> &ReproducibleGlobal<E> {
        let mut this = self;

        // NLL cannot prove this to be safe, but Polonius can
        polonius_the_crab::polonius!(|this| -> &'polonius ReproducibleGlobal<E> {
            let data: &mut StoreData<T, E> = WasmStoreContextMut::data_mut(&mut this.0);
            if let Some(global) = &data.instruction_counter {
                polonius_the_crab::polonius_return!(global);
            }
        });

        let global = WasmGlobal::new(AsContextMut::as_context_mut(this), Value::I64(0), true);

        let data: &mut StoreData<T, E> = WasmStoreContextMut::data_mut(&mut this.0);
        data.instruction_counter.insert(global)
    }
}

#[derive(Clone)]
#[repr(transparent)]
pub struct ReproducibleTable<E: WasmEngine>(E::Table);

impl<E: WasmEngine> WasmTable<ReproducibleEngine<E>> for ReproducibleTable<E> {
    fn new(
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        ty: TableType,
        init: Value<ReproducibleEngine<E>>,
    ) -> anyhow::Result<Self> {
        Ok(Self(<E::Table as WasmTable<E>>::new(
            ctx.as_context_mut().as_inner_context_mut(),
            ty,
            into_value(init),
        )?))
    }

    fn ty(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> TableType {
        WasmTable::ty(&self.0, ctx.as_context().as_inner_context())
    }

    fn size(&self, ctx: impl AsContext<ReproducibleEngine<E>>) -> u32 {
        WasmTable::size(&self.0, ctx.as_context().as_inner_context())
    }

    fn grow(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        delta: u32,
        init: Value<ReproducibleEngine<E>>,
    ) -> anyhow::Result<u32> {
        WasmTable::grow(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            delta,
            into_value(init),
        )
    }

    fn get(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        index: u32,
    ) -> Option<Value<ReproducibleEngine<E>>> {
        WasmTable::get(&self.0, ctx.as_context_mut().as_inner_context_mut(), index).map(from_value)
    }

    fn set(
        &self,
        mut ctx: impl AsContextMut<ReproducibleEngine<E>>,
        index: u32,
        value: Value<ReproducibleEngine<E>>,
    ) -> anyhow::Result<()> {
        WasmTable::set(
            &self.0,
            ctx.as_context_mut().as_inner_context_mut(),
            index,
            into_value(value),
        )
    }
}

const fn as_values<E: WasmEngine>(values: &[Value<ReproducibleEngine<E>>]) -> &[Value<E>] {
    // Safety: all of our WASM runtime type wrappers are transparent newtypes
    #[expect(unsafe_code)]
    unsafe {
        std::slice::from_raw_parts(values.as_ptr().cast(), values.len())
    }
}

fn as_values_mut<E: WasmEngine>(values: &mut [Value<ReproducibleEngine<E>>]) -> &mut [Value<E>] {
    // Safety: all of our WASM runtime type wrappers are transparent newtypes
    #[expect(unsafe_code)]
    unsafe {
        std::slice::from_raw_parts_mut(values.as_mut_ptr().cast(), values.len())
    }
}

const fn from_values<E: WasmEngine>(values: &[Value<E>]) -> &[Value<ReproducibleEngine<E>>] {
    // Safety: all of our WASM runtime type wrappers are transparent newtypes
    #[expect(unsafe_code)]
    unsafe {
        std::slice::from_raw_parts(values.as_ptr().cast(), values.len())
    }
}

fn from_values_mut<E: WasmEngine>(values: &mut [Value<E>]) -> &mut [Value<ReproducibleEngine<E>>] {
    // Safety: all of our WASM runtime type wrappers are transparent newtypes
    #[expect(unsafe_code)]
    unsafe {
        std::slice::from_raw_parts_mut(values.as_mut_ptr().cast(), values.len())
    }
}

fn into_value<E: WasmEngine>(value: Value<ReproducibleEngine<E>>) -> Value<E> {
    match value {
        Value::I32(v) => Value::I32(v),
        Value::I64(v) => Value::I64(v),
        Value::F32(v) => Value::F32(v),
        Value::F64(v) => Value::F64(v),
        Value::FuncRef(v) => Value::FuncRef(v.map(|v| v.0)),
        Value::ExternRef(v) => Value::ExternRef(v.map(|v| v.0)),
    }
}

fn from_value<E: WasmEngine>(value: Value<E>) -> Value<ReproducibleEngine<E>> {
    match value {
        Value::I32(v) => Value::I32(v),
        Value::I64(v) => Value::I64(v),
        Value::F32(v) => Value::F32(v),
        Value::F64(v) => Value::F64(v),
        Value::FuncRef(v) => Value::FuncRef(v.map(ReproducibleFunc)),
        Value::ExternRef(v) => Value::ExternRef(v.map(ReproducibleExternRef)),
    }
}

fn into_extern<E: WasmEngine>(value: Extern<ReproducibleEngine<E>>) -> Extern<E> {
    match value {
        Extern::Global(v) => Extern::Global(v.0),
        Extern::Table(v) => Extern::Table(v.0),
        Extern::Memory(v) => Extern::Memory(v.0),
        Extern::Func(v) => Extern::Func(v.0),
    }
}

fn from_extern<E: WasmEngine>(value: Extern<E>) -> Extern<ReproducibleEngine<E>> {
    match value {
        Extern::Global(v) => Extern::Global(ReproducibleGlobal(v)),
        Extern::Table(v) => Extern::Table(ReproducibleTable(v)),
        Extern::Memory(v) => Extern::Memory(ReproducibleMemory(v)),
        Extern::Func(v) => Extern::Func(ReproducibleFunc(v)),
    }
}