Skip to main content

oxdock_core/exec/
state.rs

1use std::collections::{HashMap, HashSet};
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Condvar, Mutex};
5
6use anyhow::Result;
7use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs, WorkspaceSelection};
8use oxdock_parser::{Field, Step, TypeDescriptor, TypeTag, Value};
9use oxdock_process::{BackgroundHandle, CancelHub, CommandContext, ProcessManager};
10
11use super::exit::exit_code_of;
12use super::io::{ExactCapture, ExecIo, SlidingWindow, TeeStream};
13use super::native::FunctionRegistry;
14use oxdock_pipe::KeeperGuard;
15
16/// Maximum nested function-call depth. Guards the host thread stack against
17/// runaway recursion; the error names the function that overflowed.
18pub(super) const MAX_CALL_DEPTH: usize = 64;
19
20/// Retained finished-task cap. Bounds `named_tasks` tombstones plus
21/// their tail buffers in long-lived sessions: spawning past the cap
22/// evicts the oldest finished entry. Running entries are never evicted.
23pub(super) const MAX_RETAINED_FINISHED: usize = 128;
24
25/// Live-task concurrency cap. Enforced globally through the shared
26/// counter below: any ASYNC spawn, in any nested worker, sees the
27/// same count. Refusal is backpressure, not silent kills and not an
28/// unbounded queue.
29pub const MAX_RUNNING_TASKS: usize = 64;
30
31/// RAII slot for the global live-task count. Created first inside
32/// every ASYNC worker thread; dropping on return or unwind releases
33/// the slot. The count therefore tracks threads actually alive, never
34/// table entries, so un-awaited finished tasks cannot squat slots and
35/// nested workers cannot bypass the cap.
36pub(super) struct TaskSlotGuard {
37    counter: Arc<AtomicU64>,
38}
39
40impl TaskSlotGuard {
41    pub(super) fn new(counter: Arc<AtomicU64>) -> Self {
42        Self { counter }
43    }
44}
45
46impl Drop for TaskSlotGuard {
47    fn drop(&mut self) {
48        self.counter.fetch_sub(1, Ordering::SeqCst);
49    }
50}
51
52/// Per-stream live tail cap for background tasks. Matches the
53/// foreground capture scale: the same never-grows guarantee.
54const TASK_TAIL_CAP: usize = 64 * 1024;
55
56/// Execution state for one script run. Public so hosts can register
57/// functions and introspect listings; all fields stay crate-private so the
58/// scope, recursion-budget, and task invariants cannot be broken from outside.
59pub struct ExecState<P: ProcessManager> {
60    pub(super) fs: Box<dyn WorkspaceFs>,
61    /// Pre-reserved guarded scratch dir (session temp for child
62    /// writes). Opaque [`CargoScratch`]: renderable for the child
63    /// environment but not nameable as a `&GuardedPath`, so host code
64    /// cannot `ensure()` or `create_dir_all` it. The child `cargo` creates it on demand.
65    pub(super) cargo_scratch: CargoScratch,
66    /// Pure session seed from [`oxdock_process::seed_defaults`], stored at
67    /// init alongside the layered `envs`. `ISOLATED` resets clone this
68    /// (not the layered map), and transport sanitize diffs against it.
69    /// Built once: re-seeding would re-read host fallbacks and break
70    /// state stability.
71    pub(super) seed: Arc<HashMap<String, String>>,
72    pub(super) cwd: GuardedPath,
73    pub(super) envs: Arc<HashMap<String, String>>,
74    /// Each entry is the script env as it stood at that block's entry, so
75    /// the block allowlist resolves against the enclosing scope even as
76    /// the live envs are scrubbed underneath. Nesting snapshots the
77    /// already-scrubbed parent, so narrowing is monotonic by
78    /// construction. Cloned (not reset) by `fork()` so tasks spawned
79    /// inside a block inherit its scrub.
80    pub(super) isolated_stack: Vec<Arc<HashMap<String, String>>>,
81    pub(super) bg_children: Vec<BgChild>,
82    pub(super) scope_stack: Vec<ScopeSnapshot>,
83    pub(super) io: ExecIo,
84    /// Pre-registered SlidingWindow observers for stream assertion steps.
85    /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
86    pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
87    /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
88    pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
89    /// Exact-match stdout accumulators for `ASSERT_EQ`/`ASSERT_NE stdout`, keyed by
90    /// generation and fed by the same tee. Entries allocated during
91    /// pre-registration observe bytes from scope entry; the common
92    /// top-level case therefore sees trial-cumulative output.
93    pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
94    /// Variable scopes for $variable bindings (FOR loops, LET assignments).
95    /// Innermost scope is last. Variables are looked up from innermost to outermost.
96    /// Each entry carries its declared type name alongside the value.
97    pub(super) var_scopes: Vec<HashMap<String, (TypeTag, Value)>>,
98    /// Name directory for type resolution: startup descriptors plus the
99    /// run's host descriptors. Words carry their own vtables, so this map
100    /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
101    pub(super) types: HashMap<String, &'static TypeDescriptor>,
102    /// Named record schemas for shaped MAP bindings: schema name to its
103    /// field table. Populated from host modules alongside descriptors, so
104    /// `LET $s: SSH_SESSION_INFO` resolves exactly when the owning module
105    /// is registered. Impossible to reference an unregistered schema.
106    pub(super) record_schemas: HashMap<String, Arc<[Field]>>,
107    /// Module-shared state stashed at registration, keyed by owning
108    /// module name plus value type. Bodies fetch it through
109    /// `StepCtx::module_state` instead of hand-built closures, so
110    /// every entry can stay `#[oxdock_func]`.
111    pub(super) module_states:
112        HashMap<(String, std::any::TypeId), Arc<dyn std::any::Any + Send + Sync>>,
113    /// Script-level type aliases for this run: alias name to canonical
114    /// target spelling (`PERSON` to `MAP<name:STRING>`). Populated once
115    /// from top-level `TYPE` steps before the static pass, so forward
116    /// references resolve run-wide at first coercion.
117    pub(super) type_aliases: HashMap<String, String>,
118    /// Cancellation token for background thread teardown.
119    #[allow(dead_code)]
120    pub(super) cancel_token: Arc<AtomicBool>,
121    /// Event hub fanning the same cancellation to pump supervisors.
122    /// Marked everywhere the token is stored, so blocking pumps wake
123    /// without polling. Forks get a fresh hub with their fresh token.
124    #[allow(dead_code)]
125    pub(super) cancel_hub: Arc<CancelHub>,
126    /// Handle to the currently executing foreground OS process, so
127    /// ThreadJoinHandle::kill() can interrupt a blocking wait().
128    #[allow(dead_code)]
129    pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
130    /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
131    /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
132    /// the handle lives inside the entry so `CANCEL` can synchronously tear
133    /// down a task even while a concurrent `AWAIT` is waiting on it.
134    /// Entries are retained as `Cancelled`/`Completed` tombstones so later
135    /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
136    #[allow(dead_code)]
137    pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
138    /// Counter for generating unique task IDs. Shared across subscopes via Arc.
139    #[allow(dead_code)]
140    pub(super) next_task_id: Arc<AtomicU64>,
141    /// Shared live-task count across every forked worker. Forks clone
142    /// the `Arc`, so nested spawns see the same total: the cap is
143    /// global, not per scope. Incremented atomically at allocation,
144    /// released by the worker thread's slot guard on exit.
145    pub(super) live_tasks: Arc<AtomicU64>,
146    /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
147    /// spawns in background mode so the handle can be registered for cancellation.
148    pub(super) inside_async: bool,
149    /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
150    /// pipe the worker produces to, bridging the spawn-to-first-attach
151    /// window and every transient gap between producer steps. Guards keyed
152    /// to step `k` drop when the worker completes its top-level step `k`
153    /// (matched by slice identity, so nested bodies never discharge them);
154    /// leftovers drop with the worker thread. Always `None` outside
155    /// workers; `fork` never inherits it.
156    pub(super) keeper_expiry: Option<KeeperExpiry>,
157    /// Whether `handlers::run()` must spawn in background mode so the handle
158    /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
159    /// body executes on the current thread so the deadline watcher can kill
160    /// a blocking foreground process. Unlike `inside_async`, this does not
161    /// affect end-of-pipeline named-task reaping.
162    pub(super) cancellable: bool,
163    /// Scope floor for the end-of-body reaper: task ids at or above this
164    /// joined at scope end, older ones ignored. Set only by `TIMEOUT`
165    /// (snapshot of the task-id counter at scope entry), so a worker the
166    /// body leaves running gets up to the deadline while pre-existing
167    /// tasks keep running past the scope. `None` joins everything: the
168    /// pipeline top and every other scope.
169    pub(super) reap_floor: Option<u64>,
170    /// The single function registry: DSL `FUNC` definitions, builtins, and
171    /// host extensions. Script entries scope lexically through the
172    /// registry's own frames (managed by `push_scope`/`pop_scope`);
173    /// native entries persist. Shared across `fork()` via clone.
174    pub(super) functions: FunctionRegistry<P>,
175    /// Entry script file (#115), when the run started from a file: base
176    /// for top-level relative `IMPORT` paths. `None` for stdin and inline
177    /// runs (imports resolve against the workspace root).
178    pub(super) entry_file: Option<GuardedPath>,
179    /// Active file-import chain (#115), innermost last: cycle detection
180    /// names the full chain, and the importer dir is the top's parent.
181    pub(super) import_stack: Vec<GuardedPath>,
182    /// Registry frame where file-import aliases register (#115): the
183    /// outermost import's caller frame. Nested imports share it so the
184    /// importer's `ALIAS::` bodies keep resolving nested aliases after
185    /// the nested frame pops. `None` outside an import.
186    pub(super) import_alias_frame: Option<usize>,
187    /// One file module per resolved import path (#115): parse once,
188    /// validate once, initialize once. Every alias is a view onto the
189    /// same record and the same shared state.
190    pub(super) modules: HashMap<String, ModuleRecord>,
191    pub(super) validated_modules: HashSet<String>,
192    /// Files the static closure pass already proved (#115): entry plus
193    /// every transitively imported file, checked with full nested
194    /// knowledge. Runtime re-validation of the same registry-cached
195    /// body would only false-positive on nested calls, so imports skip
196    /// the single-file re-proof when their key is present. Unseen
197    /// files (direct API use, no static pass) still validate here.
198    /// Active module context (#115), innermost last: `Some(key)` while
199    /// module-owned code runs (init body or module-owned `FUNC`),
200    /// `None` past an entry-function boundary (entry `FUNC`s stay
201    /// params-only and never see module state). Reads and mutations
202    /// consult the topmost `Some` store after lexical frames miss.
203    pub(super) module_stack: Vec<Option<String>>,
204    /// Parse-time module table (#115): imported files parse with the same
205    /// table as the entry script.
206    pub(super) module_table: oxdock_parser::ModuleTable,
207    /// Current nested function-call depth on this thread. Enforced against
208    /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
209    /// inherit the caller's depth budget.
210    pub(super) call_depth: usize,
211    /// Identity of the task this state executes (`0` = root flow).
212    /// Stamped onto pipe handles minted here and compared by the promotion
213    /// check: only the declaring task may promote its own pipes.
214    pub(super) task_id: u64,
215    /// Declared `--to-host` transfers recorded strictly at execution time:
216    /// each executed flagged `COPY` appends its evaluated
217    /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
218    /// these entries, so dead branches contribute nothing and dynamic
219    /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
220    /// in [`ExecIo`] when staged.
221    pub(super) push_manifest: Vec<(String, String)>,
222    pub(super) _marker: PhantomData<P>,
223}
224
225pub(super) struct ScopeSnapshot {
226    pub(super) cwd: GuardedPath,
227    pub(super) selection: WorkspaceSelection,
228    pub(super) envs: Arc<HashMap<String, String>>,
229}
230
231/// One parsed file module (#115), keyed by resolved display path: parse
232/// once, validate once, initialize once. `init` is `None` until the
233/// first import executes the body; every alias is a view onto the
234/// same record and the same shared state.
235#[derive(Clone, Default)]
236pub(super) struct ModuleRecord {
237    pub(super) steps: Vec<Step>,
238    pub(super) func_exports: Vec<String>,
239    /// `EXPORT TYPE` names in source order. Separate from func exports
240    /// so the MCP server never confuses a type for a tool.
241    pub(super) type_exports: Vec<String>,
242    pub(super) init: Option<ModuleInit>,
243}
244
245/// Initialized module state (#115): the shared globals every alias of
246/// one file observes. `vars` holds the module body's top-level `LET`
247/// bindings, drained from the init frame when the first import runs;
248/// module-owned `FUNC`s resolve names against `vars` after lexical
249/// frames miss, so one file's functions share one global state instead
250/// of each alias getting a private copy. `return_value` caches the
251/// init body's `RETURN`, so repeated imports bind the same value.
252#[derive(Clone)]
253pub(super) struct ModuleInit {
254    pub(super) vars: HashMap<String, (TypeTag, Value)>,
255    pub(super) return_value: Value,
256    /// Script env the module's functions execute with (#115): the
257    /// session seed plus the init body's own `ENV` contributions
258    /// (captured as a delta against the pre-init map, so
259    /// caller-established values stay out). `INHERIT_ENV` names are
260    /// re-read from the host at each call (see `inherit_names`),
261    /// since a re-inherit of an already-present value leaves no delta
262    /// yet must still admit the name.
263    pub(super) envs: HashMap<String, String>,
264    /// Top-level `INHERIT_ENV` names of the module file, re-established
265    /// from the host on every module-owned call. A module never
266    /// inherits its caller's environment; each file declares what it
267    /// reads, and the values flow from the host (or literals) at
268    /// init/call time.
269    pub(super) inherit_names: Vec<String>,
270}
271
272/// One anonymous background worker: the thread-join handle plus the
273/// task id drawn for the worker at spawn. Only `ThreadJoinHandle`s are
274/// ever pushed (a worker's own `RUN` steps wait inline); the id lets a
275/// `TIMEOUT` scope-end reaper join only the workers its own body
276/// spawned, leaving pre-existing ones alone.
277pub(super) struct BgChild {
278    pub(super) handle: Box<dyn BackgroundHandle>,
279    pub(super) task_id: u64,
280}
281
282/// Task completion record, written once by the first observer of a
283/// finished task and read by later polls. Never consumed: polls and a
284/// subsequent `AWAIT` all read the same record.
285#[derive(Clone)]
286pub(super) struct TaskCompletion {
287    pub(super) ok: bool,
288    pub(super) exit_code: i64,
289    pub(super) result: Option<Value>,
290    pub(super) error: String,
291}
292
293/// Point-in-time task view for `TASK_POLL`. Owned strings, bounded by
294/// the tail caps.
295pub(super) struct TaskObservation {
296    pub(super) running: bool,
297    pub(super) ok: bool,
298    pub(super) exit_code: i64,
299    pub(super) result: Option<Value>,
300    pub(super) error: String,
301}
302
303/// Bounded per-stream accumulator for one background task. Same
304/// drop-the-head discipline as the foreground tail rings.
305pub(super) struct TaskTails {
306    out: Vec<u8>,
307    err: Vec<u8>,
308    total_out: u64,
309    total_err: u64,
310}
311
312impl TaskTails {
313    pub(super) fn new() -> Self {
314        Self {
315            out: Vec::new(),
316            err: Vec::new(),
317            total_out: 0,
318            total_err: 0,
319        }
320    }
321
322    pub(super) fn push(&mut self, stream: TeeStream, bytes: &[u8]) {
323        let (buf, total) = match stream {
324            TeeStream::Stdout => (&mut self.out, &mut self.total_out),
325            TeeStream::Stderr => (&mut self.err, &mut self.total_err),
326        };
327        *total += bytes.len() as u64;
328        buf.extend_from_slice(bytes);
329        let excess = buf.len().saturating_sub(TASK_TAIL_CAP);
330        if excess > 0 {
331            buf.drain(..excess);
332        }
333    }
334
335    pub(super) fn snapshot(&self) -> (String, String, u64) {
336        let dropped = self.total_out.saturating_sub(self.out.len() as u64)
337            + self.total_err.saturating_sub(self.err.len() as u64);
338        (
339            String::from_utf8_lossy(&self.out).into_owned(),
340            String::from_utf8_lossy(&self.err).into_owned(),
341            dropped,
342        )
343    }
344}
345
346/// Lifecycle phase of a named background task (`LET $var: HANDLE<T> = ASYNC ...`).
347/// `Running` and `Awaiting` both hold the live handle inside the entry;
348/// `Cancelled` and `Completed` are terminal tombstones with no handle.
349pub(super) enum TaskPhase {
350    Running,
351    Awaiting,
352    Cancelled,
353    Completed,
354}
355
356pub(super) struct TaskEntryState {
357    pub(super) phase: TaskPhase,
358    pub(super) handle: Option<Box<dyn BackgroundHandle>>,
359    /// True once the handle has been consumed and its thread joined
360    /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
361    /// Threads observing `Cancelled` must wait on `done` until `reaped`
362    /// before resuming, so no caller outruns OS process teardown.
363    pub(super) reaped: bool,
364    /// Explicit result of a background task, published by `RETURN` (block
365    /// bodies) or the function call itself (single-`CALL` bodies). Set
366    /// under the entry lock before `done.notify_all()`; read by
367    /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that have not finished
368    /// or have fallen off the end. Task stdout is never captured: it
369    /// streams live to the shared parent writer.
370    pub(super) return_value: Option<Value>,
371    /// Completion record written once by the first observer of a
372    /// finished task (`TASK_POLL` or the teardown path). Read by later
373    /// polls and post-mortem rendering; never consumed.
374    pub(super) completion: Option<TaskCompletion>,
375    /// Whether this task's body can publish a value: single-`CALL` bodies
376    /// always can; block bodies can iff they contain a `RETURN` in their
377    /// own scope. A task that can return but falls off the end fails its
378    /// capture loudly; a task that cannot return yields `INT` 0.
379    pub(super) returns_value: bool,
380}
381
382/// Synchronized named-task entry shared by every scope that can observe the
383/// task (`AWAIT`, `CANCEL`, `TASK_POLL`, end-poll reaping). Exactly one
384/// thread ever takes the handle and performs teardown; all other
385/// observers rendezvous on `done`/`reaped`.
386pub(super) struct TaskEntry {
387    pub(super) state: Mutex<TaskEntryState>,
388    pub(super) done: Condvar,
389    /// Bounded live output. Fed by the worker tee, drained by
390    /// `TASK_POLL` without consuming, dropped with the entry.
391    pub(super) tails: Arc<Mutex<TaskTails>>,
392}
393
394impl TaskEntry {
395    /// Whether this entry occupies a live slot: awaiting a join, or
396    /// running with an unfinished thread. Terminal phases and reaped
397    /// joins are done. Un-awaited finished tasks report done via
398    /// `try_wait`, so ghosts never hold a slot. Never blocks: a
399    /// still-running thread reports `Ok(None)` without joining.
400    pub(super) fn is_live(&self) -> bool {
401        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
402        match guard.phase {
403            TaskPhase::Running => match guard.handle.as_mut() {
404                Some(handle) => matches!(handle.try_wait(), Ok(None)),
405                None => false,
406            },
407            TaskPhase::Awaiting => true,
408            TaskPhase::Completed | TaskPhase::Cancelled => false,
409        }
410    }
411
412    pub(super) fn new(
413        handle: Box<dyn BackgroundHandle>,
414        returns_value: bool,
415        tails: Arc<Mutex<TaskTails>>,
416    ) -> Self {
417        Self {
418            state: Mutex::new(TaskEntryState {
419                phase: TaskPhase::Running,
420                handle: Some(handle),
421                reaped: false,
422                return_value: None,
423                completion: None,
424                returns_value,
425            }),
426            done: Condvar::new(),
427            tails,
428        }
429    }
430
431    /// Non-destructive snapshot of live tails plus dropped head count.
432    /// Never blocks execution: a poisoned lock reads through.
433    pub(super) fn snapshot_tails(&self) -> (String, String, u64) {
434        self.tails
435            .lock()
436            .map(|tails| tails.snapshot())
437            .unwrap_or_else(|e| e.into_inner().snapshot())
438    }
439
440    /// Observe completion without consuming the task. Never transitions
441    /// phase, never takes the handle, never notifies: a later `AWAIT`
442    /// still joins normally. First observation of a finished task
443    /// records the completion for later polls; the `try_wait` reap it
444    /// performs is the same one `AWAIT` would do, and the cached status
445    /// keeps that path consistent.
446    pub(super) fn observe_completion(&self) -> TaskObservation {
447        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
448        if let Some(done) = guard.completion.clone() {
449            return TaskObservation {
450                running: false,
451                ok: done.ok,
452                exit_code: done.exit_code,
453                result: done.result,
454                error: done.error,
455            };
456        }
457        if !matches!(guard.phase, TaskPhase::Running) {
458            return TaskObservation {
459                running: false,
460                ok: false,
461                exit_code: -1,
462                result: None,
463                error: "task handle was not found or has already been awaited".to_string(),
464            };
465        }
466        match guard.handle.as_mut() {
467            None => TaskObservation {
468                running: true,
469                ok: true,
470                exit_code: -1,
471                result: None,
472                error: String::new(),
473            },
474            Some(handle) => match handle.try_wait() {
475                Ok(Some(status)) => {
476                    let completion = TaskCompletion {
477                        ok: status.success(),
478                        exit_code: status.code().map(i64::from).unwrap_or(-1),
479                        result: guard.return_value.clone(),
480                        error: if status.success() {
481                            String::new()
482                        } else {
483                            format!("task exited with status {status}")
484                        },
485                    };
486                    guard.completion = Some(TaskCompletion {
487                        ok: completion.ok,
488                        exit_code: completion.exit_code,
489                        result: completion.result.clone(),
490                        error: completion.error.clone(),
491                    });
492                    TaskObservation {
493                        running: false,
494                        ok: completion.ok,
495                        exit_code: completion.exit_code,
496                        result: completion.result,
497                        error: completion.error,
498                    }
499                }
500                Ok(None) => TaskObservation {
501                    running: true,
502                    ok: true,
503                    exit_code: -1,
504                    result: None,
505                    error: String::new(),
506                },
507                Err(err) => {
508                    let completion = TaskCompletion {
509                        ok: false,
510                        exit_code: exit_code_of(&err).unwrap_or(1),
511                        result: None,
512                        error: format!("{err:#}"),
513                    };
514                    guard.completion = Some(TaskCompletion {
515                        ok: completion.ok,
516                        exit_code: completion.exit_code,
517                        result: completion.result.clone(),
518                        error: completion.error.clone(),
519                    });
520                    TaskObservation {
521                        running: false,
522                        ok: completion.ok,
523                        exit_code: completion.exit_code,
524                        result: completion.result,
525                        error: completion.error,
526                    }
527                }
528            },
529        }
530    }
531
532    /// Block until the teardown owner has consumed the handle and joined
533    /// the task thread. Lock-free for callers except the wait itself.
534    pub(super) fn wait_reaped(&self) {
535        let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
536        while !guard.reaped {
537            guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
538        }
539    }
540
541    /// Mark teardown complete and wake every rendezvous waiter.
542    pub(super) fn finish_teardown(&self) {
543        {
544            let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
545            guard.handle = None;
546            guard.reaped = true;
547        }
548        self.done.notify_all();
549    }
550}
551
552/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
553/// keyed by the top-level body index of the final producer step for each
554/// pipe: dropping the guards for step `k` once it completes keeps the
555/// pipe open across every transient gap between producers, then releases
556/// it so later consumer steps in the same task observe EOF.
557///
558/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
559/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
560/// code with different slices and must never consume the worker's
561/// top-level map.
562pub(super) struct KeeperExpiry {
563    body_addr: usize,
564    body_len: usize,
565    map: HashMap<usize, Vec<KeeperGuard>>,
566}
567
568impl KeeperExpiry {
569    pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
570        Self {
571            body_addr: steps.as_ptr() as usize,
572            body_len: steps.len(),
573            map,
574        }
575    }
576
577    pub(super) fn matches(&self, steps: &[Step]) -> bool {
578        self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
579    }
580
581    /// Drop the guards expiring at top-level step `idx`. Returns true when
582    /// the map is drained and the expiry itself can be cleared.
583    pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
584        if self.matches(steps) {
585            drop(self.map.remove(&idx));
586        }
587        self.map.is_empty()
588    }
589}
590
591impl<P: ProcessManager> ExecState<P> {
592    /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
593    /// `Expr::Env`, expansions): exact hit first, case-insensitive
594    /// fallback on Windows so `{{ env:Path }}` resolves the seeded
595    /// `PATH`. The map is seeded at init, so no fallback layer exists.
596    pub(super) fn get_env(&self, key: &str) -> Option<&str> {
597        if let Some(v) = self.envs.get(key) {
598            return Some(v.as_str());
599        }
600        #[allow(clippy::disallowed_macros)]
601        if cfg!(windows) {
602            return self
603                .envs
604                .iter()
605                .find(|(k, _)| oxdock_process::names_eq(k, key))
606                .map(|(_, v)| v.as_str());
607        }
608        None
609    }
610
611    pub(super) fn command_ctx(&self) -> Result<CommandContext> {
612        // Resolve the working directory through the snapshot choke point: a
613        // snapshot-rooted cwd materializes here (so `RUN` executes against a
614        // real directory) while a local cwd resolves purely lexically with
615        // zero I/O. The seeded scratch materializes alongside: `HOME` and
616        // `TMPDIR` point at it, so children writing temp or profile data
617        // must observe real directories, never lexical candidates.
618        let cwd = self.fs.resolve_write(&self.cwd, ".")?;
619        self.cargo_scratch.ensure_materialized()?;
620        Ok(CommandContext::new(
621            &cwd.into(),
622            Arc::clone(&self.envs),
623            &self.cargo_scratch,
624            self.fs.root(),
625            self.fs.build_context(),
626        ))
627    }
628
629    /// Draw the next task id, enforcing the global live-task cap and
630    /// sweeping retained finished entries. Every ASYNC allocation path
631    /// calls this, so named and anonymous tasks share one choke point.
632    /// The live count is atomic and shared across all forked workers,
633    /// so nested spawns cannot bypass the cap that a per-state scan
634    /// would miss. Refusal is backpressure: a full host fails the spawn
635    /// loudly instead of wedging.
636    pub(super) fn alloc_task_id(&mut self) -> anyhow::Result<u64> {
637        // Purge cleanly-finished anonymous children first: their threads
638        // are gone and a zero exit has no reporter, so retaining them
639        // only grows the vec. Failed handles stay for the end-pipeline
640        // reaper, which owns their error reporting.
641        self.bg_children
642            .retain_mut(|child| match child.handle.try_wait() {
643                Ok(None) => true,
644                Ok(Some(status)) => !status.success(),
645                Err(_) => true,
646            });
647        self.live_tasks
648            .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
649                (n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
650            })
651            .map_err(|_| {
652                anyhow::anyhow!(
653                    "concurrency limit exceeded: maximum of {MAX_RUNNING_TASKS} running background tasks allowed"
654                )
655            })?;
656        let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
657        self.sweep_finished_tasks();
658        Ok(id)
659    }
660
661    /// Drop finished entries past `MAX_RETAINED_FINISHED`, oldest
662    /// first. Finished means a terminal phase or a completed join;
663    /// `Awaiting` entries always survive (a waiter is rendezvousing)
664    /// and running entries are never touched. Evicted ids read as
665    /// unknown/already-awaited afterwards, like an awaited task.
666    fn sweep_finished_tasks(&self) {
667        let mut finished: Vec<u64> = Vec::new();
668        {
669            let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
670            for (id, entry) in named.iter() {
671                // `is_live` already exempts awaiting entries: a waiter
672                // is rendezvousing on them.
673                if !entry.is_live() {
674                    finished.push(*id);
675                }
676            }
677        }
678        if finished.len() <= MAX_RETAINED_FINISHED {
679            return;
680        }
681        finished.sort_unstable();
682        let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
683        for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
684            named.remove(id);
685        }
686    }
687
688    /// Fork the execution state for a child thread. The child gets:
689    /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
690    /// - Cloned envs, cwd, cargo scratch name, var_scopes
691    /// - Fresh bg_children, scope_stack (empty -- child manages its own)
692    /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
693    /// - Cloned io configuration
694    /// - Independent cancel_token, active_process (child manages its own)
695    /// - Shared named_tasks and next_task_id (via Arc clone)
696    #[allow(dead_code)]
697    pub(super) fn fork(&self) -> Self {
698        Self {
699            fs: self.fs.clone_box(),
700            cargo_scratch: self.cargo_scratch.clone(),
701            seed: Arc::clone(&self.seed),
702            cwd: self.cwd.clone(),
703            envs: Arc::clone(&self.envs),
704            bg_children: Vec::new(),
705            scope_stack: Vec::new(),
706            isolated_stack: self.isolated_stack.clone(),
707            io: self.io.clone(),
708            assert_windows: Arc::clone(&self.assert_windows),
709            assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
710            exact_stdout: Arc::clone(&self.exact_stdout),
711            var_scopes: self.var_scopes.clone(),
712            cancel_token: Arc::new(AtomicBool::new(false)),
713            // Fresh cancellation, inherited telemetry: the fork's
714            // workers still attribute to the originating run.
715            cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
716            active_process: Arc::new(Mutex::new(None)),
717            named_tasks: Arc::clone(&self.named_tasks),
718            next_task_id: Arc::clone(&self.next_task_id),
719            // Shared live count, never reset: nested workers report into
720            // the same cap their spawner was admitted under.
721            live_tasks: Arc::clone(&self.live_tasks),
722            inside_async: true,
723            keeper_expiry: None,
724            cancellable: self.cancellable,
725            reap_floor: self.reap_floor,
726            functions: self.functions.clone(),
727            entry_file: self.entry_file.clone(),
728            import_stack: self.import_stack.clone(),
729            import_alias_frame: self.import_alias_frame,
730            modules: self.modules.clone(),
731            validated_modules: self.validated_modules.clone(),
732            module_stack: self.module_stack.clone(),
733            module_table: self.module_table.clone(),
734            types: self.types.clone(),
735            record_schemas: self.record_schemas.clone(),
736            module_states: self.module_states.clone(),
737            type_aliases: self.type_aliases.clone(),
738            call_depth: self.call_depth,
739            task_id: self.task_id,
740            // Forks start with an empty manifest: async children record
741            // their own executions; the guest packs the root manifest.
742            push_manifest: Vec::new(),
743            _marker: PhantomData,
744        }
745    }
746
747    /// Whether `pipe` may promote to an OS kernel pair on behalf of
748    /// `task_id`: only when it was declared by that same task and no
749    /// spawned child can observe it. Anything else stays script-backed, so
750    /// concurrent tasks can never disagree about EOF propagation.
751    /// Spawning tasks pass their worker id (not the spawner's): promotion
752    /// is judged from the worker's perspective, since it is the worker's
753    /// bindings that will hold raw descriptors.
754    pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
755        pipe.declaring_task() == task_id && !pipe.has_escaped()
756    }
757
758    /// Whether `pipe` may promote on the current thread (main flow and
759    /// inline resolves).
760    pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
761        Self::can_promote_in_task(pipe, self.task_id)
762    }
763
764    /// Mark every pipe visible in scope as shared-with-a-child. Called
765    /// synchronously on the spawner before a worker thread starts: forking
766    /// copies the whole environment, so every visible pipe is capturable
767    /// whether or not the child body names it. Over-marking only costs
768    /// zero-copy opportunities, never correctness.
769    pub(super) fn mark_captured_pipes_escaped(&self) {
770        for scope in self.var_scopes.iter() {
771            for (_, value) in scope.values() {
772                mark_value_pipes_escaped(value);
773            }
774        }
775        for record in self.modules.values() {
776            if let Some(init) = record.init.as_ref() {
777                for entry in init.vars.values() {
778                    mark_value_pipes_escaped(&entry.1);
779                }
780            }
781        }
782    }
783
784    pub(super) fn push_var_scope(&mut self) {
785        self.var_scopes.push(HashMap::new());
786    }
787
788    pub(super) fn pop_var_scope(&mut self) {
789        self.var_scopes.pop();
790    }
791
792    /// Reset module-owned env (#115): env to the module init's
793    /// stored map. Nothing else is touched: workspace selection and
794    /// cwd are ambient and flow through from the caller, so a module
795    /// operates in the same workspace its importer does. The
796    /// surrounding `push_scope` restores the caller afterwards.
797    pub(super) fn reset_module_env(&mut self, envs: HashMap<String, String>) {
798        self.envs = Arc::new(envs);
799    }
800
801    /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
802    /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
803    /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
804    /// Function definitions scope through the registry's own frames.
805    pub(super) fn push_scope(&mut self) {
806        self.scope_stack.push(ScopeSnapshot {
807            cwd: self.cwd.clone(),
808            selection: self.fs.selection(),
809            envs: Arc::clone(&self.envs),
810        });
811        self.functions.push_scope();
812        self.push_var_scope();
813    }
814
815    /// Exit a lexical scope, restoring everything `push_scope` saved.
816    pub(super) fn pop_scope(&mut self) -> Result<()> {
817        let snapshot = self
818            .scope_stack
819            .pop()
820            .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
821        self.fs.restore_selection(snapshot.selection);
822        self.cwd = snapshot.cwd;
823        self.envs = snapshot.envs;
824        self.functions.pop_scope();
825        self.pop_var_scope();
826        Ok(())
827    }
828    pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
829        if self
830            .var_scopes
831            .last()
832            .map(|s| s.contains_key(&key))
833            .unwrap_or(false)
834        {
835            anyhow::bail!(
836                "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
837                key,
838                key
839            );
840        }
841        let coerced = super::args::coerce_value(value, &kind)?;
842        let scope = self
843            .var_scopes
844            .last_mut()
845            .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
846        scope.insert(key, (kind, coerced));
847        Ok(())
848    }
849
850    pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
851        let kind = self
852            .var_scopes
853            .iter()
854            .rev()
855            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
856            .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
857            .ok_or_else(|| {
858                anyhow::anyhow!(
859                    "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
860                )
861            })?;
862        let coerced = super::args::coerce_value(value, &kind)?;
863        for scope in self.var_scopes.iter_mut().rev() {
864            if let Some(slot) = scope.get_mut(key) {
865                slot.1 = coerced;
866                return Ok(());
867            }
868        }
869        // Not a lexical binding: update the owning module's shared
870        // store in place, so every alias observes the mutation.
871        if let Some((_, stored)) = self.module_var_mut(key) {
872            *stored = coerced;
873            return Ok(());
874        }
875        anyhow::bail!("undeclared variable ${key}");
876    }
877
878    /// Append `item` to the LIST binding `key` in place. Copy-on-write:
879    /// the buffer detaches only when shared, so aliases keep their
880    /// contents; the sole owner mutates with no copy. Bails for
881    /// undeclared names and non-list bindings. Shaped lists validate
882    /// the item against the element tag, so a push can never silently
883    /// corrupt the shape the declaration promises.
884    pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
885        let kind = self
886            .var_scopes
887            .iter()
888            .rev()
889            .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
890            .or_else(|| self.module_var(key).map(|(k, _)| k.clone()))
891            .ok_or_else(|| {
892                anyhow::anyhow!(
893                    "undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
894                )
895            })?;
896        let element = match kind {
897            TypeTag::List => None,
898            TypeTag::ListOf(element) => Some(element.as_ref().clone()),
899            _ => {
900                anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
901            }
902        };
903        for scope in self.var_scopes.iter_mut().rev() {
904            if let Some(slot) = scope.get_mut(key) {
905                let list = slot.1.as_list_mut().ok_or_else(|| {
906                    anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
907                })?;
908                if let Some(expected) = element {
909                    oxdock_parser::check_value_at(
910                        &expected,
911                        &item,
912                        &format!("${key}[{}]", list.len()),
913                    )?;
914                }
915                list.push(item);
916                return Ok(());
917            }
918        }
919        // Not a lexical binding: append to the owning module's shared
920        // store in place, so module-global lists stay appendable from
921        // module-owned functions with no importer visibility.
922        if let Some((_, value)) = self.module_var_mut(key) {
923            let list = value.as_list_mut().ok_or_else(|| {
924                anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
925            })?;
926            if let Some(expected) = element {
927                oxdock_parser::check_value_at(
928                    &expected,
929                    &item,
930                    &format!("${key}[{}]", list.len()),
931                )?;
932            }
933            list.push(item);
934            return Ok(());
935        }
936        anyhow::bail!("undeclared variable ${key}");
937    }
938
939    pub(super) fn get_var(&self, key: &str) -> Option<Value> {
940        // Walk scopes from innermost to outermost
941        for scope in self.var_scopes.iter().rev() {
942            if let Some((_, value)) = scope.get(key) {
943                return Some(value.clone());
944            }
945        }
946        // Module-owned code falls back to the owning module's shared
947        // store (#115): one file's functions share one global state.
948        // Entry code never sees it (its boundary pushes `None`).
949        if let Some((_, value)) = self.module_var(key) {
950            return Some(value.clone());
951        }
952        None
953    }
954
955    pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
956        for scope in self.var_scopes.iter().rev() {
957            if let Some(entry) = scope.get(key) {
958                return Some(entry.clone());
959            }
960        }
961        if let Some(entry) = self.module_var(key) {
962            return Some(entry.clone());
963        }
964        None
965    }
966
967    /// Owning module of the executing code (#115): the top of the
968    /// module stack when it names a module, `None` past an entry
969    /// boundary or outside any module. Lookups stop at the first
970    /// entry from the top, so entry functions called from module
971    /// code stay params-only.
972    pub(super) fn current_module(&self) -> Option<String> {
973        match self.module_stack.last() {
974            Some(Some(key)) => Some(key.clone()),
975            _ => None,
976        }
977    }
978
979    /// One lookup for the owning module's shared store (#115): the
980    /// single fallback every variable accessor uses after its lexical
981    /// walk misses, so module-global visibility lives in exactly one
982    /// place. Entry code never reaches here (its boundary pushes
983    /// `None`, and `current_module` yields nothing then).
984    fn module_var(&self, key: &str) -> Option<&(TypeTag, Value)> {
985        self.module_store()?.get(key)
986    }
987
988    /// Mutable twin of [`ExecState::module_var`], for the two
989    /// accessors that write through to the store in place.
990    fn module_var_mut(&mut self, key: &str) -> Option<&mut (TypeTag, Value)> {
991        self.module_store_mut()?.get_mut(key)
992    }
993
994    /// Get a flattened view of all variables across all scopes.
995    /// Inner scopes take precedence over outer scopes. Module-owned
996    /// code additionally sees the owning module's shared store beneath
997    /// every lexical frame; entry code never does.
998    pub(super) fn all_vars(&self) -> HashMap<String, Value> {
999        let mut result = HashMap::new();
1000        for scope in self.var_scopes.iter().rev() {
1001            for (k, (_, v)) in scope {
1002                result.entry(k.clone()).or_insert_with(|| v.clone());
1003            }
1004        }
1005        if let Some(store) = self.module_store() {
1006            for (k, (_, v)) in store {
1007                result.entry(k.clone()).or_insert_with(|| v.clone());
1008            }
1009        }
1010        result
1011    }
1012
1013    /// Borrow the owning module's shared store, if any. The single
1014    /// map behind [`ExecState::module_var`], exposed whole for the
1015    /// one accessor that flattens every binding.
1016    fn module_store(&self) -> Option<&HashMap<String, (TypeTag, Value)>> {
1017        let module = self.current_module()?;
1018        self.modules
1019            .get(&module)?
1020            .init
1021            .as_ref()
1022            .map(|init| &init.vars)
1023    }
1024
1025    /// Mutable twin of [`ExecState::module_store`], for the accessors
1026    /// that write through to the store in place.
1027    fn module_store_mut(&mut self) -> Option<&mut HashMap<String, (TypeTag, Value)>> {
1028        let module = self.current_module()?;
1029        self.modules
1030            .get_mut(&module)?
1031            .init
1032            .as_mut()
1033            .map(|init| &mut init.vars)
1034    }
1035}
1036
1037/// Mark every pipe handle reachable from `value` as shared-with-a-child.
1038/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
1039/// shallow top-level check would miss them and let a later promotion
1040/// corrupt the shared EOF contract. Values form a tree, so recursion
1041/// terminates; host-opaque payloads cannot carry handles.
1042fn mark_value_pipes_escaped(value: &Value) {
1043    if let Some(handle) = value.as_pipe_handle() {
1044        handle.mark_escaped();
1045        return;
1046    }
1047    if let Some(items) = value.as_list() {
1048        for item in items {
1049            mark_value_pipes_escaped(item);
1050        }
1051    }
1052    if let Some(entries) = value.as_map() {
1053        for item in entries.values() {
1054            mark_value_pipes_escaped(item);
1055        }
1056    }
1057}