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