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