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<Box<dyn BackgroundHandle>>,
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 /// The single function registry: DSL `FUNC` definitions, builtins, and
165 /// host extensions. Script entries scope lexically through the
166 /// registry's own frames (managed by `push_scope`/`pop_scope`);
167 /// native entries persist. Shared across `fork()` via clone.
168 pub(super) functions: FunctionRegistry<P>,
169 /// Current nested function-call depth on this thread. Enforced against
170 /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
171 /// inherit the caller's depth budget.
172 pub(super) call_depth: usize,
173 /// Identity of the task this state executes (`0` = root flow).
174 /// Stamped onto pipe handles minted here and compared by the promotion
175 /// check: only the declaring task may promote its own pipes.
176 pub(super) task_id: u64,
177 /// Declared `--to-host` transfers recorded strictly at execution time:
178 /// each executed flagged `COPY` appends its evaluated
179 /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
180 /// these entries, so dead branches contribute nothing and dynamic
181 /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
182 /// in [`ExecIo`] when staged.
183 pub(super) push_manifest: Vec<(String, String)>,
184 pub(super) _marker: PhantomData<P>,
185}
186
187pub(super) struct ScopeSnapshot {
188 pub(super) cwd: GuardedPath,
189 pub(super) root: GuardedPath,
190 pub(super) envs: Arc<HashMap<String, String>>,
191}
192
193/// Task completion record, written once by the first observer of a
194/// finished task and read by later polls. Never consumed: polls and a
195/// subsequent `AWAIT` all read the same record.
196#[derive(Clone)]
197pub(super) struct TaskCompletion {
198 pub(super) ok: bool,
199 pub(super) exit_code: i64,
200 pub(super) result: Option<Value>,
201 pub(super) error: String,
202}
203
204/// Point-in-time task view for `TASK_POLL`. Owned strings, bounded by
205/// the tail caps.
206pub(super) struct TaskObservation {
207 pub(super) running: bool,
208 pub(super) ok: bool,
209 pub(super) exit_code: i64,
210 pub(super) result: Option<Value>,
211 pub(super) error: String,
212}
213
214/// Bounded per-stream accumulator for one background task. Same
215/// drop-the-head discipline as the foreground tail rings.
216pub(super) struct TaskTails {
217 out: Vec<u8>,
218 err: Vec<u8>,
219 total_out: u64,
220 total_err: u64,
221}
222
223impl TaskTails {
224 pub(super) fn new() -> Self {
225 Self {
226 out: Vec::new(),
227 err: Vec::new(),
228 total_out: 0,
229 total_err: 0,
230 }
231 }
232
233 pub(super) fn push(&mut self, stream: TeeStream, bytes: &[u8]) {
234 let (buf, total) = match stream {
235 TeeStream::Stdout => (&mut self.out, &mut self.total_out),
236 TeeStream::Stderr => (&mut self.err, &mut self.total_err),
237 };
238 *total += bytes.len() as u64;
239 buf.extend_from_slice(bytes);
240 let excess = buf.len().saturating_sub(TASK_TAIL_CAP);
241 if excess > 0 {
242 buf.drain(..excess);
243 }
244 }
245
246 pub(super) fn snapshot(&self) -> (String, String, u64) {
247 let dropped = self.total_out.saturating_sub(self.out.len() as u64)
248 + self.total_err.saturating_sub(self.err.len() as u64);
249 (
250 String::from_utf8_lossy(&self.out).into_owned(),
251 String::from_utf8_lossy(&self.err).into_owned(),
252 dropped,
253 )
254 }
255}
256
257/// Lifecycle phase of a named background task (`LET $var: HANDLE = ASYNC ...`).
258/// `Running` and `Awaiting` both hold the live handle inside the entry;
259/// `Cancelled` and `Completed` are terminal tombstones with no handle.
260pub(super) enum TaskPhase {
261 Running,
262 Awaiting,
263 Cancelled,
264 Completed,
265}
266
267pub(super) struct TaskEntryState {
268 pub(super) phase: TaskPhase,
269 pub(super) handle: Option<Box<dyn BackgroundHandle>>,
270 /// True once the handle has been consumed and its thread joined
271 /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
272 /// Threads observing `Cancelled` must wait on `done` until `reaped`
273 /// before resuming, so no caller outruns OS process teardown.
274 pub(super) reaped: bool,
275 /// Explicit result of a background task, published by `RETURN` (block
276 /// bodies) or the function call itself (single-`CALL` bodies). Set
277 /// under the entry lock before `done.notify_all()`; read by
278 /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that have not finished
279 /// or have fallen off the end. Task stdout is never captured: it
280 /// streams live to the shared parent writer.
281 pub(super) return_value: Option<Value>,
282 /// Completion record written once by the first observer of a
283 /// finished task (`TASK_POLL` or the teardown path). Read by later
284 /// polls and post-mortem rendering; never consumed.
285 pub(super) completion: Option<TaskCompletion>,
286 /// Whether this task's body can publish a value: single-`CALL` bodies
287 /// always can; block bodies can iff they contain a `RETURN` in their
288 /// own scope. A task that can return but falls off the end fails its
289 /// capture loudly; a task that cannot return yields `INT` 0.
290 pub(super) returns_value: bool,
291}
292
293/// Synchronized named-task entry shared by every scope that can observe the
294/// task (`AWAIT`, `CANCEL`, `TASK_POLL`, end-poll reaping). Exactly one
295/// thread ever takes the handle and performs teardown; all other
296/// observers rendezvous on `done`/`reaped`.
297pub(super) struct TaskEntry {
298 pub(super) state: Mutex<TaskEntryState>,
299 pub(super) done: Condvar,
300 /// Bounded live output. Fed by the worker tee, drained by
301 /// `TASK_POLL` without consuming, dropped with the entry.
302 pub(super) tails: Arc<Mutex<TaskTails>>,
303}
304
305impl TaskEntry {
306 /// Whether this entry occupies a live slot: awaiting a join, or
307 /// running with an unfinished thread. Terminal phases and reaped
308 /// joins are done. Un-awaited finished tasks report done via
309 /// `try_wait`, so ghosts never hold a slot. Never blocks: a
310 /// still-running thread reports `Ok(None)` without joining.
311 pub(super) fn is_live(&self) -> bool {
312 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
313 match guard.phase {
314 TaskPhase::Running => match guard.handle.as_mut() {
315 Some(handle) => matches!(handle.try_wait(), Ok(None)),
316 None => false,
317 },
318 TaskPhase::Awaiting => true,
319 TaskPhase::Completed | TaskPhase::Cancelled => false,
320 }
321 }
322
323 pub(super) fn new(
324 handle: Box<dyn BackgroundHandle>,
325 returns_value: bool,
326 tails: Arc<Mutex<TaskTails>>,
327 ) -> Self {
328 Self {
329 state: Mutex::new(TaskEntryState {
330 phase: TaskPhase::Running,
331 handle: Some(handle),
332 reaped: false,
333 return_value: None,
334 completion: None,
335 returns_value,
336 }),
337 done: Condvar::new(),
338 tails,
339 }
340 }
341
342 /// Non-destructive snapshot of live tails plus dropped head count.
343 /// Never blocks execution: a poisoned lock reads through.
344 pub(super) fn snapshot_tails(&self) -> (String, String, u64) {
345 self.tails
346 .lock()
347 .map(|tails| tails.snapshot())
348 .unwrap_or_else(|e| e.into_inner().snapshot())
349 }
350
351 /// Observe completion without consuming the task. Never transitions
352 /// phase, never takes the handle, never notifies: a later `AWAIT`
353 /// still joins normally. First observation of a finished task
354 /// records the completion for later polls; the `try_wait` reap it
355 /// performs is the same one `AWAIT` would do, and the cached status
356 /// keeps that path consistent.
357 pub(super) fn observe_completion(&self) -> TaskObservation {
358 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
359 if let Some(done) = guard.completion.clone() {
360 return TaskObservation {
361 running: false,
362 ok: done.ok,
363 exit_code: done.exit_code,
364 result: done.result,
365 error: done.error,
366 };
367 }
368 if !matches!(guard.phase, TaskPhase::Running) {
369 return TaskObservation {
370 running: false,
371 ok: false,
372 exit_code: -1,
373 result: None,
374 error: "task handle was not found or has already been awaited".to_string(),
375 };
376 }
377 match guard.handle.as_mut() {
378 None => TaskObservation {
379 running: true,
380 ok: true,
381 exit_code: -1,
382 result: None,
383 error: String::new(),
384 },
385 Some(handle) => match handle.try_wait() {
386 Ok(Some(status)) => {
387 let completion = TaskCompletion {
388 ok: status.success(),
389 exit_code: status.code().map(i64::from).unwrap_or(-1),
390 result: guard.return_value.clone(),
391 error: if status.success() {
392 String::new()
393 } else {
394 format!("task exited with status {status}")
395 },
396 };
397 guard.completion = Some(TaskCompletion {
398 ok: completion.ok,
399 exit_code: completion.exit_code,
400 result: completion.result.clone(),
401 error: completion.error.clone(),
402 });
403 TaskObservation {
404 running: false,
405 ok: completion.ok,
406 exit_code: completion.exit_code,
407 result: completion.result,
408 error: completion.error,
409 }
410 }
411 Ok(None) => TaskObservation {
412 running: true,
413 ok: true,
414 exit_code: -1,
415 result: None,
416 error: String::new(),
417 },
418 Err(err) => {
419 let completion = TaskCompletion {
420 ok: false,
421 exit_code: exit_code_of(&err).unwrap_or(1),
422 result: None,
423 error: format!("{err:#}"),
424 };
425 guard.completion = Some(TaskCompletion {
426 ok: completion.ok,
427 exit_code: completion.exit_code,
428 result: completion.result.clone(),
429 error: completion.error.clone(),
430 });
431 TaskObservation {
432 running: false,
433 ok: completion.ok,
434 exit_code: completion.exit_code,
435 result: completion.result,
436 error: completion.error,
437 }
438 }
439 },
440 }
441 }
442
443 /// Block until the teardown owner has consumed the handle and joined
444 /// the task thread. Lock-free for callers except the wait itself.
445 pub(super) fn wait_reaped(&self) {
446 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
447 while !guard.reaped {
448 guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
449 }
450 }
451
452 /// Mark teardown complete and wake every rendezvous waiter.
453 pub(super) fn finish_teardown(&self) {
454 {
455 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
456 guard.handle = None;
457 guard.reaped = true;
458 }
459 self.done.notify_all();
460 }
461}
462
463/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
464/// keyed by the top-level body index of the final producer step for each
465/// pipe: dropping the guards for step `k` once it completes keeps the
466/// pipe open across every transient gap between producers, then releases
467/// it so later consumer steps in the same task observe EOF.
468///
469/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
470/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
471/// code with different slices and must never consume the worker's
472/// top-level map.
473pub(super) struct KeeperExpiry {
474 body_addr: usize,
475 body_len: usize,
476 map: HashMap<usize, Vec<KeeperGuard>>,
477}
478
479impl KeeperExpiry {
480 pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
481 Self {
482 body_addr: steps.as_ptr() as usize,
483 body_len: steps.len(),
484 map,
485 }
486 }
487
488 pub(super) fn matches(&self, steps: &[Step]) -> bool {
489 self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
490 }
491
492 /// Drop the guards expiring at top-level step `idx`. Returns true when
493 /// the map is drained and the expiry itself can be cleared.
494 pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
495 if self.matches(steps) {
496 drop(self.map.remove(&idx));
497 }
498 self.map.is_empty()
499 }
500}
501
502impl<P: ProcessManager> ExecState<P> {
503 /// Script-map environment lookup for DSL evaluation (`is_exec_name`,
504 /// `Expr::Env`, expansions): exact hit first, case-insensitive
505 /// fallback on Windows so `{{ env:Path }}` resolves the seeded
506 /// `PATH`. The map is seeded at init, so no fallback layer exists.
507 pub(super) fn get_env(&self, key: &str) -> Option<&str> {
508 if let Some(v) = self.envs.get(key) {
509 return Some(v.as_str());
510 }
511 #[allow(clippy::disallowed_macros)]
512 if cfg!(windows) {
513 return self
514 .envs
515 .iter()
516 .find(|(k, _)| oxdock_process::names_eq(k, key))
517 .map(|(_, v)| v.as_str());
518 }
519 None
520 }
521
522 pub(super) fn command_ctx(&self) -> Result<CommandContext> {
523 // Resolve the working directory through the snapshot choke point: a
524 // snapshot-rooted cwd materializes here (so `RUN` executes against a
525 // real directory) while a local cwd resolves purely lexically with
526 // zero I/O. The seeded scratch materializes alongside: `HOME` and
527 // `TMPDIR` point at it, so children writing temp or profile data
528 // must observe real directories, never lexical candidates.
529 let cwd = self.fs.resolve_write(&self.cwd, ".")?;
530 self.cargo_scratch.ensure_materialized()?;
531 Ok(CommandContext::new(
532 &cwd.into(),
533 Arc::clone(&self.envs),
534 &self.cargo_scratch,
535 self.fs.root(),
536 self.fs.build_context(),
537 ))
538 }
539
540 /// Draw the next task id, enforcing the global live-task cap and
541 /// sweeping retained finished entries. Every ASYNC allocation path
542 /// calls this, so named and anonymous tasks share one choke point.
543 /// The live count is atomic and shared across all forked workers,
544 /// so nested spawns cannot bypass the cap that a per-state scan
545 /// would miss. Refusal is backpressure: a full host fails the spawn
546 /// loudly instead of wedging.
547 pub(super) fn alloc_task_id(&mut self) -> anyhow::Result<u64> {
548 // Purge cleanly-finished anonymous children first: their threads
549 // are gone and a zero exit has no reporter, so retaining them
550 // only grows the vec. Failed handles stay for the end-pipeline
551 // reaper, which owns their error reporting.
552 self.bg_children
553 .retain_mut(|handle| match handle.try_wait() {
554 Ok(None) => true,
555 Ok(Some(status)) => !status.success(),
556 Err(_) => true,
557 });
558 self.live_tasks
559 .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
560 (n < MAX_RUNNING_TASKS as u64).then_some(n + 1)
561 })
562 .map_err(|_| {
563 anyhow::anyhow!(
564 "concurrency limit exceeded: maximum of {MAX_RUNNING_TASKS} running background tasks allowed"
565 )
566 })?;
567 let id = self.next_task_id.fetch_add(1, Ordering::SeqCst);
568 self.sweep_finished_tasks();
569 Ok(id)
570 }
571
572 /// Drop finished entries past `MAX_RETAINED_FINISHED`, oldest
573 /// first. Finished means a terminal phase or a completed join;
574 /// `Awaiting` entries always survive (a waiter is rendezvousing)
575 /// and running entries are never touched. Evicted ids read as
576 /// unknown/already-awaited afterwards, like an awaited task.
577 fn sweep_finished_tasks(&self) {
578 let mut finished: Vec<u64> = Vec::new();
579 {
580 let named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
581 for (id, entry) in named.iter() {
582 // `is_live` already exempts awaiting entries: a waiter
583 // is rendezvousing on them.
584 if !entry.is_live() {
585 finished.push(*id);
586 }
587 }
588 }
589 if finished.len() <= MAX_RETAINED_FINISHED {
590 return;
591 }
592 finished.sort_unstable();
593 let mut named = self.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
594 for id in finished.iter().take(finished.len() - MAX_RETAINED_FINISHED) {
595 named.remove(id);
596 }
597 }
598
599 /// Fork the execution state for a child thread. The child gets:
600 /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
601 /// - Cloned envs, cwd, cargo scratch name, var_scopes
602 /// - Fresh bg_children, scope_stack (empty -- child manages its own)
603 /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
604 /// - Cloned io configuration
605 /// - Independent cancel_token, active_process (child manages its own)
606 /// - Shared named_tasks and next_task_id (via Arc clone)
607 #[allow(dead_code)]
608 pub(super) fn fork(&self) -> Self {
609 Self {
610 fs: self.fs.clone_box(),
611 cargo_scratch: self.cargo_scratch.clone(),
612 seed: Arc::clone(&self.seed),
613 cwd: self.cwd.clone(),
614 envs: Arc::clone(&self.envs),
615 bg_children: Vec::new(),
616 scope_stack: Vec::new(),
617 isolated_stack: self.isolated_stack.clone(),
618 io: self.io.clone(),
619 assert_windows: Arc::clone(&self.assert_windows),
620 assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
621 exact_stdout: Arc::clone(&self.exact_stdout),
622 var_scopes: self.var_scopes.clone(),
623 cancel_token: Arc::new(AtomicBool::new(false)),
624 // Fresh cancellation, inherited telemetry: the fork's
625 // workers still attribute to the originating run.
626 cancel_hub: Arc::new(CancelHub::with_counter(self.cancel_hub.worker_counter())),
627 active_process: Arc::new(Mutex::new(None)),
628 named_tasks: Arc::clone(&self.named_tasks),
629 next_task_id: Arc::clone(&self.next_task_id),
630 // Shared live count, never reset: nested workers report into
631 // the same cap their spawner was admitted under.
632 live_tasks: Arc::clone(&self.live_tasks),
633 inside_async: true,
634 keeper_expiry: None,
635 cancellable: self.cancellable,
636 functions: self.functions.clone(),
637 types: self.types.clone(),
638 record_schemas: self.record_schemas.clone(),
639 module_states: self.module_states.clone(),
640 type_aliases: self.type_aliases.clone(),
641 call_depth: self.call_depth,
642 task_id: self.task_id,
643 // Forks start with an empty manifest: async children record
644 // their own executions; the guest packs the root manifest.
645 push_manifest: Vec::new(),
646 _marker: PhantomData,
647 }
648 }
649
650 /// Whether `pipe` may promote to an OS kernel pair on behalf of
651 /// `task_id`: only when it was declared by that same task and no
652 /// spawned child can observe it. Anything else stays script-backed, so
653 /// concurrent tasks can never disagree about EOF propagation.
654 /// Spawning tasks pass their worker id (not the spawner's): promotion
655 /// is judged from the worker's perspective, since it is the worker's
656 /// bindings that will hold raw descriptors.
657 pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
658 pipe.declaring_task() == task_id && !pipe.has_escaped()
659 }
660
661 /// Whether `pipe` may promote on the current thread (main flow and
662 /// inline resolves).
663 pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
664 Self::can_promote_in_task(pipe, self.task_id)
665 }
666
667 /// Mark every pipe visible in scope as shared-with-a-child. Called
668 /// synchronously on the spawner before a worker thread starts: forking
669 /// copies the whole environment, so every visible pipe is capturable
670 /// whether or not the child body names it. Over-marking only costs
671 /// zero-copy opportunities, never correctness.
672 pub(super) fn mark_captured_pipes_escaped(&self) {
673 for scope in self.var_scopes.iter() {
674 for (_, value) in scope.values() {
675 mark_value_pipes_escaped(value);
676 }
677 }
678 }
679
680 pub(super) fn push_var_scope(&mut self) {
681 self.var_scopes.push(HashMap::new());
682 }
683
684 pub(super) fn pop_var_scope(&mut self) {
685 self.var_scopes.pop();
686 }
687
688 /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
689 /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
690 /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
691 /// Function definitions scope through the registry's own frames.
692 pub(super) fn push_scope(&mut self) {
693 self.scope_stack.push(ScopeSnapshot {
694 cwd: self.cwd.clone(),
695 root: self.fs.root().clone(),
696 envs: Arc::clone(&self.envs),
697 });
698 self.functions.push_scope();
699 self.push_var_scope();
700 }
701
702 /// Exit a lexical scope, restoring everything `push_scope` saved.
703 pub(super) fn pop_scope(&mut self) -> Result<()> {
704 let snapshot = self
705 .scope_stack
706 .pop()
707 .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
708 self.fs.set_root(&snapshot.root);
709 self.cwd = snapshot.cwd;
710 self.envs = snapshot.envs;
711 self.functions.pop_scope();
712 self.pop_var_scope();
713 Ok(())
714 }
715 pub(super) fn declare_var(&mut self, key: String, kind: TypeTag, value: Value) -> Result<()> {
716 if self
717 .var_scopes
718 .last()
719 .map(|s| s.contains_key(&key))
720 .unwrap_or(false)
721 {
722 anyhow::bail!(
723 "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
724 key,
725 key
726 );
727 }
728 let coerced = super::args::coerce_value(value, &kind)?;
729 let scope = self
730 .var_scopes
731 .last_mut()
732 .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
733 scope.insert(key, (kind, coerced));
734 Ok(())
735 }
736
737 pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
738 let kind = self
739 .var_scopes
740 .iter()
741 .rev()
742 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
743 .ok_or_else(|| {
744 anyhow::anyhow!(
745 "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
746 )
747 })?;
748 let coerced = super::args::coerce_value(value, &kind)?;
749 for scope in self.var_scopes.iter_mut().rev() {
750 if let Some(slot) = scope.get_mut(key) {
751 slot.1 = coerced;
752 return Ok(());
753 }
754 }
755 anyhow::bail!("undeclared variable ${key}");
756 }
757
758 /// Append `item` to the LIST binding `key` in place. Copy-on-write:
759 /// the buffer detaches only when shared, so aliases keep their
760 /// contents; the sole owner mutates with no copy. Bails for
761 /// undeclared names and non-list bindings. Shaped lists validate
762 /// the item against the element tag, so a push can never silently
763 /// corrupt the shape the declaration promises.
764 pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
765 let kind = self
766 .var_scopes
767 .iter()
768 .rev()
769 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
770 .ok_or_else(|| {
771 anyhow::anyhow!(
772 "undeclared variable ${key}: declare it first with LET ${key}: LIST<...> = ..."
773 )
774 })?;
775 let element = match kind {
776 TypeTag::List => None,
777 TypeTag::ListOf(element) => Some(element.as_ref().clone()),
778 _ => {
779 anyhow::bail!("LIST_APPEND ${key}: variable is {}, not LIST", kind.name());
780 }
781 };
782 for scope in self.var_scopes.iter_mut().rev() {
783 if let Some(slot) = scope.get_mut(key) {
784 let list = slot.1.as_list_mut().ok_or_else(|| {
785 anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
786 })?;
787 if let Some(expected) = element {
788 oxdock_parser::check_value_at(
789 &expected,
790 &item,
791 &format!("${key}[{}]", list.len()),
792 )?;
793 }
794 list.push(item);
795 return Ok(());
796 }
797 }
798 anyhow::bail!("undeclared variable ${key}");
799 }
800
801 pub(super) fn get_var(&self, key: &str) -> Option<Value> {
802 // Walk scopes from innermost to outermost
803 for scope in self.var_scopes.iter().rev() {
804 if let Some((_, value)) = scope.get(key) {
805 return Some(value.clone());
806 }
807 }
808 None
809 }
810
811 pub(super) fn get_var_typed(&self, key: &str) -> Option<(TypeTag, Value)> {
812 for scope in self.var_scopes.iter().rev() {
813 if let Some(entry) = scope.get(key) {
814 return Some(entry.clone());
815 }
816 }
817 None
818 }
819
820 /// Get a flattened view of all variables across all scopes.
821 /// Inner scopes take precedence over outer scopes.
822 pub(super) fn all_vars(&self) -> HashMap<String, Value> {
823 let mut result = HashMap::new();
824 for scope in self.var_scopes.iter().rev() {
825 for (k, (_, v)) in scope {
826 result.entry(k.clone()).or_insert_with(|| v.clone());
827 }
828 }
829 result
830 }
831}
832
833/// Mark every pipe handle reachable from `value` as shared-with-a-child.
834/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
835/// shallow top-level check would miss them and let a later promotion
836/// corrupt the shared EOF contract. Values form a tree, so recursion
837/// terminates; host-opaque payloads cannot carry handles.
838fn mark_value_pipes_escaped(value: &Value) {
839 if let Some(handle) = value.as_pipe_handle() {
840 handle.mark_escaped();
841 return;
842 }
843 if let Some(items) = value.as_list() {
844 for item in items {
845 mark_value_pipes_escaped(item);
846 }
847 }
848 if let Some(entries) = value.as_map() {
849 for item in entries.values() {
850 mark_value_pipes_escaped(item);
851 }
852 }
853}