aion/runtime/handle.rs
1//! `RuntimeHandle` spawn, register, cancel, and shutdown support.
2
3use std::sync::{Arc, Mutex};
4
5use aion_core::{ActivityError, Payload};
6use beamr::atom::AtomTable;
7use beamr::module::ModuleRegistry;
8use beamr::native::BifRegistryImpl;
9use beamr::process::ExitReason;
10use beamr::scheduler::{Scheduler, SchedulerConfig};
11use beamr::term::Term;
12
13use crate::error::EngineError;
14
15use super::config::{RuntimeConfig, SignalDeliveryConfig};
16#[cfg(test)]
17use super::nif::Mfa;
18use super::nif::NifRegistration;
19use super::payload::payload_to_term;
20
21use self::registration::{nif_registration_error, register_all_bifs};
22
23/// Local BEAM process identifier exposed by the runtime boundary.
24pub type Pid = u64;
25
26type RetainedHeap = Box<[u64]>;
27type RetainedHeaps = Vec<RetainedHeap>;
28type RetainedSpawnHeaps = Arc<dashmap::DashMap<Pid, Mutex<RetainedHeaps>>>;
29
30/// Runtime-owned workflow or activity input terms.
31///
32/// The wrapper keeps the beamr term representation inside the runtime module
33/// while later lifecycle and payload code decide how durable payloads become VM
34/// terms.
35#[derive(Debug, Default, Eq, PartialEq)]
36pub struct RuntimeInput {
37 terms: Vec<Term>,
38 heaps: RetainedHeaps,
39}
40
41impl RuntimeInput {
42 /// Convert one durable payload into the single BEAM argument used by
43 /// in-VM activity dispatch.
44 ///
45 /// The runtime boundary owns this representation. JSON payloads are passed
46 /// as BEAM binary terms and any boxed host heap backing those terms is
47 /// retained until the spawned process is observed exiting or cancelled.
48 ///
49 /// # Errors
50 ///
51 /// Returns [`EngineError::Runtime`] when a JSON number does not fit in an
52 /// immediate small integer.
53 pub fn from_payload(payload: &Payload) -> Result<Self, EngineError> {
54 let (term, heaps) = payload_to_term(payload)?.into_parts();
55 Ok(Self {
56 terms: vec![term],
57 heaps,
58 })
59 }
60
61 /// Number of terms supplied to the BEAM entrypoint.
62 #[must_use]
63 pub fn arity(&self) -> u8 {
64 u8::try_from(self.terms.len()).unwrap_or(u8::MAX)
65 }
66
67 fn into_spawn_parts(self) -> (Vec<Term>, RetainedHeaps) {
68 (self.terms, self.heaps)
69 }
70}
71
72/// Handle to the embedded beamr scheduler and code-server state.
73pub struct RuntimeHandle {
74 pub(super) scheduler: Arc<Scheduler>,
75 pub(super) atom_table: Arc<AtomTable>,
76 pub(super) module_registry: Arc<ModuleRegistry>,
77 pub(super) native_registry: Arc<BifRegistryImpl>,
78 nif_state: Arc<super::nif_state::EngineNifState>,
79 /// Engine-owned executor for background tasks that append to durable
80 /// history: child-terminal watchers, spawn recovery, and process-exit
81 /// completion retries.
82 ///
83 /// Owned here rather than by any bridge because a bridge is optional and
84 /// these tasks are not. Its shutdown aborts AND awaits, which is what stops
85 /// a task outliving the epoch and becoming a second writer against a
86 /// successor engine over the same store.
87 engine_tasks: Arc<super::engine_tasks::EngineTaskRuntime>,
88 activity_results: Arc<dashmap::DashMap<(Pid, Pid), Payload>>,
89 activity_errors: Arc<dashmap::DashMap<(Pid, Pid), ActivityError>>,
90 /// Per-workflow synchronization for retained activity delivery and death draining.
91 ///
92 /// Each workflow has an independent gate, so an exited process that remains
93 /// in beamr's process table cannot block unrelated workflows. A
94 /// dead gate remains until process-table removal is observed, preventing
95 /// delivery from inserting behind that workflow's death sweep.
96 activity_delivery_gates: dashmap::DashMap<Pid, Arc<activity_delivery::ActivityDeliveryGate>>,
97 /// One-based delivery attempt that produced a retained two-phase activity
98 /// outcome, keyed like [`Self::activity_results`] / [`Self::activity_errors`]
99 /// (#197). Retained in the same gate transaction as the final outcome and
100 /// taken atomically with that outcome, so recorded terminals carry the
101 /// genuine attempt. Absence means the first delivery (paths that never
102 /// retry — outbox re-delivery and in-VM execution — retain nothing).
103 activity_delivery_attempts: Arc<dashmap::DashMap<(Pid, Pid), u32>>,
104 #[cfg(test)]
105 activity_delivery_test_seams: activity_delivery::ActivityDeliveryTestSeams,
106 /// Live in-VM activity children per workflow pid.
107 ///
108 /// A BEAM link tears a child down when its workflow dies ABNORMALLY, but
109 /// a `Normal` exit never propagates through links (classic BEAM
110 /// semantics), so a workflow that completes while an in-VM runner is
111 /// still executing — e.g. after a `with_timeout` expiry abandoned the
112 /// await — would orphan the child and its completion waiter forever. The
113 /// workflow process monitor kills children still registered here when the
114 /// workflow exits (for any reason), and [`Self::shutdown`] kills every
115 /// remaining child so no waiter outlives the scheduler.
116 in_vm_children: Arc<dashmap::DashMap<Pid, std::collections::HashSet<Pid>>>,
117 registered_nif_modules: Arc<dashmap::DashSet<String>>,
118 spawn_heaps: RetainedSpawnHeaps,
119 signal_delivery: SignalDeliveryConfig,
120 stop_drain_timeout: std::time::Duration,
121 completion_retry: super::config::CompletionRetryConfig,
122 /// Flag gating the durable-outbox fan-out dispatch path; read by
123 /// `nif_collect.rs` to route fresh fan-out members and completions.
124 outbox_enabled: bool,
125 /// Bounded follow-up wakes for delivered mailbox markers, healing
126 /// beamr 0.4.9's lost-wakeup window (see [`super::wake_confirm`]).
127 pub(super) wake_confirmer: super::wake_confirm::WakeConfirmer,
128 /// Per-pid outcomes established before top-level process pids are published.
129 pub(super) process_exits: Arc<super::process_exit::ProcessExitRegistry>,
130 /// Runtime-provisioned owner for every process abort and shared cleanup.
131 pub(super) cleanup_executor: super::cleanup_executor::CleanupExecutor,
132 /// Identity-bearing abort jobs retained for deduplicated retries.
133 pub(super) abort_jobs: dashmap::DashMap<Pid, Arc<super::monitor::UnmonitoredProcessAbortJob>>,
134}
135
136impl RuntimeHandle {
137 /// Construct and start an embedded runtime from builder-supplied config.
138 ///
139 /// # Errors
140 ///
141 /// Returns [`EngineError::Runtime`] when beamr cannot start its scheduler.
142 /// Returns [`EngineError::Gate3BifReplacementMissing`] if beamr's complete
143 /// Gate-3 table no longer contains a required tracked fun-spawn BIF.
144 pub fn new(config: RuntimeConfig) -> Result<Self, EngineError> {
145 let atom_table = Arc::new(AtomTable::with_common_atoms());
146 let module_registry = Arc::new(ModuleRegistry::new());
147 // One NIF state per runtime instance, recovered by every native call
148 // through beamr's NIF private data — never process-wide globals.
149 let nif_state = Arc::new(super::nif_state::EngineNifState::default());
150 let scheduler_config = SchedulerConfig {
151 thread_count: config.thread_count,
152 // `None` here is beamr's own default threshold, not a value aion
153 // chose. See `RuntimeConfig::jit_threshold` for what a large value
154 // does and — importantly — what it does not do.
155 jit_threshold: config.jit_threshold,
156 nif_private_data: Some(Arc::clone(&nif_state) as _),
157 ..Default::default()
158 };
159 let native_registry = Arc::new(BifRegistryImpl::new());
160 register_all_bifs(&native_registry, &atom_table, &nif_state)?;
161 let scheduler = Arc::new(
162 Scheduler::with_code_server(
163 scheduler_config,
164 Arc::clone(&module_registry),
165 Arc::clone(&atom_table),
166 Arc::clone(&native_registry),
167 )
168 .map_err(runtime_error_from_display)?,
169 );
170 let wake_confirmer = super::wake_confirm::WakeConfirmer::new(config.signal_delivery)?;
171 // AE-017: the operator's no-progress bound, handed down by the builder.
172 // Zero is refused here as well as at the server's load path: a zero
173 // bound is not a short patience, it is no patience.
174 if config.stop_drain_timeout.is_zero() {
175 return Err(EngineError::ZeroStopDrainTimeout);
176 }
177 let shutdown_timeout = config.stop_drain_timeout;
178 let cleanup_executor = super::cleanup_executor::CleanupExecutor::new(
179 config.signal_delivery.max_enqueue_attempts as usize,
180 shutdown_timeout,
181 )?;
182 // Claim beamr's singleton stream before this scheduler can publish a pid
183 // through any RuntimeHandle spawn API.
184 let process_exits = super::process_exit::ProcessExitRegistry::new(
185 Arc::clone(&scheduler),
186 shutdown_timeout,
187 config.signal_delivery.max_enqueue_attempts as usize,
188 )?;
189 nif_state.set_process_exit_registry(&process_exits)?;
190
191 Ok(Self {
192 scheduler,
193 atom_table,
194 module_registry,
195 native_registry,
196 nif_state,
197 engine_tasks: Arc::new(super::engine_tasks::EngineTaskRuntime::new()?),
198 activity_results: Arc::new(dashmap::DashMap::new()),
199 activity_errors: Arc::new(dashmap::DashMap::new()),
200 activity_delivery_gates: dashmap::DashMap::new(),
201 activity_delivery_attempts: Arc::new(dashmap::DashMap::new()),
202 #[cfg(test)]
203 activity_delivery_test_seams: activity_delivery::ActivityDeliveryTestSeams::default(),
204 in_vm_children: Arc::new(dashmap::DashMap::new()),
205 registered_nif_modules: Arc::new(dashmap::DashSet::new()),
206 spawn_heaps: Arc::new(dashmap::DashMap::new()),
207 signal_delivery: config.signal_delivery,
208 stop_drain_timeout: config.stop_drain_timeout,
209 completion_retry: config.completion_retry,
210 outbox_enabled: config.outbox_enabled,
211 wake_confirmer,
212 process_exits,
213 cleanup_executor,
214 abort_jobs: dashmap::DashMap::new(),
215 })
216 }
217
218 /// This runtime instance's engine-scoped NIF state.
219 pub(crate) fn nif_state(&self) -> &Arc<super::nif_state::EngineNifState> {
220 &self.nif_state
221 }
222
223 /// Builder-supplied delivery/readiness policy for spawn-window waits.
224 /// The no-progress bound every stop path of this runtime waits under.
225 #[must_use]
226 pub fn stop_drain_timeout(&self) -> std::time::Duration {
227 self.stop_drain_timeout
228 }
229
230 pub(crate) fn signal_delivery(&self) -> SignalDeliveryConfig {
231 self.signal_delivery
232 }
233
234 /// Builder-supplied backoff ladder for durable completion retries.
235 ///
236 /// Deliberately not [`Self::signal_delivery`]: that policy bounds a
237 /// mailbox-enqueue wait measured in scheduler ticks, and a durable retry
238 /// against a failing store is a different question with a different answer.
239 pub(crate) fn completion_retry(&self) -> super::config::CompletionRetryConfig {
240 self.completion_retry
241 }
242
243 /// Whether the durable-outbox fan-out dispatch path is enabled.
244 ///
245 /// Read by `nif_collect.rs` to route fresh fan-out members through the
246 /// durable outbox and record completions via the dedup primitive.
247 pub(crate) fn outbox_enabled(&self) -> bool {
248 self.outbox_enabled
249 }
250
251 /// Install collected NIF entries into beamr's native registry.
252 ///
253 /// Consumes the registration collection so no caller can append more entries
254 /// after this installation step. Callers must invoke this before loading and
255 /// spawning workflow modules whose imports depend on these NIFs.
256 ///
257 /// # Errors
258 ///
259 /// Returns [`EngineError::NifRegistration`] when beamr rejects an entry,
260 /// including duplicate module/function/arity registrations.
261 pub fn install_nifs(&self, registration: NifRegistration) -> Result<(), EngineError> {
262 for entry in registration.into_entries() {
263 let mfa = entry.mfa;
264 let module = self.atom_table.intern(&mfa.module);
265 let function = self.atom_table.intern(&mfa.function);
266 let capability = beamr::native::Capability::ExternalIo;
267 let result = if entry.is_dirty {
268 self.native_registry.register_dirty(
269 module,
270 function,
271 mfa.arity,
272 entry.function,
273 beamr::scheduler::dirty::DirtySchedulerKind::Cpu,
274 capability,
275 )
276 } else {
277 self.native_registry.register(
278 module,
279 function,
280 mfa.arity,
281 entry.function,
282 capability,
283 )
284 };
285 result.map_err(|error| nif_registration_error(&mfa, error))?;
286 self.registered_nif_modules.insert(mfa.module);
287 }
288
289 Ok(())
290 }
291
292 /// Return module names that have registered NIFs and should not be
293 /// content-hash renamed during package loading.
294 #[must_use]
295 pub fn registered_nif_modules(&self) -> Vec<String> {
296 let mut module_names: Vec<_> = self
297 .registered_nif_modules
298 .iter()
299 .map(|module_name| module_name.key().clone())
300 .collect();
301 module_names.sort();
302 module_names
303 }
304
305 /// Spawn a top-level workflow process at a deployed module/function entrypoint.
306 ///
307 /// # Errors
308 ///
309 /// Returns [`EngineError::Runtime`] when the module/function/arity cannot be
310 /// resolved or beamr rejects the spawn request.
311 pub fn spawn_workflow(
312 &self,
313 deployed_module: &str,
314 function: &str,
315 input: RuntimeInput,
316 ) -> Result<Pid, EngineError> {
317 self.spawn_process(deployed_module, function, input)
318 }
319
320 /// Spawn a top-level workflow process with trap-exit enabled before it runs.
321 ///
322 /// # Errors
323 ///
324 /// Returns [`EngineError::Runtime`] when the module/function/arity cannot be
325 /// resolved or beamr rejects the spawn request.
326 pub fn spawn_workflow_trapping(
327 &self,
328 deployed_module: &str,
329 function: &str,
330 input: RuntimeInput,
331 ) -> Result<Pid, EngineError> {
332 self.release_dead_spawn_heaps();
333 let module = self.atom_table.intern(deployed_module);
334 let function = self.atom_table.intern(function);
335 let (terms, heaps) = input.into_spawn_parts();
336 let pid = self.spawn_with_exit_ownership(|| {
337 self.scheduler
338 .spawn_trap_exit(module, function, terms)
339 .map_err(runtime_error_from_display)
340 })?;
341 self.retain_spawn_heaps(pid, heaps);
342 Ok(pid)
343 }
344
345 /// Spawn an activity child process linked to its workflow parent.
346 ///
347 /// # Errors
348 ///
349 /// Returns [`EngineError::Runtime`] when the parent process is not live, the
350 /// module/function/arity cannot be resolved, or beamr rejects the linked
351 /// spawn request.
352 pub fn spawn_activity(
353 &self,
354 parent_pid: Pid,
355 deployed_module: &str,
356 function: &str,
357 input: RuntimeInput,
358 ) -> Result<Pid, EngineError> {
359 self.release_dead_spawn_heaps();
360 self.ensure_live_pid(parent_pid)?;
361 self.wait_for_process_ready(parent_pid)?;
362 let module = self.atom_table.intern(deployed_module);
363 let function_atom = self.atom_table.intern(function);
364 let (terms, heaps) = input.into_spawn_parts();
365 let pid = self.spawn_with_exit_ownership(|| {
366 self.scheduler
367 .spawn_link(parent_pid, module, function_atom, terms)
368 .map_err(runtime_error_from_display)
369 })?;
370 self.retain_spawn_heaps(pid, heaps);
371 Ok(pid)
372 }
373
374 /// Spawn an in-VM activity child process linked to its workflow parent,
375 /// running a zero-arity closure (the SDK-composed runner thunk).
376 ///
377 /// beamr deep-copies the closure's environment into the child's own heap
378 /// before the child becomes runnable (`Scheduler::spawn_link_closure`), so
379 /// no spawn heap is retained here and the caller's heap may move (GC) the
380 /// moment this returns. The child does not trap exits: workflow
381 /// cancellation propagates through the link, and an abnormal child exit is
382 /// observed by the in-VM completion watcher via [`Self::in_vm_child_outcome`].
383 ///
384 /// No parent readiness wait is performed: the only production caller is
385 /// the dispatch NIF executing ON the parent process, which is therefore
386 /// already materialized (a readiness poll on an `Executing` slot would be
387 /// pointless at best).
388 ///
389 /// # Errors
390 ///
391 /// Returns [`EngineError::Runtime`] when the parent is not live, the term
392 /// is not a zero-arity closure, or its module cannot be resolved.
393 pub fn spawn_activity_closure(
394 &self,
395 parent_pid: Pid,
396 closure_term: Term,
397 ) -> Result<Pid, EngineError> {
398 self.release_dead_spawn_heaps();
399 self.ensure_live_pid(parent_pid)?;
400 let pid = self.spawn_with_exit_ownership(|| {
401 self.scheduler
402 .spawn_link_closure(parent_pid, closure_term)
403 .map_err(runtime_error_from_display)
404 })?;
405 self.in_vm_children
406 .entry(parent_pid)
407 .or_default()
408 .insert(pid);
409 // Close the external-kill registration race: if the workflow died
410 // between the liveness check above and this registration, the
411 // monitor's `kill_in_vm_children` sweep may already have run (and
412 // beamr's link may never have been established — a caller that died
413 // mid-spawn yields an UNLINKED child), which would leave a hanging
414 // runner alive until engine shutdown. Re-checking AFTER registration
415 // makes both orderings safe: a parent death after this point observes
416 // the registration and is swept by the monitor; a death before it is
417 // torn down here (both kill paths are idempotent — the sweep guards
418 // with `is_live`).
419 if !self.is_live(parent_pid) {
420 self.kill_in_vm_children(parent_pid);
421 return Err(EngineError::Runtime {
422 reason: format!(
423 "in-vm activity child spawn: parent workflow process {parent_pid} exited during spawn"
424 ),
425 });
426 }
427 Ok(pid)
428 }
429
430 /// Drop a finished in-VM child from its workflow's teardown set (called
431 /// by the completion waiter once the child's cached outcome is decoded).
432 pub(crate) fn deregister_in_vm_child(&self, parent_pid: Pid, child_pid: Pid) {
433 if let Some(mut children) = self.in_vm_children.get_mut(&parent_pid) {
434 children.remove(&child_pid);
435 }
436 self.in_vm_children
437 .remove_if(&parent_pid, |_, children| children.is_empty());
438 }
439
440 /// Kill every in-VM activity child still registered for `workflow_pid`.
441 ///
442 /// Invoked by the workflow process monitor on workflow exit: a `Normal`
443 /// exit does not propagate through BEAM links, so a completed workflow
444 /// would otherwise orphan a still-running runner and its completion waiter.
445 /// Killing publishes the child's durable outcome, which wakes that waiter;
446 /// delivery to the dead workflow is refused and nothing is retained.
447 pub(crate) fn kill_in_vm_children(&self, workflow_pid: Pid) {
448 let Some((_, children)) = self.in_vm_children.remove(&workflow_pid) else {
449 return;
450 };
451 for child_pid in children {
452 if self.is_live(child_pid) {
453 tracing::debug!(
454 workflow_pid,
455 child_pid,
456 "killing orphaned in-vm activity child on workflow exit"
457 );
458 self.scheduler
459 .terminate_process(child_pid, ExitReason::Kill);
460 }
461 self.release_spawn_heaps(child_pid);
462 }
463 }
464
465 /// Return whether the registered native activity entry is dirty for arity 1.
466 #[must_use]
467 pub fn is_dirty(&self, module: &str, function: &str) -> bool {
468 self.is_dirty_with_arity(module, function, 1)
469 }
470
471 /// Return whether the registered native entry is dirty for the supplied arity.
472 #[must_use]
473 pub fn is_dirty_with_arity(&self, module: &str, function: &str, arity: u8) -> bool {
474 let module = self.atom_table.intern(module);
475 let function = self.atom_table.intern(function);
476 self.native_registry
477 .lookup(module, function, arity)
478 .is_some_and(|entry| entry.dirty_kind.is_some())
479 }
480
481 /// Cancel a live process by PID.
482 ///
483 /// # Errors
484 ///
485 /// Returns [`EngineError::Runtime`] when `pid` is not live.
486 pub fn cancel_pid(&self, pid: Pid) -> Result<(), EngineError> {
487 self.ensure_live_pid(pid)?;
488 self.scheduler.terminate_process(pid, ExitReason::Kill);
489 self.release_spawn_heaps(pid);
490 Ok(())
491 }
492
493 /// Set a live process' trap-exit flag, returning the previous value.
494 ///
495 /// # Errors
496 ///
497 /// Returns [`EngineError::Runtime`] when `pid` is not live.
498 pub fn set_trap_exit(&self, pid: Pid, value: bool) -> Result<bool, EngineError> {
499 self.scheduler
500 .set_trap_exit(pid, value)
501 .map_err(runtime_error_from_display)
502 }
503
504 /// Return true when `pid` is currently live.
505 ///
506 /// This reports scheduler process-table residency, not whether Aion's
507 /// exit cleanup has started; the crate-internal `process_cleanup_started`
508 /// reports that.
509 #[must_use]
510 pub fn is_live(&self, pid: Pid) -> bool {
511 self.scheduler.process_table().get(pid).is_some()
512 }
513
514 /// Return a live process' trap-exit flag.
515 ///
516 /// # Errors
517 ///
518 /// Returns [`EngineError::Runtime`] when `pid` is not live.
519 pub fn trap_exit(&self, pid: Pid) -> Result<bool, EngineError> {
520 self.scheduler
521 .trap_exit(pid)
522 .ok_or_else(|| runtime_error(format!("process {pid} is not live")))
523 }
524
525 /// Return true when two live processes have a bidirectional link.
526 ///
527 /// # Errors
528 ///
529 /// Returns [`EngineError::Runtime`] when either process is not live.
530 pub fn is_linked(&self, left: Pid, right: Pid) -> Result<bool, EngineError> {
531 self.ensure_live_pid(left)?;
532 self.ensure_live_pid(right)?;
533 Ok(self.scheduler.is_linked(left, right))
534 }
535
536 /// The engine-owned executor for durable background tasks.
537 ///
538 /// Every caller shares this one instance: the child bridge, spawn recovery
539 /// and the process-exit completion retry. A second executor with the same
540 /// epoch-close discipline would be the same rule in two places.
541 pub(crate) fn engine_tasks(&self) -> Arc<super::engine_tasks::EngineTaskRuntime> {
542 Arc::clone(&self.engine_tasks)
543 }
544
545 /// Arm the injected process-exit drain failure, so a test can make
546 /// [`Self::shutdown`] fail deterministically.
547 ///
548 /// Exists because none of the drain failures can be produced on demand,
549 /// which is how the "every teardown step still runs" property stayed
550 /// unpinned.
551 ///
552 /// 🔴 THE SET IS OPEN, AND TWO EARLIER REVISIONS OF THIS COMMENT CLAIMED
553 /// OTHERWISE. The first said they are all timeout-shaped. The second
554 /// replaced that with an eleven-variant enumeration — three timeout-shaped,
555 /// five poison-shaped, three panic-shaped — and asserted "what they share is
556 /// a precondition: each needs a stalled, poisoned or dead worker thread".
557 /// **Both are false, and the second is the more dangerous because it looks
558 /// exhaustive.**
559 ///
560 /// `close_and_join_all` ends with
561 /// `handle.join().map_err(|_| ProcessExitDrainerPanicked)??` — and the
562 /// SECOND `?` propagates the drainer thread's own `Result<(), EngineError>`
563 /// verbatim (`runtime/process_exit.rs`). Whatever that thread can return
564 /// reaches this function's caller. That includes at least
565 /// `ProcessExitEventStreamDisconnected` (`runtime/process_exit_drainer.rs`
566 /// — beamr disconnected its publisher) and
567 /// `ProcessExitOutcomeMissingAfterEvent` (a beamr contract breach surfaced
568 /// through `registry.process_event`). Neither is timeout-, poison- or
569 /// panic-shaped, and neither needs a worker thread of ours to be stalled,
570 /// poisoned or dead.
571 ///
572 /// So: **do not enumerate this set, and do not reason from a shared shape or
573 /// a shared precondition.** The property that actually holds, and the only
574 /// one this seam needs, is that none of them can be arranged by a test
575 /// through this type's public surface. `process_exits` stays private; this
576 /// is the one named seam, and it is `#[cfg(test)]` so it cannot reach a
577 /// shipped binary.
578 ///
579 /// The injected variant is `ProcessExitRegistryPoisoned` because that is
580 /// what the injection point (`begin_shutdown` → `lock_lifecycle`) can
581 /// actually raise. A fault wearing a label its own injection site cannot
582 /// issue is a fixture modelling a machine that does not exist.
583 ///
584 /// Crate-visible rather than module-visible because the property it exists
585 /// to measure lives at [`crate::Engine::shutdown`], one module over — a seam
586 /// only reachable from its own module cannot test the caller that wraps it.
587 #[cfg(test)]
588 pub(crate) fn force_process_exit_drain_failure(&self) {
589 self.process_exits.force_shutdown_failure();
590 }
591
592 /// Shut down the embedded scheduler and wait for worker threads to stop.
593 ///
594 /// # Errors
595 ///
596 /// Returns the **first** typed failure raised by the process-exit drain
597 /// (`begin_shutdown`, `close_and_join_all`) or the cleanup-executor drain.
598 /// Those failures are an OPEN set — see
599 /// [`Self::force_process_exit_drain_failure`] for why they cannot be
600 /// enumerated — and the shape does not matter here, because none of them
601 /// short-circuits this function: the error is carried to the end and
602 /// returned only after the
603 /// engine-task epoch has been closed and the scheduler stopped. See the
604 /// comment on `first_error` in the body for why that ordering is a
605 /// correctness requirement rather than a tidiness preference.
606 pub fn shutdown(&self) -> Result<(), EngineError> {
607 // Kill every still-live in-VM activity child before stopping the
608 // scheduler so the singleton drainer can capture each durable outcome.
609 let workflow_pids: Vec<Pid> = self
610 .in_vm_children
611 .iter()
612 .map(|entry| *entry.key())
613 .collect();
614 for workflow_pid in workflow_pids {
615 self.kill_in_vm_children(workflow_pid);
616 }
617 // 🔴 Every fallible drain below RECORDS its failure instead of
618 // returning it, so that the epoch close at the end of this function is
619 // reached on every path.
620 //
621 // The epoch close aborts and awaits tasks that append terminal events.
622 // A drain timeout is not an unrelated inconvenience — it is precisely
623 // the condition under which those tasks are still armed, because one
624 // degraded store both stalls the drain and is what the completion
625 // retries are waiting on. If a `?` here returned early, the retries
626 // would keep running; the operator, seeing a shutdown error, restarts;
627 // and the successor engine recovers the same histories while this
628 // process is still appending to them — two writers for one workflow,
629 // which is the invariant-3 violation this whole mechanism exists to
630 // prevent.
631 //
632 // Nothing downstream would catch it on THIS path either. `Drop for
633 // Engine` exists, and what it does is enumerated in exactly one place —
634 // its own doc comment, which is the authority; this comment deliberately
635 // does not repeat the list, because it has already been stale once (it
636 // named two of the three things that drop does, and was written when
637 // there were two). What matters here is the shared PROPERTY of every
638 // item on that list: none of them await, and none of them run at all
639 // while the caller still holds the engine to read this function's `Err`.
640 //
641 // `EngineTaskRuntime::drop` is no help under the
642 // same conditions: an attempt in flight holds its own strong handle, so
643 // that backstop is pinned shut for exactly the span of the append it
644 // would need to stop. Closing the epoch here is the only mechanism that
645 // is guaranteed to run, which is why it does not sit behind a `?`.
646 let mut first_error: Option<EngineError> = None;
647
648 match self.process_exits.begin_shutdown() {
649 Ok(pids) => {
650 for pid in pids {
651 if self.is_live(pid) {
652 self.scheduler.terminate_process(pid, ExitReason::Kill);
653 }
654 }
655 }
656 Err(error) => first_error = Some(error),
657 }
658 // 🔴 EVERY FAILURE IS REPORTED, EVEN THOUGH ONLY ONE CAN BE RETURNED.
659 // Three steps below can each fail independently and the signature can
660 // carry one `EngineError`, so a later failure that is not the first
661 // would otherwise vanish with no trace at all — a swallowed `Result` in
662 // the teardown path of a durable engine, which this codebase forbids
663 // outright. `keep_shutdown_error` returns the first and emits every
664 // subsequent one at `error` level with the step that produced it.
665 // Abort jobs may be blocked waiting for exactly the exits published
666 // above, so drain the bounded executor only after every registered pid
667 // has been force-unblocked.
668 keep_shutdown_error(
669 &mut first_error,
670 "cleanup_executor.shutdown",
671 self.cleanup_executor.shutdown(),
672 );
673 // Pending wake follow-ups are moot once process observation is closed.
674 self.wake_confirmer.shutdown();
675 keep_shutdown_error(
676 &mut first_error,
677 "process_exits.close_and_join_all",
678 self.process_exits.close_and_join_all(),
679 );
680 // Close the engine-task epoch here, after every process-exit callback
681 // has been drained (so an exit observed during teardown still gets its
682 // one attempt) and before the scheduler goes away.
683 //
684 // This must be on THIS path, not only on the child bridge's. The
685 // executor is owned here precisely because completion retries append
686 // terminal events on a core lifecycle path, and a core path's epoch
687 // close must not depend on whether an optional bridge was installed:
688 // a retry still running after this returns could append against a
689 // store a successor engine is also recovering (invariant 3).
690 //
691 // A second `shutdown` call is a no-op: it re-gates and re-sweeps the
692 // three already-empty maps `gate_and_abort` covers (`watches`,
693 // `spawn_retries`, `completion_retries`), finds the runtime slot empty,
694 // and returns without awaiting anything. That makes the bridge's own
695 // later call harmless
696 // because the two are strictly sequential (`Engine::shutdown` runs this
697 // one, then the bridge's). It does NOT mean "returning implies
698 // quiescence" for a hypothetical concurrent second caller — only the
699 // first call awaits.
700 self.engine_tasks.shutdown();
701 self.scheduler.shutdown();
702 self.spawn_heaps.clear();
703
704 match first_error {
705 Some(error) => Err(error),
706 None => Ok(()),
707 }
708 }
709
710 fn spawn_process(
711 &self,
712 deployed_module: &str,
713 function: &str,
714 input: RuntimeInput,
715 ) -> Result<Pid, EngineError> {
716 self.release_dead_spawn_heaps();
717 let module = self.atom_table.intern(deployed_module);
718 let function = self.atom_table.intern(function);
719 let (terms, heaps) = input.into_spawn_parts();
720 let pid = self.spawn_with_exit_ownership(|| {
721 self.scheduler
722 .spawn(module, function, terms)
723 .map_err(runtime_error_from_display)
724 })?;
725 self.retain_spawn_heaps(pid, heaps);
726 Ok(pid)
727 }
728
729 fn retain_spawn_heaps(&self, pid: Pid, heaps: RetainedHeaps) {
730 if heaps.is_empty() {
731 return;
732 }
733 self.spawn_heaps.insert(pid, Mutex::new(heaps));
734 }
735
736 pub(super) fn release_spawn_heaps(&self, pid: Pid) {
737 self.spawn_heaps.remove(&pid);
738 }
739
740 fn release_dead_spawn_heaps(&self) {
741 let dead_pids: Vec<Pid> = self
742 .spawn_heaps
743 .iter()
744 .filter_map(|entry| {
745 let pid = *entry.key();
746 self.scheduler
747 .process_table()
748 .get(pid)
749 .is_none()
750 .then_some(pid)
751 })
752 .collect();
753 for pid in dead_pids {
754 self.release_spawn_heaps(pid);
755 }
756 }
757
758 pub(super) fn ensure_live_pid(&self, pid: Pid) -> Result<(), EngineError> {
759 if self.scheduler.process_table().get(pid).is_some() {
760 Ok(())
761 } else {
762 Err(runtime_error(format!("process {pid} is not live")))
763 }
764 }
765
766 #[cfg(test)]
767 pub(crate) fn live_processes_for_test(&self) -> usize {
768 self.scheduler.process_table().len()
769 }
770
771 /// Spawn an inert test process without module code.
772 ///
773 /// # Errors
774 ///
775 /// Returns [`EngineError::Runtime`] when beamr rejects the test spawn.
776 #[cfg(test)]
777 pub fn spawn_test_process(&self) -> Result<Pid, EngineError> {
778 self.spawn_with_exit_ownership(|| Ok(self.scheduler.spawn_test_process(false)))
779 }
780
781 /// Spawn an inert test process with explicit trap-exit state.
782 ///
783 /// # Errors
784 ///
785 /// Returns [`EngineError::Runtime`] when beamr rejects the test spawn.
786 #[cfg(test)]
787 pub fn spawn_test_process_with_trap_exit(&self, trap_exit: bool) -> Result<Pid, EngineError> {
788 self.spawn_with_exit_ownership(|| Ok(self.scheduler.spawn_test_process(trap_exit)))
789 }
790
791 /// Spawn an inert linked test child without enabling trap-exit on the child.
792 ///
793 /// # Errors
794 ///
795 /// Returns [`EngineError::Runtime`] when the parent is not live or beamr
796 /// rejects the linked spawn.
797 #[cfg(test)]
798 pub fn spawn_linked_test_process(&self, parent_pid: Pid) -> Result<Pid, EngineError> {
799 self.ensure_live_pid(parent_pid)?;
800 self.spawn_with_exit_ownership(|| {
801 self.scheduler
802 .spawn_linked_test_process(parent_pid)
803 .map_err(runtime_error_from_display)
804 })
805 }
806
807 /// Return true when a live process has a trapped EXIT message from `source_pid`.
808 ///
809 /// # Errors
810 ///
811 /// Returns [`EngineError::Runtime`] when `target_pid` is not live.
812 #[cfg(test)]
813 pub fn has_trapped_exit_message(
814 &self,
815 target_pid: Pid,
816 source_pid: Pid,
817 ) -> Result<bool, EngineError> {
818 self.ensure_live_pid(target_pid)?;
819 Ok(self
820 .scheduler
821 .has_trapped_exit_message(target_pid, source_pid)
822 .unwrap_or(false))
823 }
824
825 /// Poll until a trapped EXIT message from `source_pid` arrives at `target_pid`.
826 ///
827 /// beamr delivers exit signals asynchronously after process termination.
828 /// Tests that assert on trapped exit messages must wait for delivery.
829 ///
830 /// # Errors
831 ///
832 /// Returns [`EngineError::Runtime`] if the message does not arrive within 50ms.
833 #[cfg(test)]
834 pub fn wait_for_trapped_exit(
835 &self,
836 target_pid: Pid,
837 source_pid: Pid,
838 ) -> Result<(), EngineError> {
839 let deadline = std::time::Instant::now() + std::time::Duration::from_millis(50);
840 while std::time::Instant::now() < deadline {
841 if self
842 .scheduler
843 .has_trapped_exit_message(target_pid, source_pid)
844 .unwrap_or(false)
845 {
846 return Ok(());
847 }
848 std::thread::sleep(std::time::Duration::from_millis(1));
849 }
850 Err(runtime_error(format!(
851 "trapped exit from {source_pid} to {target_pid} did not arrive"
852 )))
853 }
854
855 /// Terminate a test process with a trappable abnormal reason.
856 ///
857 /// # Errors
858 ///
859 /// Returns [`EngineError::Runtime`] when `pid` is not live.
860 #[cfg(test)]
861 pub fn terminate_test_process_with_error(&self, pid: Pid) -> Result<(), EngineError> {
862 self.ensure_live_pid(pid)?;
863 self.scheduler.terminate_process(pid, ExitReason::Error);
864 Ok(())
865 }
866
867 #[cfg(test)]
868 pub(crate) fn lookup_native_for_test(
869 &self,
870 module: &str,
871 function: &str,
872 arity: u8,
873 ) -> Option<beamr::native::NativeEntry> {
874 let module = self.atom_table.intern(module);
875 let function = self.atom_table.intern(function);
876 self.native_registry.lookup(module, function, arity)
877 }
878
879 #[cfg(test)]
880 pub(crate) fn retained_spawn_heap_count_for_test(&self) -> usize {
881 self.release_dead_spawn_heaps();
882 self.spawn_heaps.len()
883 }
884}
885
886/// Keep the FIRST teardown failure for the caller, and report every subsequent
887/// one rather than dropping it.
888///
889/// Teardown accumulates instead of failing fast — every step must run, because
890/// a skipped one leaves a durable writer armed. The cost of that choice is that
891/// more than one step can fail while only one `EngineError` can be returned.
892/// Reporting the others here is what keeps "accumulate and continue" from
893/// becoming "swallow and continue": the return value carries the first, the log
894/// carries the rest, and no failure is lost.
895fn keep_shutdown_error(
896 first_error: &mut Option<EngineError>,
897 step: &'static str,
898 result: Result<(), EngineError>,
899) {
900 let Err(error) = result else {
901 return;
902 };
903 if first_error.is_none() {
904 *first_error = Some(error);
905 return;
906 }
907 tracing::error!(
908 step,
909 error = %error,
910 "a further runtime-shutdown step failed after an earlier one; only the first failure \
911 can be returned, so this one is reported here"
912 );
913}
914
915fn runtime_error(reason: String) -> EngineError {
916 EngineError::Runtime { reason }
917}
918
919fn runtime_error_from_display(reason: impl std::fmt::Display) -> EngineError {
920 runtime_error(reason.to_string())
921}
922
923mod activity_delivery;
924mod delivery;
925mod process_ownership;
926mod readiness;
927mod registration;
928mod spawn_bifs;
929
930pub(crate) use delivery::InVmChildOutcome;
931
932#[cfg(test)]
933#[path = "handle/test_support.rs"]
934mod test_support;
935
936#[cfg(test)]
937#[path = "handle/tests.rs"]
938mod tests;