harn_vm/observability/execution_scope.rs
1//! Ambient EXECUTION SCOPE — an immutable owner token minted once per Harn
2//! program run and readable, like [`crate::observability::request_id`], from
3//! hostlib builtins on the synchronous dispatch stack.
4//!
5//! Unlike `request_id` (which a *host* pushes only at served ingress and which
6//! is `None` for standalone `harn run`/`harn test`), the execution scope is
7//! established by the VM itself at the top-level program boundary
8//! (`Vm::execute_scoped`), so it is ALWAYS present during real execution and is
9//! never a shared sentinel. That is exactly what lets the verdict issuance
10//! authority bind a proof-of-execution receipt to the specific run that
11//! PRODUCED the evidence: `run_test` captures the active scope when it records a
12//! real execution, and `harness.verdict.issue` mints a positive verdict only
13//! when the current active scope EQUALS that captured owner — so an old green
14//! handle cannot bless a later, different run (the cross-run replay class).
15//!
16//! The scope is a stack so nested program executions restore the outer owner on
17//! return; the innermost entry wins for [`current_execution_scope`]. When no
18//! scope is active (there is no owning execution), issuance FAILS CLOSED — it
19//! never falls back to a default owner.
20
21use std::cell::RefCell;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::sync::Arc;
24
25thread_local! {
26 static ACTIVE_EXECUTION_SCOPE_STACK: RefCell<Vec<Arc<str>>> = const { RefCell::new(Vec::new()) };
27}
28
29static SCOPE_COUNTER: AtomicU64 = AtomicU64::new(1);
30
31/// Mint a fresh, process-unique, immutable execution-scope id. The `pid`
32/// prefix keeps ids from colliding across processes that share the (in-process)
33/// result store's namespace; the monotonic counter keeps them distinct within
34/// one process. Callers push the returned id via [`enter_execution_scope`].
35pub fn mint_execution_scope() -> Arc<str> {
36 let n = SCOPE_COUNTER.fetch_add(1, Ordering::SeqCst);
37 Arc::from(format!("hxs-{:x}-{n}", std::process::id()).as_str())
38}
39
40/// RAII guard returned by [`enter_execution_scope`]. Popping the stack on drop
41/// keeps the ambient balanced even when the enclosed program run panics or
42/// returns an error.
43#[must_use = "dropping the guard immediately pops the execution scope"]
44pub struct ExecutionScopeGuard {
45 _private: (),
46}
47
48impl Drop for ExecutionScopeGuard {
49 fn drop(&mut self) {
50 ACTIVE_EXECUTION_SCOPE_STACK.with(|stack| {
51 stack.borrow_mut().pop();
52 });
53 }
54}
55
56/// Push `scope` onto the ambient stack for the lifetime of the returned guard.
57/// The innermost entry wins for [`current_execution_scope`].
58pub fn enter_execution_scope(scope: Arc<str>) -> ExecutionScopeGuard {
59 ACTIVE_EXECUTION_SCOPE_STACK.with(|stack| stack.borrow_mut().push(scope));
60 ExecutionScopeGuard { _private: () }
61}
62
63/// Currently-active execution scope, or `None` when no owning program run is
64/// active on this task. Verdict issuance treats `None` as fail-closed.
65pub fn current_execution_scope() -> Option<Arc<str>> {
66 ACTIVE_EXECUTION_SCOPE_STACK.with(|stack| stack.borrow().last().cloned())
67}
68
69/// Replace the whole ambient stack, returning the previous one. Used by the
70/// orchestration ambient-scope machinery to carry the owner across
71/// `spawn_local` fan-out boundaries (which plain thread-locals do not cross),
72/// mirroring how the current-session stack is propagated.
73pub(crate) fn swap_execution_scope_stack(replacement: Vec<Arc<str>>) -> Vec<Arc<str>> {
74 ACTIVE_EXECUTION_SCOPE_STACK
75 .with(|stack| std::mem::replace(&mut *stack.borrow_mut(), replacement))
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn current_returns_none_when_nothing_pushed() {
84 // A fresh thread has no owning execution.
85 std::thread::spawn(|| {
86 assert_eq!(current_execution_scope(), None);
87 })
88 .join()
89 .unwrap();
90 }
91
92 #[test]
93 fn guard_pops_on_drop_and_inner_shadows_outer() {
94 std::thread::spawn(|| {
95 let outer = mint_execution_scope();
96 let inner = mint_execution_scope();
97 assert_ne!(outer, inner);
98 let _o = enter_execution_scope(outer.clone());
99 assert_eq!(current_execution_scope().as_deref(), Some(&*outer));
100 {
101 let _i = enter_execution_scope(inner.clone());
102 assert_eq!(current_execution_scope().as_deref(), Some(&*inner));
103 }
104 assert_eq!(current_execution_scope().as_deref(), Some(&*outer));
105 })
106 .join()
107 .unwrap();
108 }
109}