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