aion-rs 0.4.0

Transport-agnostic Aion workflow engine with durability, replay, timers, and supervision.
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
//! `RuntimeHandle` spawn, register, cancel, and shutdown support.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use aion_core::{ActivityError, Payload};
use beamr::atom::AtomTable;
use beamr::module::ModuleRegistry;
use beamr::native::{BifRegistryImpl, NativeRegistrationError};
use beamr::process::ExitReason;
use beamr::scheduler::{Scheduler, SchedulerConfig};
use beamr::term::Term;

use crate::error::EngineError;

use super::config::{RuntimeConfig, SignalDeliveryConfig};
use super::nif::{Mfa, NifRegistration};
use super::payload::payload_to_term;

/// Local BEAM process identifier exposed by the runtime boundary.
pub type Pid = u64;

type RetainedHeap = Box<[u64]>;
type RetainedHeaps = Vec<RetainedHeap>;
type RetainedSpawnHeaps = Arc<dashmap::DashMap<Pid, Mutex<RetainedHeaps>>>;

/// Runtime-owned workflow or activity input terms.
///
/// The wrapper keeps the beamr term representation inside the runtime module
/// while later lifecycle and payload code decide how durable payloads become VM
/// terms.
#[derive(Debug, Default, Eq, PartialEq)]
pub struct RuntimeInput {
    terms: Vec<Term>,
    heaps: RetainedHeaps,
}

impl RuntimeInput {
    /// Convert one durable payload into the single BEAM argument used by
    /// in-VM activity dispatch.
    ///
    /// The runtime boundary owns this representation. JSON payloads are passed
    /// as BEAM binary terms and any boxed host heap backing those terms is
    /// retained until the spawned process is observed exiting or cancelled.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when a JSON number does not fit in an
    /// immediate small integer.
    pub fn from_payload(payload: &Payload) -> Result<Self, EngineError> {
        let (term, heaps) = payload_to_term(payload)?.into_parts();
        Ok(Self {
            terms: vec![term],
            heaps,
        })
    }

    /// Number of terms supplied to the BEAM entrypoint.
    #[must_use]
    pub fn arity(&self) -> u8 {
        u8::try_from(self.terms.len()).unwrap_or(u8::MAX)
    }

    fn into_spawn_parts(self) -> (Vec<Term>, RetainedHeaps) {
        (self.terms, self.heaps)
    }
}

/// Handle to the embedded beamr scheduler and code-server state.
pub struct RuntimeHandle {
    pub(super) scheduler: Scheduler,
    pub(super) atom_table: Arc<AtomTable>,
    pub(super) module_registry: Arc<ModuleRegistry>,
    pub(super) native_registry: Arc<BifRegistryImpl>,
    nif_state: Arc<super::nif_state::EngineNifState>,
    activity_results: Arc<dashmap::DashMap<(Pid, Pid), Payload>>,
    activity_errors: Arc<dashmap::DashMap<(Pid, Pid), ActivityError>>,
    registered_nif_modules: Arc<dashmap::DashSet<String>>,
    spawn_heaps: RetainedSpawnHeaps,
    signal_delivery: SignalDeliveryConfig,
    /// Bounded follow-up wakes for delivered mailbox markers, healing
    /// beamr 0.4.9's lost-wakeup window (see [`super::wake_confirm`]).
    pub(super) wake_confirmer: super::wake_confirm::WakeConfirmer,
    /// Highest process identifier this runtime has spawned.
    ///
    /// beamr allocates pids from a monotonic counter, so any pid at or below
    /// this watermark was spawned here and its exit outcome stays observable
    /// through the scheduler's exit tombstones even after the process leaves
    /// the live table. Monitor installation uses this to accept processes
    /// that exited between spawn and monitor setup.
    spawned_pid_watermark: AtomicU64,
}

impl RuntimeHandle {
    /// Construct and start an embedded runtime from builder-supplied config.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when beamr cannot start its scheduler.
    pub fn new(config: RuntimeConfig) -> Result<Self, EngineError> {
        let atom_table = Arc::new(AtomTable::with_common_atoms());
        let module_registry = Arc::new(ModuleRegistry::new());
        // One NIF state per runtime instance, recovered by every native call
        // through beamr's NIF private data — never process-wide globals.
        let nif_state = Arc::new(super::nif_state::EngineNifState::default());
        let scheduler_config = SchedulerConfig {
            thread_count: config.thread_count,
            nif_private_data: Some(Arc::clone(&nif_state) as _),
            ..Default::default()
        };
        let native_registry = Arc::new(BifRegistryImpl::new());
        register_all_bifs(&native_registry, &atom_table)?;
        let scheduler = Scheduler::with_code_server(
            scheduler_config,
            Arc::clone(&module_registry),
            Arc::clone(&atom_table),
            Arc::clone(&native_registry),
        )
        .map_err(runtime_error_from_display)?;

        Ok(Self {
            scheduler,
            atom_table,
            module_registry,
            native_registry,
            nif_state,
            activity_results: Arc::new(dashmap::DashMap::new()),
            activity_errors: Arc::new(dashmap::DashMap::new()),
            registered_nif_modules: Arc::new(dashmap::DashSet::new()),
            spawn_heaps: Arc::new(dashmap::DashMap::new()),
            signal_delivery: config.signal_delivery,
            wake_confirmer: super::wake_confirm::WakeConfirmer::new(config.signal_delivery)?,
            spawned_pid_watermark: AtomicU64::new(0),
        })
    }

    /// This runtime instance's engine-scoped NIF state.
    pub(crate) fn nif_state(&self) -> &Arc<super::nif_state::EngineNifState> {
        &self.nif_state
    }

    /// Builder-supplied delivery/readiness policy for spawn-window waits.
    pub(crate) fn signal_delivery(&self) -> SignalDeliveryConfig {
        self.signal_delivery
    }

    /// Install collected NIF entries into beamr's native registry.
    ///
    /// Consumes the registration collection so no caller can append more entries
    /// after this installation step. Callers must invoke this before loading and
    /// spawning workflow modules whose imports depend on these NIFs.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::NifRegistration`] when beamr rejects an entry,
    /// including duplicate module/function/arity registrations.
    pub fn install_nifs(&self, registration: NifRegistration) -> Result<(), EngineError> {
        for entry in registration.into_entries() {
            let mfa = entry.mfa;
            let module = self.atom_table.intern(&mfa.module);
            let function = self.atom_table.intern(&mfa.function);
            let capability = beamr::native::Capability::ExternalIo;
            let result = if entry.is_dirty {
                self.native_registry.register_dirty(
                    module,
                    function,
                    mfa.arity,
                    entry.function,
                    beamr::scheduler::dirty::DirtySchedulerKind::Cpu,
                    capability,
                )
            } else {
                self.native_registry.register(
                    module,
                    function,
                    mfa.arity,
                    entry.function,
                    capability,
                )
            };
            result.map_err(|error| nif_registration_error(&mfa, error))?;
            self.registered_nif_modules.insert(mfa.module);
        }

        Ok(())
    }

    /// Return module names that have registered NIFs and should not be
    /// content-hash renamed during package loading.
    #[must_use]
    pub fn registered_nif_modules(&self) -> Vec<String> {
        let mut module_names: Vec<_> = self
            .registered_nif_modules
            .iter()
            .map(|module_name| module_name.key().clone())
            .collect();
        module_names.sort();
        module_names
    }

    /// Spawn a top-level workflow process at a deployed module/function entrypoint.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when the module/function/arity cannot be
    /// resolved or beamr rejects the spawn request.
    pub fn spawn_workflow(
        &self,
        deployed_module: &str,
        function: &str,
        input: RuntimeInput,
    ) -> Result<Pid, EngineError> {
        self.spawn_process(deployed_module, function, input)
    }

    /// Spawn a top-level workflow process with trap-exit enabled before it runs.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when the module/function/arity cannot be
    /// resolved or beamr rejects the spawn request.
    pub fn spawn_workflow_trapping(
        &self,
        deployed_module: &str,
        function: &str,
        input: RuntimeInput,
    ) -> Result<Pid, EngineError> {
        self.release_dead_spawn_heaps();
        let module = self.atom_table.intern(deployed_module);
        let function = self.atom_table.intern(function);
        let (terms, heaps) = input.into_spawn_parts();
        let pid = self
            .scheduler
            .spawn_trap_exit(module, function, terms)
            .map_err(runtime_error_from_display)?;
        self.record_spawned_pid(pid);
        self.retain_spawn_heaps(pid, heaps);
        Ok(pid)
    }

    /// Spawn an activity child process linked to its workflow parent.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when the parent process is not live, the
    /// module/function/arity cannot be resolved, or beamr rejects the linked
    /// spawn request.
    pub fn spawn_activity(
        &self,
        parent_pid: Pid,
        deployed_module: &str,
        function: &str,
        input: RuntimeInput,
    ) -> Result<Pid, EngineError> {
        self.release_dead_spawn_heaps();
        self.ensure_live_pid(parent_pid)?;
        self.wait_for_process_ready(parent_pid)?;
        let arity = input.arity();
        let module = self.atom_table.intern(deployed_module);
        let function_atom = self.atom_table.intern(function);
        let (terms, heaps) = input.into_spawn_parts();
        let pid = if self.is_dirty_with_arity(deployed_module, function, arity) {
            self.scheduler
                .spawn_link_dirty(parent_pid, module, function_atom, terms)
                .map_err(runtime_error_from_display)?
        } else {
            self.scheduler
                .spawn_link(parent_pid, module, function_atom, terms)
                .map_err(runtime_error_from_display)?
        };
        self.record_spawned_pid(pid);
        self.retain_spawn_heaps(pid, heaps);
        Ok(pid)
    }

    /// Return whether the registered native activity entry is dirty for arity 1.
    #[must_use]
    pub fn is_dirty(&self, module: &str, function: &str) -> bool {
        self.is_dirty_with_arity(module, function, 1)
    }

    /// Return whether the registered native entry is dirty for the supplied arity.
    #[must_use]
    pub fn is_dirty_with_arity(&self, module: &str, function: &str, arity: u8) -> bool {
        let module = self.atom_table.intern(module);
        let function = self.atom_table.intern(function);
        self.native_registry
            .lookup(module, function, arity)
            .is_some_and(|entry| entry.dirty_kind.is_some())
    }

    /// Cancel a live process by PID.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when `pid` is not live.
    pub fn cancel_pid(&self, pid: Pid) -> Result<(), EngineError> {
        self.ensure_live_pid(pid)?;
        self.scheduler.terminate_process(pid, ExitReason::Kill);
        self.release_spawn_heaps(pid);
        Ok(())
    }

    /// Set a live process' trap-exit flag, returning the previous value.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when `pid` is not live.
    pub fn set_trap_exit(&self, pid: Pid, value: bool) -> Result<bool, EngineError> {
        self.scheduler
            .set_trap_exit(pid, value)
            .map_err(runtime_error_from_display)
    }

    /// Return true when `pid` is currently live.
    #[must_use]
    pub fn is_live(&self, pid: Pid) -> bool {
        self.scheduler.process_table().get(pid).is_some()
    }

    /// Return a live process' trap-exit flag.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when `pid` is not live.
    pub fn trap_exit(&self, pid: Pid) -> Result<bool, EngineError> {
        self.scheduler
            .trap_exit(pid)
            .ok_or_else(|| runtime_error(format!("process {pid} is not live")))
    }

    /// Return true when two live processes have a bidirectional link.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when either process is not live.
    pub fn is_linked(&self, left: Pid, right: Pid) -> Result<bool, EngineError> {
        self.ensure_live_pid(left)?;
        self.ensure_live_pid(right)?;
        Ok(self.scheduler.is_linked(left, right))
    }

    /// Shut down the embedded scheduler and wait for worker threads to stop.
    ///
    /// # Errors
    ///
    /// Currently infallible; reserved for typed runtime shutdown failures.
    pub fn shutdown(&self) -> Result<(), EngineError> {
        // Stop the wake-confirmation worker first: its only job is healing
        // lost wakeups for a running scheduler, and pending follow-ups are
        // moot once the scheduler stops.
        self.wake_confirmer.shutdown();
        self.scheduler.shutdown();
        self.spawn_heaps.clear();
        Ok(())
    }

    fn spawn_process(
        &self,
        deployed_module: &str,
        function: &str,
        input: RuntimeInput,
    ) -> Result<Pid, EngineError> {
        self.release_dead_spawn_heaps();
        let module = self.atom_table.intern(deployed_module);
        let function = self.atom_table.intern(function);
        let (terms, heaps) = input.into_spawn_parts();
        let pid = self
            .scheduler
            .spawn(module, function, terms)
            .map_err(runtime_error_from_display)?;
        self.record_spawned_pid(pid);
        self.retain_spawn_heaps(pid, heaps);
        Ok(pid)
    }

    fn record_spawned_pid(&self, pid: Pid) {
        self.spawned_pid_watermark.fetch_max(pid, Ordering::AcqRel);
    }

    fn retain_spawn_heaps(&self, pid: Pid, heaps: RetainedHeaps) {
        if heaps.is_empty() {
            return;
        }
        self.spawn_heaps.insert(pid, Mutex::new(heaps));
    }

    pub(super) fn release_spawn_heaps(&self, pid: Pid) {
        self.spawn_heaps.remove(&pid);
    }

    fn release_dead_spawn_heaps(&self) {
        let dead_pids: Vec<Pid> = self
            .spawn_heaps
            .iter()
            .filter_map(|entry| {
                let pid = *entry.key();
                self.scheduler
                    .process_table()
                    .get(pid)
                    .is_none()
                    .then_some(pid)
            })
            .collect();
        for pid in dead_pids {
            self.release_spawn_heaps(pid);
        }
    }

    pub(super) fn ensure_live_pid(&self, pid: Pid) -> Result<(), EngineError> {
        if self.scheduler.process_table().get(pid).is_some() {
            Ok(())
        } else {
            Err(runtime_error(format!("process {pid} is not live")))
        }
    }

    /// Ensure `pid` has an observable exit outcome: it is either live now or
    /// was spawned by this runtime and already exited.
    ///
    /// A workflow can run to completion on a scheduler thread between its
    /// spawn and the caller's monitor installation. The exited process is no
    /// longer in the live table, but beamr keeps its exit tombstone, so
    /// `run_until_exit` still returns the recorded outcome immediately.
    /// Rejecting such pids would spuriously fail the spawn of any workflow
    /// that finishes faster than its monitor is installed.
    pub(super) fn ensure_monitorable_pid(&self, pid: Pid) -> Result<(), EngineError> {
        if self.scheduler.process_table().get(pid).is_some() {
            return Ok(());
        }
        if pid > 0 && pid <= self.spawned_pid_watermark.load(Ordering::Acquire) {
            return Ok(());
        }
        Err(runtime_error(format!(
            "process {pid} was never spawned by this runtime"
        )))
    }

    /// Register a test module whose exported function waits indefinitely.
    ///
    /// This keeps lifecycle tests at the runtime boundary while still exercising
    /// real module lookup and trap-exit workflow spawning.
    #[cfg(test)]
    pub fn register_waiting_test_module(&self, deployed_name: &str, function: &str) {
        use std::collections::HashMap;

        use beamr::loader::Instruction;
        use beamr::loader::decode::compact::Operand;
        use beamr::module::Module;

        let module = self.atom_table.intern(deployed_name);
        let function = self.atom_table.intern(function);
        let label = 10;
        self.module_registry.insert(Module {
            name: module,
            generation: 0,
            origin: beamr::module::ModuleOrigin::Preloaded,
            exports: HashMap::from([((function, 1), label)]),
            label_index: HashMap::from([(label, 0)]),
            code: vec![
                Instruction::Label { label },
                Instruction::Wait {
                    fail: Operand::Label(label),
                },
            ],
            function_table: Vec::new(),
            line_table: Vec::new(),
            literals: Vec::new(),
            constant_pool: beamr::constant_pool::ConstantPool::new(),
            resolved_imports: Vec::new(),
            lambdas: Vec::new(),
            string_table: Vec::new(),
            line_info: Vec::new(),
        });
    }

    /// Spawn an inert test process without module code.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when beamr rejects the test spawn.
    #[cfg(test)]
    pub fn spawn_test_process(&self) -> Result<Pid, EngineError> {
        let pid = self.scheduler.spawn_test_process(false);
        self.record_spawned_pid(pid);
        Ok(pid)
    }

    /// Spawn an inert test process with explicit trap-exit state.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when beamr rejects the test spawn.
    #[cfg(test)]
    pub fn spawn_test_process_with_trap_exit(&self, trap_exit: bool) -> Result<Pid, EngineError> {
        let pid = self.scheduler.spawn_test_process(trap_exit);
        self.record_spawned_pid(pid);
        Ok(pid)
    }

    /// Spawn an inert linked test child without enabling trap-exit on the child.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when the parent is not live or beamr
    /// rejects the linked spawn.
    #[cfg(test)]
    pub fn spawn_linked_test_process(&self, parent_pid: Pid) -> Result<Pid, EngineError> {
        self.ensure_live_pid(parent_pid)?;
        let pid = self
            .scheduler
            .spawn_linked_test_process(parent_pid)
            .map_err(runtime_error_from_display)?;
        self.record_spawned_pid(pid);
        Ok(pid)
    }

    /// Return true when a live process has a trapped EXIT message from `source_pid`.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when `target_pid` is not live.
    #[cfg(test)]
    pub fn has_trapped_exit_message(
        &self,
        target_pid: Pid,
        source_pid: Pid,
    ) -> Result<bool, EngineError> {
        self.ensure_live_pid(target_pid)?;
        Ok(self
            .scheduler
            .has_trapped_exit_message(target_pid, source_pid)
            .unwrap_or(false))
    }

    /// Poll until a trapped EXIT message from `source_pid` arrives at `target_pid`.
    ///
    /// beamr delivers exit signals asynchronously after process termination.
    /// Tests that assert on trapped exit messages must wait for delivery.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] if the message does not arrive within 50ms.
    #[cfg(test)]
    pub fn wait_for_trapped_exit(
        &self,
        target_pid: Pid,
        source_pid: Pid,
    ) -> Result<(), EngineError> {
        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(50);
        while std::time::Instant::now() < deadline {
            if self
                .scheduler
                .has_trapped_exit_message(target_pid, source_pid)
                .unwrap_or(false)
            {
                return Ok(());
            }
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        Err(runtime_error(format!(
            "trapped exit from {source_pid} to {target_pid} did not arrive"
        )))
    }

    /// Terminate a test process with a trappable abnormal reason.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Runtime`] when `pid` is not live.
    #[cfg(test)]
    pub fn terminate_test_process_with_error(&self, pid: Pid) -> Result<(), EngineError> {
        self.ensure_live_pid(pid)?;
        self.scheduler.terminate_process(pid, ExitReason::Error);
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn lookup_native_for_test(
        &self,
        module: &str,
        function: &str,
        arity: u8,
    ) -> Option<beamr::native::NativeEntry> {
        let module = self.atom_table.intern(module);
        let function = self.atom_table.intern(function);
        self.native_registry.lookup(module, function, arity)
    }

    #[cfg(test)]
    pub(crate) fn run_until_exit_for_test(&self, pid: Pid) -> (ExitReason, Term) {
        let (reason, owned_result) = self.scheduler.run_until_exit(pid);
        self.release_spawn_heaps(pid);
        (reason, owned_result.root())
    }

    #[cfg(test)]
    pub(crate) fn retained_spawn_heap_count_for_test(&self) -> usize {
        self.release_dead_spawn_heaps();
        self.spawn_heaps.len()
    }
}

fn runtime_error(reason: String) -> EngineError {
    EngineError::Runtime { reason }
}

fn runtime_error_from_display(reason: impl std::fmt::Display) -> EngineError {
    runtime_error(reason.to_string())
}

fn nif_registration_error(mfa: &Mfa, error: NativeRegistrationError) -> EngineError {
    match error {
        NativeRegistrationError::DuplicateMfa { .. } => EngineError::NifRegistration {
            reason: format!("native function already registered for {}", mfa.display()),
        },
    }
}

fn register_all_bifs(
    registry: &BifRegistryImpl,
    atom_table: &AtomTable,
) -> Result<(), EngineError> {
    use beamr::native::{
        bifs::register_gate1_bifs, gate3_bifs::register_gate3_bifs,
        gleam_ffi::register_gleam_ffi_bifs, otp_stubs::init_otp_atoms,
        otp_stubs::register_otp_stubs, process_bifs::register_gate2_bifs,
        selector_ffi::register_selector_bifs, stdlib_stubs::register_stdlib_stubs,
    };
    register_gate1_bifs(registry, atom_table).map_err(runtime_error_from_display)?;
    register_gate2_bifs(registry, atom_table).map_err(runtime_error_from_display)?;
    register_gate3_bifs(registry, atom_table).map_err(runtime_error_from_display)?;
    register_stdlib_stubs(registry, atom_table).map_err(runtime_error_from_display)?;
    register_selector_bifs(registry, atom_table).map_err(runtime_error_from_display)?;
    register_gleam_ffi_bifs(registry, atom_table).map_err(runtime_error_from_display)?;
    init_otp_atoms(atom_table);
    register_otp_stubs(registry, atom_table).map_err(runtime_error_from_display)?;
    Ok(())
}

mod delivery;

#[cfg(test)]
#[path = "handle/test_support.rs"]
mod test_support;

#[cfg(test)]
mod tests {
    use aion_core::Payload;
    use std::time::Duration;

    use beamr::loader::Instruction;
    use beamr::loader::decode::compact::Operand;
    use beamr::module::{Module, ResolvedImport, ResolvedImportTarget};
    use beamr::native::ProcessContext;
    use beamr::term::Term;
    use beamr::term::binary_ref::BinaryRef;

    use super::{RuntimeHandle, RuntimeInput};
    use crate::error::EngineError;
    use crate::runtime::{Mfa, NifEntry, NifRegistration, RuntimeConfig, SignalDeliveryConfig};

    fn forty_two(args: &[Term], _context: &mut ProcessContext) -> Result<Term, Term> {
        if args.len() > 255 {
            return Err(Term::small_int(0));
        }
        Ok(Term::small_int(42))
    }

    fn thirteen(args: &[Term], _context: &mut ProcessContext) -> Result<Term, Term> {
        if args.len() > 255 {
            return Err(Term::small_int(0));
        }
        Ok(Term::small_int(13))
    }

    fn binary_length(args: &[Term], _context: &mut ProcessContext) -> Result<Term, Term> {
        match args {
            [term] => BinaryRef::new(*term)
                .and_then(|binary| i64::try_from(binary.as_bytes().len()).ok())
                .map(Term::small_int)
                .ok_or_else(|| Term::small_int(0)),
            _ => Err(Term::small_int(0)),
        }
    }

    fn native_call_module_for_test(
        module: beamr::atom::Atom,
        function: beamr::atom::Atom,
        target_module: beamr::atom::Atom,
        target_function: beamr::atom::Atom,
        native_entry: Option<beamr::native::NativeEntry>,
    ) -> Module {
        native_call_module_with_arity_for_test(
            module,
            function,
            target_module,
            target_function,
            0,
            native_entry,
        )
    }

    fn native_call_module_with_arity_for_test(
        module: beamr::atom::Atom,
        function: beamr::atom::Atom,
        target_module: beamr::atom::Atom,
        target_function: beamr::atom::Atom,
        arity: u8,
        native_entry: Option<beamr::native::NativeEntry>,
    ) -> Module {
        let label = 1;
        let code = vec![
            Instruction::Label { label },
            Instruction::CallExt {
                arity: Operand::Unsigned(arity.into()),
                import: Operand::Unsigned(0),
            },
            Instruction::Return,
        ];
        let mut module_data = Module {
            name: module,
            generation: 0,
            origin: beamr::module::ModuleOrigin::Preloaded,
            exports: std::collections::HashMap::from([((function, arity), label)]),
            label_index: std::collections::HashMap::from([(label, 0)]),
            code,
            function_table: Vec::new(),
            line_table: Vec::new(),
            literals: Vec::new(),
            constant_pool: beamr::constant_pool::ConstantPool::new(),
            resolved_imports: Vec::new(),
            lambdas: Vec::new(),
            string_table: Vec::new(),
            line_info: Vec::new(),
        };
        if let Some(native_entry) = native_entry {
            module_data.resolved_imports.push(ResolvedImport {
                module: target_module,
                function: target_function,
                arity,
                target: ResolvedImportTarget::Native(native_entry),
            });
        }
        module_data
    }

    fn assert_send_sync<T: Send + Sync>() {}

    fn fixture_workflow_beam() -> &'static [u8] {
        include_bytes!("../../tests/fixtures/aion_fixture_workflow.beam")
    }

    #[test]
    fn runtime_handle_is_send_sync() {
        assert_send_sync::<RuntimeHandle>();
    }

    #[test]
    fn registers_spawns_and_shuts_down() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        runtime.register_module("aion_fixture_workflow", fixture_workflow_beam())?;

        let pid =
            runtime.spawn_workflow("aion_fixture_workflow", "wait", RuntimeInput::default())?;
        assert!(runtime.cancel_pid(pid).is_ok());
        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn signal_delivery_to_dead_process_returns_typed_error()
    -> Result<(), Box<dyn std::error::Error>> {
        let signal_delivery =
            SignalDeliveryConfig::new(Duration::ZERO, 1, Duration::ZERO, Duration::ZERO);
        let runtime =
            RuntimeHandle::new(RuntimeConfig::new(Some(1)).with_signal_delivery(signal_delivery))?;
        let pid = runtime.spawn_test_process()?;
        runtime.terminate_test_process_with_error(pid)?;

        let error = runtime
            .deliver_signal_received(pid)
            .err()
            .ok_or("dead process delivery unexpectedly succeeded")?;

        assert!(matches!(error, EngineError::Runtime { .. }));
        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn duplicate_nif_mfa_returns_typed_error() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        let mfa = Mfa::new("host", "answer", 0);
        let mut registration = NifRegistration::new();
        registration.add_host_nifs([
            NifEntry::new(mfa.clone(), forty_two),
            NifEntry::dirty(mfa, thirteen),
        ]);

        let error = runtime.install_nifs(registration).err();

        assert!(matches!(
            error,
            Some(EngineError::NifRegistration { reason })
                if reason.contains("host:answer/0")
        ));
        assert_eq!(runtime.registered_nif_modules(), vec!["host"]);
        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn payload_binary_remains_valid_through_spawn_and_is_released()
    -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        let mfa = Mfa::new("host", "binary_length", 1);
        let mut registration = NifRegistration::new();
        registration.add_host_nifs([NifEntry::new(mfa, binary_length)]);
        runtime.install_nifs(registration)?;

        let native_entry = runtime.lookup_native_for_test("host", "binary_length", 1);
        let module = native_call_module_with_arity_for_test(
            runtime.atom_table.intern("payload_echo"),
            runtime.atom_table.intern("run"),
            runtime.atom_table.intern("host"),
            runtime.atom_table.intern("binary_length"),
            1,
            native_entry,
        );
        runtime.module_registry.insert(module);
        let payload = Payload::new(
            aion_core::ContentType::Json,
            br#"{"hello":"world"}"#.to_vec(),
        );

        let pid =
            runtime.spawn_workflow("payload_echo", "run", RuntimeInput::from_payload(&payload)?)?;
        assert_eq!(runtime.retained_spawn_heap_count_for_test(), 1);
        let (reason, result) = runtime.run_until_exit_for_test(pid);

        assert_eq!(reason, beamr::process::ExitReason::Normal);
        assert_eq!(
            result.as_small_int(),
            Some(i64::try_from(payload.bytes().len()).unwrap_or(0))
        );
        assert_eq!(runtime.retained_spawn_heap_count_for_test(), 0);
        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn workflow_outcome_releases_payload_heaps() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        let mfa = Mfa::new("host", "binary_length", 1);
        let mut registration = NifRegistration::new();
        registration.add_host_nifs([NifEntry::new(mfa, binary_length)]);
        runtime.install_nifs(registration)?;

        let native_entry = runtime.lookup_native_for_test("host", "binary_length", 1);
        let module = native_call_module_with_arity_for_test(
            runtime.atom_table.intern("payload_workflow_outcome"),
            runtime.atom_table.intern("run"),
            runtime.atom_table.intern("host"),
            runtime.atom_table.intern("binary_length"),
            1,
            native_entry,
        );
        runtime.module_registry.insert(module);
        let payload = Payload::new(
            aion_core::ContentType::Json,
            br#"{"workflow":"outcome"}"#.to_vec(),
        );

        let pid = runtime.spawn_workflow(
            "payload_workflow_outcome",
            "run",
            RuntimeInput::from_payload(&payload)?,
        )?;
        assert_eq!(runtime.retained_spawn_heap_count_for_test(), 1);
        let outcome = runtime.workflow_outcome(pid)?;

        assert_eq!(
            outcome?,
            Payload::from_json(&serde_json::json!(payload.bytes().len()))?
        );
        assert_eq!(runtime.retained_spawn_heap_count_for_test(), 0);
        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn repeated_completed_payload_spawns_do_not_accumulate_retained_heaps()
    -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        let mfa = Mfa::new("host", "binary_length", 1);
        let mut registration = NifRegistration::new();
        registration.add_host_nifs([NifEntry::new(mfa, binary_length)]);
        runtime.install_nifs(registration)?;

        let native_entry = runtime.lookup_native_for_test("host", "binary_length", 1);
        let module = native_call_module_with_arity_for_test(
            runtime.atom_table.intern("payload_echo_many"),
            runtime.atom_table.intern("run"),
            runtime.atom_table.intern("host"),
            runtime.atom_table.intern("binary_length"),
            1,
            native_entry,
        );
        runtime.module_registry.insert(module);
        let payload = Payload::new(
            aion_core::ContentType::Json,
            br#"{"iteration":true}"#.to_vec(),
        );

        for _ in 0..1_000 {
            let pid = runtime.spawn_workflow(
                "payload_echo_many",
                "run",
                RuntimeInput::from_payload(&payload)?,
            )?;
            let (reason, result) = runtime.run_until_exit_for_test(pid);
            assert_eq!(reason, beamr::process::ExitReason::Normal);
            assert_eq!(
                result.as_small_int(),
                Some(i64::try_from(payload.bytes().len()).unwrap_or(0))
            );
            assert_eq!(runtime.retained_spawn_heap_count_for_test(), 0);
        }

        runtime.shutdown()?;
        Ok(())
    }

    #[test]
    fn distinct_nifs_are_registered_and_callable() -> Result<(), Box<dyn std::error::Error>> {
        let runtime = RuntimeHandle::new(RuntimeConfig::new(None))?;
        let mut registration = NifRegistration::new();
        registration.add_engine_nifs().add_host_nifs([
            NifEntry::new(Mfa::new("host", "answer", 0), forty_two),
            NifEntry::dirty(Mfa::new("host", "thirteen", 0), thirteen),
        ]);

        runtime.install_nifs(registration)?;

        assert_eq!(
            runtime.registered_nif_modules(),
            vec!["aion_flow_ffi", "host"]
        );
        let answer = runtime.lookup_native_for_test("host", "answer", 0);
        assert!(answer.is_some());
        assert!(
            runtime
                .lookup_native_for_test("host", "thirteen", 0)
                .is_some_and(|entry| entry.dirty_kind.is_some())
        );

        let host_nif_call = native_call_module_for_test(
            runtime.atom_table.intern("host_nif_call"),
            runtime.atom_table.intern("answer"),
            runtime.atom_table.intern("host"),
            runtime.atom_table.intern("answer"),
            answer,
        );
        runtime.module_registry.insert(host_nif_call);
        let pid = runtime.spawn_workflow("host_nif_call", "answer", RuntimeInput::default())?;
        let (reason, result) = runtime.run_until_exit_for_test(pid);

        assert_eq!(reason, beamr::process::ExitReason::Normal);
        assert_eq!(result, Term::small_int(42));
        runtime.shutdown()?;
        Ok(())
    }
}