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