oxdock_core/exec/state.rs
1use std::collections::HashMap;
2use std::marker::PhantomData;
3use std::sync::atomic::{AtomicBool, AtomicU64};
4use std::sync::{Arc, Condvar, Mutex};
5
6use anyhow::Result;
7use oxdock_fs::{CargoScratch, GuardedPath, WorkspaceFs};
8use oxdock_parser::{Step, TypeDescriptor, Value};
9use oxdock_process::{BackgroundHandle, CommandContext, ProcessManager};
10
11use super::io::{ExactCapture, ExecIo, SlidingWindow};
12use super::native::FunctionRegistry;
13use oxdock_pipe::KeeperGuard;
14
15/// Maximum nested function-call depth. Guards the host thread stack against
16/// runaway recursion; the error names the function that overflowed.
17pub(super) const MAX_CALL_DEPTH: usize = 64;
18
19/// Execution state for one script run. Public so hosts can register
20/// functions and introspect listings; all fields stay crate-private so the
21/// scope, recursion-budget, and task invariants cannot be broken from outside.
22pub struct ExecState<P: ProcessManager> {
23 pub(super) fs: Box<dyn WorkspaceFs>,
24 /// Pre-reserved guarded scratch name for `CARGO_TARGET_DIR` (issue #131).
25 /// Opaque [`CargoScratch`]: renderable for the child environment but not
26 /// nameable as a `&GuardedPath`, so host code cannot `ensure()` or
27 /// `create_dir_all` it. The child `cargo` creates it on demand.
28 pub(super) cargo_scratch: CargoScratch,
29 pub(super) cwd: GuardedPath,
30 pub(super) envs: Arc<HashMap<String, String>>,
31 pub(super) bg_children: Vec<Box<dyn BackgroundHandle>>,
32 pub(super) scope_stack: Vec<ScopeSnapshot>,
33 pub(super) io: ExecIo,
34 /// Pre-registered SlidingWindow observers for stream assertion steps.
35 /// Keyed by (generation, step index). TeeWriter pushes every chunk to all windows.
36 pub(super) assert_windows: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
37 /// Same observer map fed by the stderr tee for `ASSERT_CONTAINS stderr`.
38 pub(super) assert_windows_stderr: Arc<Mutex<HashMap<(usize, usize), SlidingWindow>>>,
39 /// Exact-match stdout accumulators for `ASSERT_EQ stdout`, keyed by
40 /// generation and fed by the same tee. Entries allocated during
41 /// pre-registration observe bytes from scope entry; the common
42 /// top-level case therefore sees trial-cumulative output.
43 pub(super) exact_stdout: Arc<Mutex<HashMap<usize, ExactCapture>>>,
44 /// Variable scopes for $variable bindings (FOR loops, LET assignments).
45 /// Innermost scope is last. Variables are looked up from innermost to outermost.
46 /// Each entry carries its declared type name alongside the value.
47 pub(super) var_scopes: Vec<HashMap<String, (String, Value)>>,
48 /// Name directory for type resolution: startup descriptors plus the
49 /// run's host descriptors. Words carry their own vtables, so this map
50 /// serves only name queries (declarations, `TYPES()`, `TYPE_DESCRIBE`).
51 pub(super) types: HashMap<String, &'static TypeDescriptor>,
52 /// Cancellation token for background thread teardown.
53 #[allow(dead_code)]
54 pub(super) cancel_token: Arc<AtomicBool>,
55 /// Handle to the currently executing foreground OS process, so
56 /// ThreadJoinHandle::kill() can interrupt a blocking wait().
57 #[allow(dead_code)]
58 pub(super) active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
59 /// Named task registry for AWAIT/CANCEL support. Shared across subscopes
60 /// via Arc. Each entry is a synchronized state machine (`TaskEntry`):
61 /// the handle lives inside the entry so `CANCEL` can synchronously tear
62 /// down a task even while a concurrent `AWAIT` is waiting on it.
63 /// Entries are retained as `Cancelled`/`Completed` tombstones so later
64 /// `AWAIT`/`CANCEL` report precise errors instead of `TaskNotFound`.
65 #[allow(dead_code)]
66 pub(super) named_tasks: Arc<Mutex<HashMap<u64, Arc<TaskEntry>>>>,
67 /// Counter for generating unique task IDs. Shared across subscopes via Arc.
68 #[allow(dead_code)]
69 pub(super) next_task_id: Arc<AtomicU64>,
70 /// Whether we're inside an ASYNC block thread. When true, `handlers::run()`
71 /// spawns in background mode so the handle can be registered for cancellation.
72 pub(super) inside_async: bool,
73 /// Step-indexed keeper expiry for one `ASYNC` worker. Each guard pins a
74 /// pipe the worker produces to, bridging the spawn-to-first-attach
75 /// window and every transient gap between producer steps. Guards keyed
76 /// to step `k` drop when the worker completes its top-level step `k`
77 /// (matched by slice identity, so nested bodies never discharge them);
78 /// leftovers drop with the worker thread. Always `None` outside
79 /// workers; `fork` never inherits it.
80 pub(super) keeper_expiry: Option<KeeperExpiry>,
81 /// Whether `handlers::run()` must spawn in background mode so the handle
82 /// registers in `active_process` for cancellation. Set while a `TIMEOUT`
83 /// body executes on the current thread so the deadline watcher can kill
84 /// a blocking foreground process. Unlike `inside_async`, this does not
85 /// affect end-of-pipeline named-task reaping.
86 pub(super) cancellable: bool,
87 /// The single function registry: DSL `FUNC` definitions, builtins, and
88 /// host extensions. Script entries scope lexically through the
89 /// registry's own frames (managed by `push_scope`/`pop_scope`);
90 /// native entries persist. Shared across `fork()` via clone.
91 pub(super) functions: FunctionRegistry<P>,
92 /// Current nested function-call depth on this thread. Enforced against
93 /// `MAX_CALL_DEPTH`; cloned (not reset) by `fork()` so async children
94 /// inherit the caller's depth budget.
95 pub(super) call_depth: usize,
96 /// Identity of the task this state executes (`0` = root flow).
97 /// Stamped onto pipe handles minted here and compared by the promotion
98 /// check: only the declaring task may promote its own pipes.
99 pub(super) task_id: u64,
100 /// Declared `--to-host` transfers recorded strictly at execution time:
101 /// each executed flagged `COPY` appends its evaluated
102 /// `(guest_src, host_dst)` pair. The guest serve loop packs exactly
103 /// these entries, so dead branches contribute nothing and dynamic
104 /// paths (`$var`, `{{ ... }}`) resolve normally. Shared with the sink
105 /// in [`ExecIo`] when staged.
106 pub(super) push_manifest: Vec<(String, String)>,
107 pub(super) _marker: PhantomData<P>,
108}
109
110pub(super) struct ScopeSnapshot {
111 pub(super) cwd: GuardedPath,
112 pub(super) root: GuardedPath,
113 pub(super) envs: Arc<HashMap<String, String>>,
114}
115
116/// Lifecycle phase of a named background task (`LET $var: HANDLE = ASYNC ...`).
117/// `Running` and `Awaiting` both hold the live handle inside the entry;
118/// `Cancelled` and `Completed` are terminal tombstones with no handle.
119pub(super) enum TaskPhase {
120 Running,
121 Awaiting,
122 Cancelled,
123 Completed,
124}
125
126pub(super) struct TaskEntryState {
127 pub(super) phase: TaskPhase,
128 pub(super) handle: Option<Box<dyn BackgroundHandle>>,
129 /// True once the handle has been consumed and its thread joined
130 /// (`kill()` for cancellations, `try_wait`-reap for natural completion).
131 /// Threads observing `Cancelled` must wait on `done` until `reaped`
132 /// before resuming, so no caller outruns OS process teardown.
133 pub(super) reaped: bool,
134 /// Explicit result of a background task, published by `RETURN` (block
135 /// bodies) or the function call itself (single-`CALL` bodies). Set
136 /// under the entry lock before `done.notify_all()`; read by
137 /// `LET $o: TYPE = AWAIT $t`. `None` for tasks that returned nothing
138 /// or have not finished. Task stdout is never captured: it streams
139 /// live to the shared parent writer.
140 pub(super) return_value: Option<Value>,
141 /// Whether this task's body can publish a value: single-`CALL` bodies
142 /// always can; block bodies can iff they contain a `RETURN` in their
143 /// own scope. A task that can return but falls off the end fails its
144 /// capture loudly; a task that cannot return yields `INT` 0.
145 pub(super) returns_value: bool,
146}
147
148/// Synchronized named-task entry shared by every scope that can observe the
149/// task (`AWAIT`, `CANCEL`, end-poll reaping). Exactly one thread ever takes
150/// the handle and performs teardown; all other observers rendezvous on
151/// `done`/`reaped`.
152pub(super) struct TaskEntry {
153 pub(super) state: Mutex<TaskEntryState>,
154 pub(super) done: Condvar,
155}
156
157impl TaskEntry {
158 pub(super) fn new(handle: Box<dyn BackgroundHandle>, returns_value: bool) -> Self {
159 Self {
160 state: Mutex::new(TaskEntryState {
161 phase: TaskPhase::Running,
162 handle: Some(handle),
163 reaped: false,
164 return_value: None,
165 returns_value,
166 }),
167 done: Condvar::new(),
168 }
169 }
170
171 /// Block until the teardown owner has consumed the handle and joined
172 /// the task thread. Lock-free for callers except the wait itself.
173 pub(super) fn wait_reaped(&self) {
174 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
175 while !guard.reaped {
176 guard = self.done.wait(guard).unwrap_or_else(|e| e.into_inner());
177 }
178 }
179
180 /// Mark teardown complete and wake every rendezvous waiter.
181 pub(super) fn finish_teardown(&self) {
182 {
183 let mut guard = self.state.lock().unwrap_or_else(|e| e.into_inner());
184 guard.handle = None;
185 guard.reaped = true;
186 }
187 self.done.notify_all();
188 }
189}
190
191/// Step-indexed keeper expiry for one `ASYNC` worker thread. Guards are
192/// keyed by the top-level body index of the final producer step for each
193/// pipe: dropping the guards for step `k` once it completes keeps the
194/// pipe open across every transient gap between producers, then releases
195/// it so later consumer steps in the same task observe EOF.
196///
197/// Slice identity (`body_addr`/`body_len`) gates discharge: nested bodies
198/// (`FOR`/`IF`/`TIMEOUT`/inner `ASYNC`) execute through the same stepping
199/// code with different slices and must never consume the worker's
200/// top-level map.
201pub(super) struct KeeperExpiry {
202 body_addr: usize,
203 body_len: usize,
204 map: HashMap<usize, Vec<KeeperGuard>>,
205}
206
207impl KeeperExpiry {
208 pub(super) fn new(steps: &[Step], map: HashMap<usize, Vec<KeeperGuard>>) -> Self {
209 Self {
210 body_addr: steps.as_ptr() as usize,
211 body_len: steps.len(),
212 map,
213 }
214 }
215
216 pub(super) fn matches(&self, steps: &[Step]) -> bool {
217 self.body_addr == steps.as_ptr() as usize && self.body_len == steps.len()
218 }
219
220 /// Drop the guards expiring at top-level step `idx`. Returns true when
221 /// the map is drained and the expiry itself can be cleared.
222 pub(super) fn expire_step(&mut self, steps: &[Step], idx: usize) -> bool {
223 if self.matches(steps) {
224 drop(self.map.remove(&idx));
225 }
226 self.map.is_empty()
227 }
228}
229
230impl<P: ProcessManager> ExecState<P> {
231 pub(super) fn command_ctx(&self) -> Result<CommandContext> {
232 // Resolve the working directory through the snapshot choke point: a
233 // snapshot-rooted cwd materializes here (so `RUN` executes against a
234 // real directory) while a local cwd resolves purely lexically with
235 // zero I/O. `CARGO_TARGET_DIR` is the pre-reserved scratch name (never
236 // ensured by us); callers may still override it via the env map, which
237 // apply_ctx respects when spawning processes.
238 let cwd = self.fs.resolve_write(&self.cwd, ".")?;
239 Ok(CommandContext::new(
240 &cwd.into(),
241 Arc::clone(&self.envs),
242 &self.cargo_scratch,
243 self.fs.root(),
244 self.fs.build_context(),
245 ))
246 }
247
248 /// Fork the execution state for a child thread. The child gets:
249 /// - A cloned filesystem handle (shared snapshot backing, independent root selection)
250 /// - Cloned envs, cwd, cargo scratch name, var_scopes
251 /// - Fresh bg_children, scope_stack (empty -- child manages its own)
252 /// - Shared assert_windows, assert_windows_stderr, exact_stdout (Arc clones)
253 /// - Cloned io configuration
254 /// - Independent cancel_token, active_process (child manages its own)
255 /// - Shared named_tasks and next_task_id (via Arc clone)
256 #[allow(dead_code)]
257 pub(super) fn fork(&self) -> Self {
258 Self {
259 fs: self.fs.clone_box(),
260 cargo_scratch: self.cargo_scratch.clone(),
261 cwd: self.cwd.clone(),
262 envs: Arc::clone(&self.envs),
263 bg_children: Vec::new(),
264 scope_stack: Vec::new(),
265 io: self.io.clone(),
266 assert_windows: Arc::clone(&self.assert_windows),
267 assert_windows_stderr: Arc::clone(&self.assert_windows_stderr),
268 exact_stdout: Arc::clone(&self.exact_stdout),
269 var_scopes: self.var_scopes.clone(),
270 cancel_token: Arc::new(AtomicBool::new(false)),
271 active_process: Arc::new(Mutex::new(None)),
272 named_tasks: Arc::clone(&self.named_tasks),
273 next_task_id: Arc::clone(&self.next_task_id),
274 inside_async: true,
275 keeper_expiry: None,
276 cancellable: self.cancellable,
277 functions: self.functions.clone(),
278 types: self.types.clone(),
279 call_depth: self.call_depth,
280 task_id: self.task_id,
281 // Forks start with an empty manifest: async children record
282 // their own executions; the guest packs the root manifest.
283 push_manifest: Vec::new(),
284 _marker: PhantomData,
285 }
286 }
287
288 /// Whether `pipe` may promote to an OS kernel pair on behalf of
289 /// `task_id`: only when it was declared by that same task and no
290 /// spawned child can observe it. Anything else stays script-backed, so
291 /// concurrent tasks can never disagree about EOF propagation.
292 /// Spawning tasks pass their worker id (not the spawner's): promotion
293 /// is judged from the worker's perspective, since it is the worker's
294 /// bindings that will hold raw descriptors.
295 pub(super) fn can_promote_in_task(pipe: &oxdock_pipe::PipeHandle, task_id: u64) -> bool {
296 pipe.declaring_task() == task_id && !pipe.has_escaped()
297 }
298
299 /// Whether `pipe` may promote on the current thread (main flow and
300 /// inline resolves).
301 pub(super) fn can_promote_to_os(&self, pipe: &oxdock_pipe::PipeHandle) -> bool {
302 Self::can_promote_in_task(pipe, self.task_id)
303 }
304
305 /// Mark every pipe visible in scope as shared-with-a-child. Called
306 /// synchronously on the spawner before a worker thread starts: forking
307 /// copies the whole environment, so every visible pipe is capturable
308 /// whether or not the child body names it. Over-marking only costs
309 /// zero-copy opportunities, never correctness.
310 pub(super) fn mark_captured_pipes_escaped(&self) {
311 for scope in self.var_scopes.iter() {
312 for (_, value) in scope.values() {
313 mark_value_pipes_escaped(value);
314 }
315 }
316 }
317
318 pub(super) fn push_var_scope(&mut self) {
319 self.var_scopes.push(HashMap::new());
320 }
321
322 pub(super) fn pop_var_scope(&mut self) {
323 self.var_scopes.pop();
324 }
325
326 /// Enter a lexical scope: snapshot cwd/root/envs and open a fresh
327 /// variable scope. Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE);
328 /// only pipes (ExecIo) and filesystem effects cross scope boundaries.
329 /// Function definitions scope through the registry's own frames.
330 pub(super) fn push_scope(&mut self) {
331 self.scope_stack.push(ScopeSnapshot {
332 cwd: self.cwd.clone(),
333 root: self.fs.root().clone(),
334 envs: Arc::clone(&self.envs),
335 });
336 self.functions.push_scope();
337 self.push_var_scope();
338 }
339
340 /// Exit a lexical scope, restoring everything `push_scope` saved.
341 pub(super) fn pop_scope(&mut self) -> Result<()> {
342 let snapshot = self
343 .scope_stack
344 .pop()
345 .ok_or_else(|| anyhow::anyhow!("scope stack underflow during pop"))?;
346 self.fs.set_root(&snapshot.root);
347 self.cwd = snapshot.cwd;
348 self.envs = snapshot.envs;
349 self.functions.pop_scope();
350 self.pop_var_scope();
351 Ok(())
352 }
353 pub(super) fn declare_var(&mut self, key: String, kind: String, value: Value) -> Result<()> {
354 if self
355 .var_scopes
356 .last()
357 .map(|s| s.contains_key(&key))
358 .unwrap_or(false)
359 {
360 anyhow::bail!(
361 "redeclaration error: ${} already declared in this scope; use ${} = ... to mutate",
362 key,
363 key
364 );
365 }
366 let coerced = super::args::coerce_value(value, &kind, &*self)?;
367 let scope = self
368 .var_scopes
369 .last_mut()
370 .ok_or_else(|| anyhow::anyhow!("no variable scope for declaration"))?;
371 scope.insert(key, (kind, coerced));
372 Ok(())
373 }
374
375 pub(super) fn mutate_var(&mut self, key: &str, value: Value) -> Result<()> {
376 let kind = self
377 .var_scopes
378 .iter()
379 .rev()
380 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
381 .ok_or_else(|| {
382 anyhow::anyhow!(
383 "undeclared variable ${key}: declare it first with LET ${key}: TYPE = ..."
384 )
385 })?;
386 let coerced = super::args::coerce_value(value, &kind, &*self)?;
387 for scope in self.var_scopes.iter_mut().rev() {
388 if let Some(slot) = scope.get_mut(key) {
389 slot.1 = coerced;
390 return Ok(());
391 }
392 }
393 anyhow::bail!("undeclared variable ${key}");
394 }
395
396 /// Append `item` to the LIST binding `key` in place. Copy-on-write:
397 /// the buffer detaches only when shared, so aliases keep their
398 /// contents; the sole owner mutates with no copy. Bails for
399 /// undeclared names and non-LIST bindings.
400 pub(super) fn push_into_list(&mut self, key: &str, item: Value) -> Result<()> {
401 let kind = self
402 .var_scopes
403 .iter()
404 .rev()
405 .find_map(|s| s.get(key).map(|(k, _)| k.clone()))
406 .ok_or_else(|| {
407 anyhow::anyhow!(
408 "undeclared variable ${key}: declare it first with LET ${key}: LIST = ..."
409 )
410 })?;
411 if kind != "LIST" {
412 anyhow::bail!("LIST_APPEND ${key}: variable is {kind}, not LIST");
413 }
414 for scope in self.var_scopes.iter_mut().rev() {
415 if let Some(slot) = scope.get_mut(key) {
416 let list = slot.1.as_list_mut().ok_or_else(|| {
417 anyhow::anyhow!("LIST_APPEND ${key}: variable is not a LIST value")
418 })?;
419 list.push(item);
420 return Ok(());
421 }
422 }
423 anyhow::bail!("undeclared variable ${key}");
424 }
425
426 pub(super) fn get_var(&self, key: &str) -> Option<Value> {
427 // Walk scopes from innermost to outermost
428 for scope in self.var_scopes.iter().rev() {
429 if let Some((_, value)) = scope.get(key) {
430 return Some(value.clone());
431 }
432 }
433 None
434 }
435
436 pub(super) fn get_var_typed(&self, key: &str) -> Option<(String, Value)> {
437 for scope in self.var_scopes.iter().rev() {
438 if let Some(entry) = scope.get(key) {
439 return Some(entry.clone());
440 }
441 }
442 None
443 }
444
445 /// Get a flattened view of all variables across all scopes.
446 /// Inner scopes take precedence over outer scopes.
447 pub(super) fn all_vars(&self) -> HashMap<String, Value> {
448 let mut result = HashMap::new();
449 for scope in self.var_scopes.iter().rev() {
450 for (k, (_, v)) in scope {
451 result.entry(k.clone()).or_insert_with(|| v.clone());
452 }
453 }
454 result
455 }
456}
457
458/// Mark every pipe handle reachable from `value` as shared-with-a-child.
459/// Pipes travel inside lists and maps (`LET $bag: LIST = [$p]`), so a
460/// shallow top-level check would miss them and let a later promotion
461/// corrupt the shared EOF contract. Values form a tree, so recursion
462/// terminates; host-opaque payloads cannot carry handles.
463fn mark_value_pipes_escaped(value: &Value) {
464 if let Some(handle) = value.as_pipe_handle() {
465 handle.mark_escaped();
466 return;
467 }
468 if let Some(items) = value.as_list() {
469 for item in items {
470 mark_value_pipes_escaped(item);
471 }
472 }
473 if let Some(entries) = value.as_map() {
474 for item in entries.values() {
475 mark_value_pipes_escaped(item);
476 }
477 }
478}