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