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