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