Skip to main content

oxdock_core/exec/
steps.rs

1use std::collections::HashMap;
2use std::process::ExitStatus;
3use std::sync::Arc;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6
7use anyhow::{Result, bail};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{Arg, AssertTarget, Step, StepKind, Value, guard_option_allows};
10use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
11
12/// Create an ExitStatus from a raw exit code. Cross-platform.
13fn exit_status_from_code(code: i32) -> ExitStatus {
14    #[cfg(unix)]
15    {
16        use std::os::unix::process::ExitStatusExt;
17        ExitStatus::from_raw(code << 8)
18    }
19    #[cfg(windows)]
20    {
21        use std::os::windows::process::ExitStatusExt;
22        ExitStatus::from_raw(code as u32)
23    }
24}
25
26use super::handlers;
27use super::io::{ExactCapture, SlidingWindow, StreamHandle};
28use super::native::PureTable;
29use super::state::{ExecState, TaskEntry, TaskPhase};
30use oxdock_pipe::PipeInner;
31
32/// A background handle wrapping a `std::thread::JoinHandle` for ASYNC blocks
33/// that execute commands in a background thread.
34pub(super) struct ThreadJoinHandle {
35    join: Option<std::thread::JoinHandle<Result<()>>>,
36    cancel_token: Arc<AtomicBool>,
37    active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
38    /// Identity of the worker thread, published by the child on entry.
39    /// Forked worker state shares the parent task registry via `Arc`, so a
40    /// parent that errors out can drop its registry reference while the
41    /// worker is still alive. The worker then becomes the last registry
42    /// owner and would drop (and join) its own handle on thread exit, which
43    /// is undefined behavior (`pthread_join` on self). Detect that case and
44    /// detach instead of joining.
45    worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
46    /// Preserved error from the child thread, if any.
47    thread_error: Option<anyhow::Error>,
48    /// `EXIT` code from the child thread, if it exited. anyhow errors do
49    /// not cross the join boundary by value, and the re-emit below would
50    /// otherwise flatten the typed request into a plain string.
51    thread_exit_code: Option<i64>,
52}
53
54impl ThreadJoinHandle {
55    pub(super) fn new(
56        join: std::thread::JoinHandle<Result<()>>,
57        cancel_token: Arc<AtomicBool>,
58        active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
59        worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
60    ) -> Self {
61        Self {
62            join: Some(join),
63            cancel_token,
64            active_process,
65            worker,
66            thread_error: None,
67            thread_exit_code: None,
68        }
69    }
70
71    /// Re-emit the preserved thread error. `anyhow` errors do not cross
72    /// the join boundary by value, so an EXIT code rides alongside in
73    /// `thread_exit_code` and is re-attached here as a typed request
74    /// under the flattened message: the text stays identical, and the
75    /// code stays machine readable.
76    fn reemit_error(&self) -> anyhow::Error {
77        let msg = self
78            .thread_error
79            .as_ref()
80            .map(|err| format!("{err:#}"))
81            .unwrap_or_else(|| "background thread failed without an error".to_string());
82        match self.thread_exit_code {
83            Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
84            None => anyhow::anyhow!("{msg}"),
85        }
86    }
87
88    /// Whether the caller is the worker thread owned by this handle.
89    fn is_self(&self) -> bool {
90        let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
91        guard.is_some_and(|id| id == std::thread::current().id())
92    }
93
94    /// Reap the thread if finished, preserving any error.
95    fn reap(&mut self) {
96        if self.join.is_none() {
97            return;
98        }
99        if self.is_self() {
100            // The worker is dropping the last registry reference on its own
101            // exit path (parent already tore down or errored out). Detach
102            // instead of joining self, which is undefined behavior.
103            let _ = self.join.take();
104            return;
105        }
106        let handle = self.join.take().unwrap();
107        match handle.join() {
108            Ok(Ok(())) => {}
109            Ok(Err(e)) => {
110                self.thread_exit_code = super::exit::exit_code_of(&e);
111                self.thread_error = Some(e);
112            }
113            Err(panic) => {
114                let msg = if let Some(s) = panic.downcast_ref::<&str>() {
115                    s.to_string()
116                } else if let Some(s) = panic.downcast_ref::<String>() {
117                    s.clone()
118                } else {
119                    "thread panicked".to_string()
120                };
121                self.thread_error = Some(anyhow::anyhow!("{msg}"));
122            }
123        }
124    }
125}
126
127impl BackgroundHandle for ThreadJoinHandle {
128    fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
129        if let Some(join) = &self.join {
130            if join.is_finished() {
131                self.reap();
132            } else {
133                return Ok(None);
134            }
135        }
136        // anyhow::Error is not Clone and this method may run repeatedly,
137        // so the preserved error is re-emitted rather than moved. The
138        // alternate display (`{err:#}`) flattens the full causal chain
139        // into the new message: `{err}` alone would drop every
140        // `Caused by` layer at the ASYNC task boundary.
141        if self.thread_error.is_some() {
142            Err(self.reemit_error())
143        } else {
144            Ok(Some(exit_status_from_code(0)))
145        }
146    }
147
148    fn kill(&mut self) -> Result<()> {
149        // Signal cancellation
150        self.cancel_token.store(true, Ordering::SeqCst);
151        // Kill any active OS process to interrupt blocking wait
152        if let Ok(mut guard) = self.active_process.lock()
153            && let Some(ref mut proc) = *guard
154        {
155            let _ = proc.kill();
156        }
157        // Join the thread to ensure it completes before returning
158        self.reap();
159        Ok(())
160    }
161
162    fn wait(&mut self) -> Result<ExitStatus> {
163        self.reap();
164        // Same chain-preserving re-emit as `try_wait` above.
165        if self.thread_error.is_some() {
166            Err(self.reemit_error())
167        } else {
168            Ok(exit_status_from_code(0))
169        }
170    }
171}
172
173impl Drop for ThreadJoinHandle {
174    fn drop(&mut self) {
175        let _ = self.kill();
176    }
177}
178
179/// Monotonically increasing generation counter for assert_windows key scoping.
180/// Each execute_steps invocation gets a unique generation, preventing key
181/// collisions between nested scopes (for_loop bodies, WithIo blocks).
182static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
183
184/// Intra-thread control-flow signal (`BREAK`/`CONTINUE`/`RETURN`).
185/// Produced by steps, consumed by the nearest loop (`Break`/`Continue`) or
186/// `call_func` (`Return`). Anything reaching a thread boundary (`ASYNC`
187/// spawn, `await` reaping) or the pipeline top becomes a step-numbered
188/// error. `idx` is the 0-based index of the originating step in its own
189/// body, so boundary errors can name it.
190#[derive(Debug)]
191pub(super) enum Flow {
192    Done,
193    Break { idx: usize },
194    Continue { idx: usize },
195    Return { idx: usize, value: Value },
196}
197
198pub(super) fn allocate_assert_generation() -> usize {
199    ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
200}
201
202/// Which stream a stream-targeted assertion observes.
203#[derive(Clone, Copy, PartialEq, Eq)]
204pub(super) enum AssertStream {
205    Stdout,
206    Stderr,
207}
208
209/// Extract the substring needle from a step asserting over a stream:
210/// `ASSERT_CONTAINS stdout|stderr`, handling both top-level and
211/// WITH_IO-wrapped variants. Returns the observed stream and the needle.
212fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
213    let step = match kind {
214        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
215        other => other,
216    };
217    match step {
218        StepKind::AssertContains { haystack, needle } => match haystack {
219            AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
220            AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
221            _ => None,
222        },
223        _ => None,
224    }
225}
226
227/// Whether the step needs the exact-match stdout accumulator:
228/// `ASSERT_EQ stdout`, top-level or WITH_IO-wrapped.
229fn needs_exact_stdout(kind: &StepKind) -> bool {
230    let step = match kind {
231        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
232        other => other,
233    };
234    matches!(
235        step,
236        StepKind::AssertEq {
237            actual: AssertTarget::Stdout,
238            ..
239        }
240    )
241}
242
243/// An assertion first argument evaluated far enough to check:
244/// values stay typed, streams stay references to live buffers.
245pub(super) enum ResolvedAssertTarget {
246    Value(Value),
247    Stdout,
248    Stderr,
249    Pipe(Vec<u8>),
250}
251
252/// Evaluate an assertion target. `Arg::Expr` evaluates typed;
253/// strings, templates, and parts render to `String`; stream markers
254/// resolve to live buffers (peeked, never consumed). A `$var` holding a
255/// `PIPE` likewise peeks its backend bytes: lowering cannot know variable
256/// types, so the pipe dispatch lives here where the value exists.
257pub(super) fn resolve_assert_target<P: ProcessManager>(
258    target: &AssertTarget,
259    cx: &mut StepCtx<'_, P>,
260) -> Result<ResolvedAssertTarget> {
261    match target {
262        AssertTarget::Value(arg) => {
263            let value = super::args::evaluate_assert_operand(arg, cx)?;
264            if let Some(handle) = value.as_pipe_handle() {
265                let bytes =
266                    cx.state.io.peek_pipe_content(&handle).map_err(|e| {
267                        anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
268                    })?;
269                return Ok(ResolvedAssertTarget::Pipe(bytes));
270            }
271            Ok(ResolvedAssertTarget::Value(value))
272        }
273        AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
274        AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
275    }
276}
277
278/// Pre-register stream assertion observers so tees feed them data before
279/// the steps execute. Substring needles (`ASSERT_CONTAINS stdout|stderr`)
280/// get per-step `SlidingWindow`s; `ASSERT_EQ stdout` allocates the
281/// generation's exact accumulator. Uses `args::resolve_arg_state` for
282/// actual template expansion. Handles both top-level and WITH_IO-wrapped
283/// assertions via `extract_stream_needle` / `needs_exact_stdout`.
284pub(super) fn pre_register_assertions<P: ProcessManager>(
285    state: &mut ExecState<P>,
286    steps: &[Step],
287    generation: usize,
288) -> Result<()> {
289    let mut windows = match state.assert_windows.lock() {
290        Ok(guard) => guard,
291        Err(_) => bail!("assert_windows poisoned"),
292    };
293    let mut stderr_windows = match state.assert_windows_stderr.lock() {
294        Ok(guard) => guard,
295        Err(_) => bail!("assert_windows_stderr poisoned"),
296    };
297    let mut exact = match state.exact_stdout.lock() {
298        Ok(guard) => guard,
299        Err(_) => bail!("exact_stdout poisoned"),
300    };
301    for (idx, step) in steps.iter().enumerate() {
302        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
303            let resolved = super::args::resolve_arg_state(arg, state)?;
304            let map = match stream {
305                AssertStream::Stdout => &mut windows,
306                AssertStream::Stderr => &mut stderr_windows,
307            };
308            map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
309        }
310        if needs_exact_stdout(&step.kind) {
311            exact.entry(generation).or_insert_with(ExactCapture::new);
312        }
313    }
314    Ok(())
315}
316
317/// After an environment mutation (ENV or INHERIT_ENV), re-expand all
318/// substring assertion needles for the current generation to reflect new
319/// env values. Preserves ring buffer history via `update_needle`. Handles
320/// both top-level and WITH_IO-wrapped assertions. Exact accumulators hold
321/// no needle and need no sync.
322#[allow(clippy::collapsible_if)]
323pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
324    state: &ExecState<P>,
325    steps: &[Step],
326    generation: usize,
327) -> Result<()> {
328    let mut windows = match state.assert_windows.lock() {
329        Ok(guard) => guard,
330        Err(_) => bail!("assert_windows poisoned"),
331    };
332    let mut stderr_windows = match state.assert_windows_stderr.lock() {
333        Ok(guard) => guard,
334        Err(_) => bail!("assert_windows_stderr poisoned"),
335    };
336    for (idx, step) in steps.iter().enumerate() {
337        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
338            let map = match stream {
339                AssertStream::Stdout => &mut windows,
340                AssertStream::Stderr => &mut stderr_windows,
341            };
342            if let Some(w) = map.get_mut(&(generation, idx)) {
343                let resolved = super::args::resolve_arg_state(arg, state)?;
344                w.update_needle(resolved.into_bytes());
345            }
346        }
347    }
348    Ok(())
349}
350
351/// Per-step execution context handed to every command handler.
352///
353/// Host-registered functions receive this context: read script state through
354/// the public accessors (`get_var`, `get_env`, `cwd`) and return a `Value`.
355/// The fields stay crate-private so execution invariants hold for hosts.
356///
357/// Output contract (load-bearing for `LET`-capture, pipes, and stream assertions):
358/// handlers must emit stdout/stderr ONLY through `out`/`err` : via
359/// `write_stdout` or `StreamHandle::to_stdout`/`to_stderr` : and never write
360/// to host stdout directly. The step runner swaps these handles per context:
361/// `LET $x: STRING = <command>` installs a spillable capture sink, `WITH_IO`
362/// installs named-pipe endpoints, and the root installs the assertion tee. A handler that bypasses its context handles silently breaks all three.
363pub struct StepCtx<'a, P: ProcessManager> {
364    pub(super) state: &'a mut ExecState<P>,
365    pub(super) process: &'a mut P,
366    pub(super) stdin: CommandStdin,
367    pub(super) expose_stdin: bool,
368    pub(super) out: Option<StreamHandle>,
369    pub(super) err: Option<StreamHandle>,
370    /// Pipe backend backing `out`, when a `WITH_IO` stdout binding resolved
371    /// to a script pipe. Uniform context enrichment (populated for every
372    /// command, read only by consumers that need the backend, like the
373    /// network bridge). `None` for inherited, captured, and tee outputs,
374    /// and for OS pairs (kernel bytes are invisible).
375    pub(super) out_pipe: Option<Arc<PipeInner>>,
376    /// Pipe backend backing `stdin`, when a `WITH_IO` stdin binding
377    /// resolved to a script pipe. Lets bridge workers run timeout-bounded
378    /// reads without touching shared pipe semantics (`None` for OS pairs,
379    /// which fall back to blocking reads).
380    pub(super) stdin_pipe: Option<Arc<PipeInner>>,
381}
382
383impl<'a, P: ProcessManager> StepCtx<'a, P> {
384    /// Shared writer behind the step error stream, when one exists (never
385    /// for OS kernel pairs). Lets streaming hosts pump guest stderr live
386    /// instead of buffering it to the end of the block.
387    pub(super) fn err_shared(&self) -> Option<SharedOutput> {
388        match self.err.clone() {
389            Some(StreamHandle::Stream(writer)) => Some(writer),
390            _ => None,
391        }
392    }
393
394    /// Look up a script variable by name (innermost scope first).
395    pub fn get_var(&self, key: &str) -> Option<Value> {
396        self.state.get_var(key)
397    }
398
399    /// Look up an environment variable visible to the script: the
400    /// script map, seeded at session start. Exact hit first,
401    /// case-insensitive fallback on Windows.
402    pub fn get_env(&self, key: &str) -> Option<String> {
403        self.state.get_env(key).map(str::to_string)
404    }
405
406    /// Snapshot of the script-visible environment: `ENV` assignments
407    /// layered over inherited entries, as currently scoped. Hosts staging
408    /// child processes layer this over the host environment (the same
409    /// contract `RUN` honors through `CommandContext`), so block-scoped
410    /// `ENV` reaches the child and reverts at scope exit with no extra
411    /// machinery.
412    pub fn env_snapshot(&self) -> HashMap<String, String> {
413        self.state.envs.as_ref().clone()
414    }
415
416    /// Materialize the session scratch hierarchy (root + `tmp`) for
417    /// spawn sites that stage children without a `CommandContext`
418    /// (PTY): the seeded `HOME`/`TMPDIR` paths must exist when the
419    /// guest writes them, even when no `RUN` step ran first.
420    pub fn ensure_scratch_materialized(&self) -> Result<()> {
421        self.state.cargo_scratch.ensure_materialized()
422    }
423
424    /// Current working directory (guarded; stays inside the workspace).
425    pub fn cwd(&self) -> &GuardedPath {
426        &self.state.cwd
427    }
428
429    /// Shared snapshot of every registered pure function, keyed by
430    /// qualified name. Lets host-driven expansion resolve
431    /// `{{ MODULE::FUNC(args) }}` through the live registry instead of
432    /// hardcoding module or function names. Stateful, script, and pipe
433    /// backed entries never appear here: placeholder evaluation has no
434    /// step context and must stay side effect free. Dual entries
435    /// contribute their template arm.
436    pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
437        self.state.pure_function_table()
438    }
439
440    /// Mint a fresh unbound pipe handle, like bare `LET $p: PIPE`. The
441    /// backend materializes lazily on first binding; return it from a
442    /// host function to hand the DSL a pipe it can bind. Tagged with the
443    /// current task so promotion checks see the declaration origin.
444    pub fn new_pipe(&self) -> Value {
445        Value::pipe_fresh_in_task(self.state.task_id)
446    }
447
448    /// Borrow the read half of a `PIPE` value for byte streaming (see
449    /// [`PipeStream`](super::PipeStream)). Unbound handles materialize as script pipes :
450    /// hosts cannot spawn `RUN`, so script is the only sensible kind,
451    /// and a later `RUN` binding adapts through the shared path. DSL,
452    /// bridge, and host bindings on an OS-materialized handle resolve
453    /// through the single-take bridge: the first call takes, repeats bail
454    /// loudly (same contract as DSL consumers; use script-backed pipes
455    /// for repeat or multi access).
456    pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
457        use oxdock_pipe::{Materialized, materialize};
458        let Some(handle) = value.as_pipe_handle() else {
459            anyhow::bail!(
460                "host pipe_reader needs a PIPE value, got {}",
461                value.type_name()
462            );
463        };
464        match materialize(&handle, false)? {
465            Materialized::Script(backend) => Ok(backend.reader_handle()),
466            #[cfg(not(miri))]
467            Materialized::Os(entry) => {
468                let owned = entry.reader.take().map_err(|_| {
469                    anyhow::anyhow!(
470                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
471                    )
472                })?;
473                Ok(Arc::new(Mutex::new(owned)))
474            }
475        }
476    }
477
478    /// Borrow the write half of a `PIPE` value for byte streaming (see
479    /// [`PipeStream`](super::PipeStream)). Same materialization and take-once contract as
480    /// [`StepCtx::pipe_reader`].
481    pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
482        use oxdock_pipe::{Materialized, materialize};
483        let Some(handle) = value.as_pipe_handle() else {
484            anyhow::bail!(
485                "host pipe_writer needs a PIPE value, got {}",
486                value.type_name()
487            );
488        };
489        match materialize(&handle, false)? {
490            Materialized::Script(backend) => Ok(backend.writer_handle()),
491            #[cfg(not(miri))]
492            Materialized::Os(entry) => {
493                let owned = entry.writer.take().map_err(|_| {
494                    anyhow::anyhow!(
495                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
496                    )
497                })?;
498                Ok(Arc::new(Mutex::new(owned)))
499            }
500        }
501    }
502
503    /// Explicitly close a script pipe: readers drain buffered bytes, then
504    /// observe EOF regardless of live writers or keeper pins. Unbound
505    /// handles bail (closing a never-bound pipe is a caller bug), and
506    /// OS-materialized handles bail (kernel pairs close by dropping their
507    /// taken halves : drop the value instead).
508    pub fn close_pipe(&self, value: &Value) -> Result<()> {
509        let Some(handle) = value.as_pipe_handle() else {
510            anyhow::bail!(
511                "host close_pipe needs a PIPE value, got {}",
512                value.type_name()
513            );
514        };
515        let Some(backend) = oxdock_pipe::script_backend(&handle) else {
516            anyhow::bail!(
517                "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
518            );
519        };
520        backend.force_close();
521        Ok(())
522    }
523
524    /// Whether the current task was cancelled (`CANCEL`/`TIMEOUT`). For
525    /// external host modules running blocking pumps: poll each tick so
526    /// silent-but-open pipes cannot strand the task thread.
527    pub fn is_cancelled(&self) -> bool {
528        self.state
529            .cancel_token
530            .load(std::sync::atomic::Ordering::SeqCst)
531    }
532
533    /// Shared cancellation flag for pump threads spawned by host
534    /// functions: clone into the worker and poll each tick, same as
535    /// `is_cancelled`, so `CANCEL`/`TIMEOUT` ends the pump and its
536    /// writer drop closes the output pipe for downstream readers.
537    pub fn cancel_token(&self) -> Arc<AtomicBool> {
538        Arc::clone(&self.state.cancel_token)
539    }
540
541    /// Whether this step runs on an `ASYNC` task thread. Blocking pumps
542    /// must refuse the main sequential flow.
543    pub fn is_async_task(&self) -> bool {
544        self.state.inside_async
545    }
546
547    /// Module-shared state stashed at registration (`HostModule::with_state`).
548    /// Lets `#[oxdock_func]` bodies reach state that cannot ride in a
549    /// value (endpoint registries) without hand-built closures. `None`
550    /// when the module registered no such state: a programmer error at
551    /// module-build time, never a script failure.
552    pub fn module_state<T: Send + Sync + 'static>(
553        &self,
554        module: &str,
555    ) -> Option<std::sync::Arc<T>> {
556        self.state
557            .module_states
558            .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
559            .clone()
560            .downcast::<T>()
561            .ok()
562    }
563
564    /// Resolve an explicitly passed `PIPE` value to its script backend for
565    /// timeout-bounded reads (`read_into_timeout`). This is value-based on
566    /// purpose: the ambient `out_pipe`/`stdin_pipe` fields only populate via
567    /// engine-level `WITH_IO` resolution, which never runs for host function
568    /// calls. Returns `None` for unbound and OS-materialized handles, which
569    /// fall back to blocking reads.
570    pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
571        let handle = value.as_pipe_handle()?;
572        oxdock_pipe::script_backend(&handle)
573    }
574}
575
576#[allow(clippy::too_many_arguments)]
577pub(super) fn execute_steps<P: ProcessManager>(
578    state: &mut ExecState<P>,
579    process: &mut P,
580    steps: &[Step],
581    stdin: CommandStdin,
582    expose_stdin: bool,
583    out: Option<StreamHandle>,
584    err: Option<StreamHandle>,
585    out_pipe: Option<Arc<PipeInner>>,
586    stdin_pipe: Option<Arc<PipeInner>>,
587    wait_at_end: bool,
588) -> Result<Flow> {
589    let generation = allocate_assert_generation();
590    let flow = match execute_steps_inner(
591        state,
592        process,
593        generation,
594        steps,
595        stdin,
596        expose_stdin,
597        out,
598        err,
599        out_pipe,
600        stdin_pipe,
601        wait_at_end,
602    ) {
603        Ok(flow) => flow,
604        Err(e) => {
605            // A step failed before end-of-pipeline reaping ran. Join
606            // background work now so the parent owns teardown: otherwise the
607            // parent drops its task-registry reference while a worker still
608            // lives, leaving the worker as the last registry owner to drop
609            // (and join) its own handle on thread exit.
610            teardown_tasks_on_error(state);
611            cleanup_assertion_generation(state, generation)?;
612            return Err(e);
613        }
614    };
615    // Cleanup: remove all assertion state for this generation
616    cleanup_assertion_generation(state, generation)?;
617    Ok(flow)
618}
619
620/// Remove per-generation assertion observers. Runs on success and on step
621/// failure so a failed pipeline never leaks windows into later runs.
622fn cleanup_assertion_generation<P: ProcessManager>(
623    state: &mut ExecState<P>,
624    generation: usize,
625) -> Result<()> {
626    let mut windows = match state.assert_windows.lock() {
627        Ok(guard) => guard,
628        Err(_) => bail!("assert_windows poisoned"),
629    };
630    windows.retain(|(g, _), _| *g != generation);
631    let mut stderr_windows = match state.assert_windows_stderr.lock() {
632        Ok(guard) => guard,
633        Err(_) => bail!("assert_windows_stderr poisoned"),
634    };
635    stderr_windows.retain(|(g, _), _| *g != generation);
636    let mut exact = match state.exact_stdout.lock() {
637        Ok(guard) => guard,
638        Err(_) => bail!("exact_stdout poisoned"),
639    };
640    exact.retain(|g, _| *g != generation);
641    Ok(())
642}
643
644/// Join background work after a step failure, mirroring the end-of-pipeline
645/// fail-fast teardown. Anonymous handles always belong to the current
646/// thread. Named entries are root-owned: worker threads must never block on
647/// sibling tasks, which may depend on the worker via AWAIT.
648fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
649    for survivor in state.bg_children.iter_mut() {
650        let _ = survivor.kill();
651    }
652    state.bg_children.clear();
653    if state.inside_async {
654        return;
655    }
656    let entries: Vec<Arc<TaskEntry>> = {
657        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
658        named.values().cloned().collect()
659    };
660    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
661    for entry in &entries {
662        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
663        match guard.phase {
664            TaskPhase::Running | TaskPhase::Awaiting => {
665                guard.phase = TaskPhase::Cancelled;
666                if let Some(handle) = guard.handle.take() {
667                    to_kill.push((Arc::clone(entry), handle));
668                }
669            }
670            TaskPhase::Cancelled | TaskPhase::Completed => {}
671        }
672    }
673    for (entry, mut handle) in to_kill {
674        let _ = handle.kill();
675        entry.finish_teardown();
676    }
677}
678
679/// Execute a single step with an explicit generation and index.
680/// Used by `with_io` to preserve the parent step's index for assertion window keys.
681#[allow(clippy::too_many_arguments)]
682pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
683    state: &mut ExecState<P>,
684    process: &mut P,
685    cmd: &StepKind,
686    generation: usize,
687    idx: usize,
688    stdin: CommandStdin,
689    expose_stdin: bool,
690    out: Option<StreamHandle>,
691    err: Option<StreamHandle>,
692    out_pipe: Option<Arc<PipeInner>>,
693    stdin_pipe: Option<Arc<PipeInner>>,
694) -> Result<Flow> {
695    let mut cx = StepCtx {
696        state,
697        process,
698        stdin,
699        expose_stdin,
700        out,
701        err,
702        out_pipe,
703        stdin_pipe,
704    };
705    // Compound steps (loops, functions, scoped wrappers) participate in
706    // Flow and dispatch through the Flow path; every other variant runs
707    // the leaf pipeline below and yields Done.
708    match cmd {
709        StepKind::FuncDef { .. }
710        | StepKind::Call { .. }
711        | StepKind::Return { .. }
712        | StepKind::While { .. }
713        | StepKind::Break
714        | StepKind::Continue
715        | StepKind::For { .. }
716        | StepKind::If { .. }
717        | StepKind::Timeout { .. }
718        | StepKind::Isolated { .. }
719        | StepKind::WithIo { .. }
720        | StepKind::AssignCapture { .. } => {
721            return dispatch_flow_step(cmd, &mut cx, generation, idx);
722        }
723        _ => {}
724    }
725    match cmd {
726        StepKind::Run(arg) => {
727            let cmd = super::args::resolve_arg(arg, &mut cx)?;
728            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
729            handlers::run(&mut cx, idx, &cmd)
730        }
731        StepKind::RunExec { argv } => {
732            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
733            handlers::run_argv(&mut cx, idx, &resolved)
734        }
735        StepKind::Echo(arg) => {
736            let msg = super::args::resolve_arg(arg, &mut cx)?;
737            handlers::echo(&mut cx, &msg)
738        }
739        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
740        StepKind::Workdir(arg) => {
741            let path = super::args::resolve_arg(arg, &mut cx)?;
742            handlers::workdir(&mut cx, idx, &path)
743        }
744        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
745        StepKind::RemoteBlock {
746            target,
747            vars,
748            env,
749            body,
750        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
751        StepKind::Env { key, value } => {
752            let resolved = super::args::resolve_arg(value, &mut cx)?;
753            handlers::env(&mut cx, key, &resolved)
754        }
755        StepKind::InheritEnv { keys } => {
756            handlers::inherit_env(&mut cx, keys)?;
757            sync_iteration_assert_needles(
758                cx.state,
759                &[Step {
760                    guard: None,
761                    kind: cmd.clone(),
762                    scope_enter: 0,
763                    scope_exit: 0,
764                }],
765                generation,
766            )?;
767            Ok(())
768        }
769        StepKind::IsolatedInheritEnv { keys } => {
770            handlers::isolated_inherit_env(&mut cx, keys)?;
771            Ok(())
772        }
773        StepKind::Copy {
774            from_workspace,
775            from_host,
776            to_host,
777            from,
778            to,
779        } => {
780            if *from_host || *to_host {
781                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
782            } else {
783                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
784                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
785                handlers::copy(
786                    &mut cx,
787                    idx,
788                    from_workspace.clone(),
789                    &from_resolved,
790                    &to_resolved,
791                )
792            }
793        }
794        StepKind::CopyGit {
795            rev,
796            from,
797            to,
798            include_dirty,
799        } => {
800            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
801            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
802            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
803            handlers::copy_git(
804                &mut cx,
805                idx,
806                &rev_resolved,
807                &from_resolved,
808                &to_resolved,
809                *include_dirty,
810            )
811        }
812        StepKind::HashSha256 { path } => {
813            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
814            handlers::hash_sha256(&mut cx, idx, &path_resolved)
815        }
816        StepKind::Archive { src, dst, raw } => {
817            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
818            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
819            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
820        }
821        StepKind::Unarchive {
822            src,
823            dst,
824            max_bytes,
825        } => {
826            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
827            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
828            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
829            handlers::unarchive(
830                &mut cx,
831                idx,
832                &src_resolved,
833                &dst_resolved,
834                cap_resolved.as_deref(),
835            )
836        }
837        StepKind::Symlink {
838            from_workspace,
839            from,
840            to,
841        } => {
842            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
843            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
844            handlers::symlink(
845                &mut cx,
846                idx,
847                from_workspace.clone(),
848                &from_resolved,
849                &to_resolved,
850            )
851        }
852        StepKind::Mkdir(arg) => {
853            let path = super::args::resolve_arg(arg, &mut cx)?;
854            handlers::mkdir(&mut cx, idx, &path)
855        }
856        StepKind::Install { from, to } => {
857            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
858            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
859            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
860        }
861        StepKind::Ls(arg) => {
862            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
863            handlers::ls(&mut cx, idx, &resolved)
864        }
865        StepKind::Cwd => handlers::cwd(&mut cx, idx),
866        StepKind::Read(arg) => {
867            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
868            handlers::read(&mut cx, idx, &resolved)
869        }
870        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
871        StepKind::Prompt {
872            var,
873            message,
874            default,
875        } => {
876            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
877            let default_resolved = match default {
878                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
879                None => None,
880            };
881            handlers::prompt(
882                &mut cx,
883                idx,
884                var,
885                &message_resolved,
886                default_resolved.as_deref(),
887            )
888        }
889        StepKind::ListAppend { list, item } => {
890            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
891            handlers::push_into(&mut cx, idx, list, value)
892        }
893        StepKind::Write { path, contents } => {
894            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
895            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
896            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
897        }
898        StepKind::Append { path, contents } => {
899            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
900            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
901            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
902        }
903        StepKind::Remove { path, recursive } => {
904            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
905            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
906        }
907        StepKind::Expand { path, overrides } => {
908            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
909            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
910            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
911        }
912        StepKind::AssertEq {
913            hash,
914            actual,
915            expected,
916        } => {
917            let target = resolve_assert_target(actual, &mut cx)?;
918            let expected_resolved = match expected {
919                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
920                None => None,
921            };
922            handlers::assert_eq(
923                &mut cx,
924                idx,
925                generation,
926                idx,
927                hash,
928                &target,
929                expected_resolved.as_ref(),
930            )
931        }
932        StepKind::AssertContains { haystack, needle } => {
933            let target = resolve_assert_target(haystack, &mut cx)?;
934            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
935        }
936        StepKind::WithIoBlock { .. } => {
937            bail!("WITH_IO block should have been expanded during parsing")
938        }
939        StepKind::Exit(code) => {
940            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
941            handlers::exit(&mut cx, code)
942        }
943        StepKind::Assign {
944            var,
945            decl_type,
946            expr,
947        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
948        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
949        StepKind::AssignAsync {
950            var,
951            decl_type,
952            body,
953        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
954        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
955        StepKind::AwaitCapture {
956            out_var,
957            out_type,
958            task_var,
959        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
960        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
961        StepKind::Sleep { duration } => {
962            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
963            handlers::sleep(&mut cx, idx, &duration)
964        }
965        StepKind::TypeAlias { .. } => {
966            // Static declaration: collected before the run and
967            // resolved at first coercion. Nothing to execute.
968            Ok(())
969        }
970        StepKind::FuncDef { .. }
971        | StepKind::Call { .. }
972        | StepKind::Return { .. }
973        | StepKind::While { .. }
974        | StepKind::Break
975        | StepKind::Continue
976        | StepKind::For { .. }
977        | StepKind::If { .. }
978        | StepKind::Timeout { .. }
979        | StepKind::Isolated { .. }
980        | StepKind::WithIo { .. }
981        | StepKind::AssignCapture { .. } => {
982            unreachable!("compound steps dispatch before this match")
983        }
984    }?;
985    Ok(Flow::Done)
986}
987
988#[allow(clippy::too_many_arguments)]
989fn execute_steps_inner<P: ProcessManager>(
990    state: &mut ExecState<P>,
991    process: &mut P,
992    generation: usize,
993    steps: &[Step],
994    stdin: CommandStdin,
995    expose_stdin: bool,
996    out: Option<StreamHandle>,
997    err: Option<StreamHandle>,
998    out_pipe: Option<Arc<PipeInner>>,
999    stdin_pipe: Option<Arc<PipeInner>>,
1000    wait_at_end: bool,
1001) -> Result<Flow> {
1002    // Pre-register assertion windows for this generation
1003    pre_register_assertions(state, steps, generation)?;
1004
1005    for (idx, step) in steps.iter().enumerate() {
1006        // Check for cancellation before each step
1007        if state.cancel_token.load(Ordering::SeqCst) {
1008            bail!("ASYNC task cancelled");
1009        }
1010        if step.scope_enter > 0 {
1011            for _ in 0..step.scope_enter {
1012                state.push_scope();
1013            }
1014        }
1015
1016        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1017        let flow_result: Result<Flow> = if !should_run {
1018            Ok(Flow::Done)
1019        } else {
1020            let mut cx = StepCtx {
1021                state,
1022                process,
1023                stdin: stdin.clone(),
1024                expose_stdin,
1025                out: out.clone(),
1026                err: err.clone(),
1027                out_pipe: out_pipe.clone(),
1028                stdin_pipe: stdin_pipe.clone(),
1029            };
1030            // Function/loop control steps dispatch through the Flow path;
1031            // every other variant runs the leaf pipeline and yields Done.
1032            let flow_result: Result<Flow> = match &step.kind {
1033                StepKind::FuncDef { .. }
1034                | StepKind::Call { .. }
1035                | StepKind::Return { .. }
1036                | StepKind::While { .. }
1037                | StepKind::Break
1038                | StepKind::Continue
1039                | StepKind::For { .. }
1040                | StepKind::If { .. }
1041                | StepKind::Timeout { .. }
1042                | StepKind::Isolated { .. }
1043                | StepKind::WithIo { .. }
1044                | StepKind::AssignCapture { .. } => {
1045                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1046                }
1047                _ => {
1048                    match &step.kind {
1049                        StepKind::InheritEnv { keys } => {
1050                            handlers::inherit_env(&mut cx, keys)?;
1051                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1052                            Ok(())
1053                        }
1054                        StepKind::IsolatedInheritEnv { keys } => {
1055                            handlers::isolated_inherit_env(&mut cx, keys)?;
1056                            Ok(())
1057                        }
1058                        StepKind::Workdir(arg) => {
1059                            let path = super::args::resolve_arg(arg, &mut cx)?;
1060                            handlers::workdir(&mut cx, idx, &path)
1061                        }
1062                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1063                        StepKind::RemoteBlock {
1064                            target,
1065                            vars,
1066                            env,
1067                            body,
1068                        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1069                        StepKind::Env { key, value } => {
1070                            let resolved = super::args::resolve_arg(value, &mut cx)?;
1071                            handlers::env(&mut cx, key, &resolved)?;
1072                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1073                            Ok(())
1074                        }
1075                        StepKind::Run(arg) => {
1076                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
1077                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
1078                            handlers::run(&mut cx, idx, &cmd)
1079                        }
1080                        StepKind::RunExec { argv } => {
1081                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1082                            handlers::run_argv(&mut cx, idx, &resolved)
1083                        }
1084                        StepKind::Echo(arg) => {
1085                            let msg = super::args::resolve_arg(arg, &mut cx)?;
1086                            handlers::echo(&mut cx, &msg)
1087                        }
1088                        StepKind::AsyncBlock { .. } => {
1089                            handlers::dispatch_async_block(&step.kind, &mut cx)
1090                        }
1091                        StepKind::Copy {
1092                            from_workspace,
1093                            from_host,
1094                            to_host,
1095                            from,
1096                            to,
1097                        } => {
1098                            if *from_host || *to_host {
1099                                super::remote::copy_transfer(
1100                                    &mut cx, *from_host, *to_host, from, to,
1101                                )
1102                            } else {
1103                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1104                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1105                                handlers::copy(
1106                                    &mut cx,
1107                                    idx,
1108                                    from_workspace.clone(),
1109                                    &from_resolved,
1110                                    &to_resolved,
1111                                )
1112                            }
1113                        }
1114                        StepKind::CopyGit {
1115                            rev,
1116                            from,
1117                            to,
1118                            include_dirty,
1119                        } => {
1120                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1121                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1122                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1123                            handlers::copy_git(
1124                                &mut cx,
1125                                idx,
1126                                &rev_resolved,
1127                                &from_resolved,
1128                                &to_resolved,
1129                                *include_dirty,
1130                            )
1131                        }
1132                        StepKind::HashSha256 { path } => {
1133                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1134                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
1135                        }
1136                        StepKind::Archive { src, dst, raw } => {
1137                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1138                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1139                            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
1140                        }
1141                        StepKind::Unarchive {
1142                            src,
1143                            dst,
1144                            max_bytes,
1145                        } => {
1146                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1147                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1148                            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1149                            handlers::unarchive(
1150                                &mut cx,
1151                                idx,
1152                                &src_resolved,
1153                                &dst_resolved,
1154                                cap_resolved.as_deref(),
1155                            )
1156                        }
1157                        StepKind::Symlink {
1158                            from_workspace,
1159                            from,
1160                            to,
1161                        } => {
1162                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1163                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1164                            handlers::symlink(
1165                                &mut cx,
1166                                idx,
1167                                from_workspace.clone(),
1168                                &from_resolved,
1169                                &to_resolved,
1170                            )
1171                        }
1172                        StepKind::Mkdir(arg) => {
1173                            let path = super::args::resolve_arg(arg, &mut cx)?;
1174                            handlers::mkdir(&mut cx, idx, &path)
1175                        }
1176                        StepKind::Install { from, to } => {
1177                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1178                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1179                            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1180                        }
1181                        StepKind::Ls(arg) => {
1182                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1183                            handlers::ls(&mut cx, idx, &resolved)
1184                        }
1185                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
1186                        StepKind::Read(arg) => {
1187                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1188                            handlers::read(&mut cx, idx, &resolved)
1189                        }
1190                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1191                        StepKind::Prompt {
1192                            var,
1193                            message,
1194                            default,
1195                        } => {
1196                            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1197                            let default_resolved = match default {
1198                                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1199                                None => None,
1200                            };
1201                            handlers::prompt(
1202                                &mut cx,
1203                                idx,
1204                                var,
1205                                &message_resolved,
1206                                default_resolved.as_deref(),
1207                            )
1208                        }
1209                        StepKind::ListAppend { list, item } => {
1210                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1211                            handlers::push_into(&mut cx, idx, list, value)
1212                        }
1213                        StepKind::Write { path, contents } => {
1214                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1215                            let contents_resolved =
1216                                super::args::resolve_arg_opt(contents, &mut cx)?;
1217                            handlers::write(
1218                                &mut cx,
1219                                idx,
1220                                &path_resolved,
1221                                contents_resolved.as_deref(),
1222                            )
1223                        }
1224                        StepKind::Append { path, contents } => {
1225                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1226                            let contents_resolved =
1227                                super::args::resolve_arg_opt(contents, &mut cx)?;
1228                            handlers::append(
1229                                &mut cx,
1230                                idx,
1231                                &path_resolved,
1232                                contents_resolved.as_deref(),
1233                            )
1234                        }
1235                        StepKind::Remove { path, recursive } => {
1236                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1237                            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1238                        }
1239                        StepKind::Expand { path, overrides } => {
1240                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1241                            let overrides_resolved =
1242                                super::args::resolve_overrides(overrides, &mut cx)?;
1243                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1244                        }
1245                        StepKind::AssertEq {
1246                            hash,
1247                            actual,
1248                            expected,
1249                        } => {
1250                            let target = resolve_assert_target(actual, &mut cx)?;
1251                            let expected_resolved = match expected {
1252                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1253                                None => None,
1254                            };
1255                            handlers::assert_eq(
1256                                &mut cx,
1257                                idx,
1258                                generation,
1259                                idx,
1260                                hash,
1261                                &target,
1262                                expected_resolved.as_ref(),
1263                            )
1264                        }
1265                        StepKind::AssertContains { haystack, needle } => {
1266                            let target = resolve_assert_target(haystack, &mut cx)?;
1267                            handlers::assert_contains(
1268                                &mut cx, idx, generation, idx, &target, needle,
1269                            )
1270                        }
1271                        StepKind::WithIoBlock { .. } => {
1272                            bail!("WITH_IO block should have been expanded during parsing")
1273                        }
1274                        StepKind::Exit(code) => {
1275                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1276                            handlers::exit(&mut cx, code)
1277                        }
1278                        StepKind::Assign {
1279                            var,
1280                            decl_type,
1281                            expr,
1282                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1283                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1284                        StepKind::AssignAsync {
1285                            var,
1286                            decl_type,
1287                            body,
1288                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1289                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1290                        StepKind::AwaitCapture {
1291                            out_var,
1292                            out_type,
1293                            task_var,
1294                        } => handlers::dispatch_await_capture(
1295                            out_var,
1296                            out_type.clone(),
1297                            task_var,
1298                            &mut cx,
1299                        ),
1300                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1301                        StepKind::Sleep { duration } => {
1302                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1303                            handlers::sleep(&mut cx, idx, &duration)
1304                        }
1305                        StepKind::TypeAlias { .. } => {
1306                            // Static declaration: collected before the run and
1307                            // resolved at first coercion. Nothing to execute.
1308                            Ok(())
1309                        }
1310                        StepKind::FuncDef { .. }
1311                        | StepKind::Call { .. }
1312                        | StepKind::Return { .. }
1313                        | StepKind::While { .. }
1314                        | StepKind::Break
1315                        | StepKind::Continue
1316                        | StepKind::For { .. }
1317                        | StepKind::If { .. }
1318                        | StepKind::Timeout { .. }
1319                        | StepKind::Isolated { .. }
1320                        | StepKind::WithIo { .. }
1321                        | StepKind::AssignCapture { .. } => {
1322                            unreachable!("compound steps dispatch in the outer match")
1323                        }
1324                    }?;
1325                    Ok(Flow::Done)
1326                }
1327            };
1328            flow_result
1329        };
1330
1331        let restore_result = restore_scopes(state, step.scope_exit);
1332        // Keeper expiry: drop spawn-time pins whose final producer step
1333        // just completed, so later consumer steps in the same task observe
1334        // EOF. Gated on slice identity, so nested bodies executing through
1335        // this same loop never discharge the worker's top-level map.
1336        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1337            expiry.expire_step(steps, idx)
1338        } else {
1339            false
1340        };
1341        if expiry_drained {
1342            state.keeper_expiry = None;
1343        }
1344        let flow = flow_result?;
1345        restore_result?;
1346        match flow {
1347            Flow::Done => {}
1348            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1349                return Ok(flow);
1350            }
1351        }
1352    }
1353
1354    // Poll anonymous background handles at end-of-pipeline. The shared
1355    // named_tasks entries are reaped only by the root context: task threads
1356    // must never block on sibling tasks, which may depend on this thread
1357    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1358    // reaped by the root end-poll, and explicitly awaited tasks join via
1359    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1360    // later AWAIT/CANCEL report precise errors.
1361    let reap_named = !state.inside_async;
1362    let has_bg = !state.bg_children.is_empty();
1363    let named_pending = |state: &ExecState<P>| {
1364        reap_named
1365            && state
1366                .named_tasks
1367                .lock()
1368                .unwrap_or_else(|e| e.into_inner())
1369                .values()
1370                .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1371    };
1372    let has_named = named_pending(state);
1373    if wait_at_end && (has_bg || has_named) {
1374        loop {
1375            let mut failed_status: Option<anyhow::Error> = None;
1376
1377            // Cancellation (deadline watcher or parent teardown) must break
1378            // the poll loop: without this, a stuck background handle would
1379            // hang the reaper forever. Flows into the shared fail-fast
1380            // teardown below.
1381            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1382                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1383            }
1384
1385            // 1. Poll anonymous background handles
1386            let mut i = 0;
1387            while i < state.bg_children.len() {
1388                match state.bg_children[i].try_wait() {
1389                    Ok(Some(status)) => {
1390                        if !status.success() && failed_status.is_none() {
1391                            failed_status =
1392                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1393                            break;
1394                        }
1395                        state.bg_children.swap_remove(i);
1396                    }
1397                    Ok(None) => {
1398                        i += 1;
1399                    }
1400                    Err(e) => {
1401                        if failed_status.is_none() {
1402                            failed_status = Some(e);
1403                        }
1404                        break;
1405                    }
1406                }
1407            }
1408
1409            // 2. Poll un-awaited named tasks (root context only). Each entry
1410            // is probed under a short entry lock; terminal entries are
1411            // retained as tombstones, never removed.
1412            if failed_status.is_none() && reap_named {
1413                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1414                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1415                    named
1416                        .iter()
1417                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1418                        .collect()
1419                };
1420                for (id, entry) in &entries {
1421                    enum Poll {
1422                        Pending,
1423                        CompletedOk,
1424                        CompletedErr(anyhow::Error),
1425                    }
1426                    let poll = {
1427                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1428                        match guard.phase {
1429                            TaskPhase::Running | TaskPhase::Awaiting => {
1430                                match guard.handle.as_mut() {
1431                                    Some(handle) => match handle.try_wait() {
1432                                        Ok(Some(status)) => {
1433                                            let _ = guard.handle.take();
1434                                            guard.phase = TaskPhase::Completed;
1435                                            if status.success() {
1436                                                Poll::CompletedOk
1437                                            } else {
1438                                                Poll::CompletedErr(anyhow::anyhow!(
1439                                                    "named ASYNC task {id} exited with status {status}"
1440                                                ))
1441                                            }
1442                                        }
1443                                        Ok(None) => Poll::Pending,
1444                                        Err(e) => {
1445                                            let _ = guard.handle.take();
1446                                            guard.phase = TaskPhase::Completed;
1447                                            Poll::CompletedErr(e)
1448                                        }
1449                                    },
1450                                    // Handle taken by a concurrent CANCEL/AWAIT
1451                                    // teardown; the barrier below rendezvouses.
1452                                    None => Poll::Pending,
1453                                }
1454                            }
1455                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1456                        }
1457                    };
1458                    match poll {
1459                        Poll::Pending => {}
1460                        Poll::CompletedOk => {
1461                            entry.finish_teardown();
1462                        }
1463                        Poll::CompletedErr(e) => {
1464                            entry.finish_teardown();
1465                            if failed_status.is_none() {
1466                                failed_status = Some(e);
1467                            }
1468                            break;
1469                        }
1470                    }
1471                }
1472            }
1473
1474            // 3. Fail-fast teardown (named entries are root-owned; task
1475            // threads only tear down their own anonymous children).
1476            // Handles are taken under short locks and killed outside every
1477            // lock; tombstones are retained.
1478            if let Some(err) = failed_status {
1479                for survivor in state.bg_children.iter_mut() {
1480                    let _ = survivor.kill();
1481                }
1482                if reap_named {
1483                    let entries: Vec<Arc<TaskEntry>> = {
1484                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1485                        named.values().cloned().collect()
1486                    };
1487                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1488                    for entry in &entries {
1489                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1490                        match guard.phase {
1491                            TaskPhase::Running | TaskPhase::Awaiting => {
1492                                guard.phase = TaskPhase::Cancelled;
1493                                if let Some(handle) = guard.handle.take() {
1494                                    to_kill.push((Arc::clone(entry), handle));
1495                                }
1496                            }
1497                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1498                        }
1499                    }
1500                    for (entry, mut handle) in to_kill {
1501                        let _ = handle.kill();
1502                        entry.finish_teardown();
1503                    }
1504                }
1505                state.bg_children.clear();
1506                return Err(err);
1507            }
1508
1509            let bg_empty = state.bg_children.is_empty();
1510            if bg_empty && !named_pending(state) {
1511                return Ok(Flow::Done);
1512            }
1513            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1514            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1515            // instead of spinning, so this thread never outruns the join.
1516            if reap_named {
1517                let unreaped: Vec<Arc<TaskEntry>> = {
1518                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1519                    named
1520                        .values()
1521                        .filter(|entry| {
1522                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1523                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1524                        })
1525                        .cloned()
1526                        .collect()
1527                };
1528                for entry in &unreaped {
1529                    entry.wait_reaped();
1530                }
1531            }
1532            std::thread::sleep(std::time::Duration::from_millis(10));
1533        }
1534    }
1535
1536    Ok(Flow::Done)
1537}
1538
1539fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1540    for _ in 0..count {
1541        state.pop_scope()?;
1542    }
1543    Ok(())
1544}
1545
1546/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1547/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1548/// the session already fulfilled the transfer declarations. Scope,
1549/// pipes, and filesystem effects behave exactly like any local block;
1550/// control-flow signals crossing the block edge become step-numbered
1551/// errors, mirroring the pipeline-top mapping.
1552#[allow(clippy::too_many_arguments)]
1553pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1554    state: &mut ExecState<P>,
1555    process: &mut P,
1556    steps: &[Step],
1557    stdin: CommandStdin,
1558    expose_stdin: bool,
1559    out: Option<StreamHandle>,
1560    err: Option<StreamHandle>,
1561    out_pipe: Option<Arc<PipeInner>>,
1562    stdin_pipe: Option<Arc<PipeInner>>,
1563) -> Result<()> {
1564    let flow = execute_scoped_steps(
1565        state,
1566        process,
1567        steps,
1568        stdin,
1569        expose_stdin,
1570        out,
1571        err,
1572        out_pipe,
1573        stdin_pipe,
1574        true,
1575    )?;
1576    match flow {
1577        Flow::Done => Ok(()),
1578        Flow::Break { idx } => {
1579            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1580        }
1581        Flow::Continue { idx } => {
1582            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1583        }
1584        Flow::Return { idx, .. } => {
1585            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1586        }
1587    }
1588}
1589
1590/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1591/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1592/// filesystem effects cross. Restores even when the body fails. Propagates
1593/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1594#[allow(clippy::too_many_arguments)]
1595pub(super) fn execute_scoped_steps<P: ProcessManager>(
1596    state: &mut ExecState<P>,
1597    process: &mut P,
1598    steps: &[Step],
1599    stdin: CommandStdin,
1600    expose_stdin: bool,
1601    out: Option<StreamHandle>,
1602    err: Option<StreamHandle>,
1603    out_pipe: Option<Arc<PipeInner>>,
1604    stdin_pipe: Option<Arc<PipeInner>>,
1605    wait_at_end: bool,
1606) -> Result<Flow> {
1607    state.push_scope();
1608    let res = execute_steps(
1609        state,
1610        process,
1611        steps,
1612        stdin,
1613        expose_stdin,
1614        out,
1615        err,
1616        out_pipe,
1617        stdin_pipe,
1618        wait_at_end,
1619    );
1620    // Restore the scope even when the body failed, but never let an
1621    // unwinding failure mask the body's own error.
1622    let pop_res = state.pop_scope();
1623    match (res, pop_res) {
1624        (Ok(flow), Ok(())) => Ok(flow),
1625        (Err(e), _) => Err(e),
1626        (Ok(_), Err(e)) => Err(e),
1627    }
1628}
1629
1630/// Dispatch one compound step (loops, functions, scoped wrappers) through
1631/// the Flow path. Called with the caller's generation/idx so assertion
1632/// windows and error attribution match the leaf pipeline.
1633fn dispatch_flow_step<P: ProcessManager>(
1634    cmd: &StepKind,
1635    cx: &mut StepCtx<'_, P>,
1636    generation: usize,
1637    idx: usize,
1638) -> Result<Flow> {
1639    match cmd {
1640        StepKind::FuncDef { name, params, body } => {
1641            handlers::define_func(cx, name, params, body)?;
1642            Ok(Flow::Done)
1643        }
1644        StepKind::Call { name, args } => {
1645            let _ = handlers::call_func_value(cx, idx, name, args)?;
1646            Ok(Flow::Done)
1647        }
1648        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1649        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1650        StepKind::Break => Ok(Flow::Break { idx }),
1651        StepKind::Continue => Ok(Flow::Continue { idx }),
1652        StepKind::For {
1653            key_var,
1654            key_type,
1655            var,
1656            var_type,
1657            in_expr,
1658            body,
1659        } => handlers::for_loop(
1660            cx,
1661            key_var.as_deref(),
1662            key_type.clone(),
1663            var,
1664            var_type.clone(),
1665            in_expr,
1666            body,
1667        ),
1668        StepKind::If {
1669            cond,
1670            then_body,
1671            else_ifs,
1672            else_body,
1673        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1674        StepKind::Timeout { duration, body } => {
1675            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1676            handlers::timeout(cx, idx, &duration, body)
1677        }
1678        StepKind::Isolated { body } => handlers::isolated(cx, body),
1679        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1680        StepKind::AssignCapture {
1681            var,
1682            decl_type,
1683            cmd,
1684        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1685        _ => {
1686            unreachable!("dispatch_flow_step handles only compound steps")
1687        }
1688    }
1689}