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