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.
400    pub fn get_env(&self, key: &str) -> Option<String> {
401        self.state.envs.get(key).cloned()
402    }
403
404    /// Snapshot of the script-visible environment: `ENV` assignments
405    /// layered over inherited entries, as currently scoped. Hosts staging
406    /// child processes layer this over the host environment (the same
407    /// contract `RUN` honors through `CommandContext`), so block-scoped
408    /// `ENV` reaches the child and reverts at scope exit with no extra
409    /// machinery.
410    pub fn env_snapshot(&self) -> HashMap<String, String> {
411        self.state.envs.as_ref().clone()
412    }
413
414    /// Current working directory (guarded; stays inside the workspace).
415    pub fn cwd(&self) -> &GuardedPath {
416        &self.state.cwd
417    }
418
419    /// Shared snapshot of every registered pure function, keyed by
420    /// qualified name. Lets host-driven expansion resolve
421    /// `{{ MODULE::FUNC(args) }}` through the live registry instead of
422    /// hardcoding module or function names. Stateful, script, and pipe
423    /// backed entries never appear here: placeholder evaluation has no
424    /// step context and must stay side effect free.
425    pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
426        self.state.pure_function_table()
427    }
428
429    /// Mint a fresh unbound pipe handle, like bare `LET $p: PIPE`. The
430    /// backend materializes lazily on first binding; return it from a
431    /// host function to hand the DSL a pipe it can bind. Tagged with the
432    /// current task so promotion checks see the declaration origin.
433    pub fn new_pipe(&self) -> Value {
434        Value::pipe_fresh_in_task(self.state.task_id)
435    }
436
437    /// Borrow the read half of a `PIPE` value for byte streaming (see
438    /// [`PipeStream`](super::PipeStream)). Unbound handles materialize as script pipes :
439    /// hosts cannot spawn `RUN`, so script is the only sensible kind,
440    /// and a later `RUN` binding adapts through the shared path. DSL,
441    /// bridge, and host bindings on an OS-materialized handle resolve
442    /// through the single-take bridge: the first call takes, repeats bail
443    /// loudly (same contract as DSL consumers; use script-backed pipes
444    /// for repeat or multi access).
445    pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
446        use oxdock_pipe::{Materialized, materialize};
447        let Some(handle) = value.as_pipe_handle() else {
448            anyhow::bail!(
449                "host pipe_reader needs a PIPE value, got {}",
450                value.type_name()
451            );
452        };
453        match materialize(&handle, false)? {
454            Materialized::Script(backend) => Ok(backend.reader_handle()),
455            #[cfg(not(miri))]
456            Materialized::Os(entry) => {
457                let owned = entry.reader.take().map_err(|_| {
458                    anyhow::anyhow!(
459                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
460                    )
461                })?;
462                Ok(Arc::new(Mutex::new(owned)))
463            }
464        }
465    }
466
467    /// Borrow the write half of a `PIPE` value for byte streaming (see
468    /// [`PipeStream`](super::PipeStream)). Same materialization and take-once contract as
469    /// [`StepCtx::pipe_reader`].
470    pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
471        use oxdock_pipe::{Materialized, materialize};
472        let Some(handle) = value.as_pipe_handle() else {
473            anyhow::bail!(
474                "host pipe_writer needs a PIPE value, got {}",
475                value.type_name()
476            );
477        };
478        match materialize(&handle, false)? {
479            Materialized::Script(backend) => Ok(backend.writer_handle()),
480            #[cfg(not(miri))]
481            Materialized::Os(entry) => {
482                let owned = entry.writer.take().map_err(|_| {
483                    anyhow::anyhow!(
484                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
485                    )
486                })?;
487                Ok(Arc::new(Mutex::new(owned)))
488            }
489        }
490    }
491
492    /// Explicitly close a script pipe: readers drain buffered bytes, then
493    /// observe EOF regardless of live writers or keeper pins. Unbound
494    /// handles bail (closing a never-bound pipe is a caller bug), and
495    /// OS-materialized handles bail (kernel pairs close by dropping their
496    /// taken halves : drop the value instead).
497    pub fn close_pipe(&self, value: &Value) -> Result<()> {
498        let Some(handle) = value.as_pipe_handle() else {
499            anyhow::bail!(
500                "host close_pipe needs a PIPE value, got {}",
501                value.type_name()
502            );
503        };
504        let Some(backend) = oxdock_pipe::script_backend(&handle) else {
505            anyhow::bail!(
506                "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
507            );
508        };
509        backend.force_close();
510        Ok(())
511    }
512
513    /// Whether the current task was cancelled (`CANCEL`/`TIMEOUT`). For
514    /// external host modules running blocking pumps: poll each tick so
515    /// silent-but-open pipes cannot strand the task thread.
516    pub fn is_cancelled(&self) -> bool {
517        self.state
518            .cancel_token
519            .load(std::sync::atomic::Ordering::SeqCst)
520    }
521
522    /// Whether this step runs on an `ASYNC` task thread. Blocking pumps
523    /// must refuse the main sequential flow.
524    pub fn is_async_task(&self) -> bool {
525        self.state.inside_async
526    }
527
528    /// Resolve an explicitly passed `PIPE` value to its script backend for
529    /// timeout-bounded reads (`read_into_timeout`). This is value-based on
530    /// purpose: the ambient `out_pipe`/`stdin_pipe` fields only populate via
531    /// engine-level `WITH_IO` resolution, which never runs for host function
532    /// calls. Returns `None` for unbound and OS-materialized handles, which
533    /// fall back to blocking reads.
534    pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
535        let handle = value.as_pipe_handle()?;
536        oxdock_pipe::script_backend(&handle)
537    }
538}
539
540#[allow(clippy::too_many_arguments)]
541pub(super) fn execute_steps<P: ProcessManager>(
542    state: &mut ExecState<P>,
543    process: &mut P,
544    steps: &[Step],
545    stdin: CommandStdin,
546    expose_stdin: bool,
547    out: Option<StreamHandle>,
548    err: Option<StreamHandle>,
549    out_pipe: Option<Arc<PipeInner>>,
550    stdin_pipe: Option<Arc<PipeInner>>,
551    wait_at_end: bool,
552) -> Result<Flow> {
553    let generation = allocate_assert_generation();
554    let flow = match execute_steps_inner(
555        state,
556        process,
557        generation,
558        steps,
559        stdin,
560        expose_stdin,
561        out,
562        err,
563        out_pipe,
564        stdin_pipe,
565        wait_at_end,
566    ) {
567        Ok(flow) => flow,
568        Err(e) => {
569            // A step failed before end-of-pipeline reaping ran. Join
570            // background work now so the parent owns teardown: otherwise the
571            // parent drops its task-registry reference while a worker still
572            // lives, leaving the worker as the last registry owner to drop
573            // (and join) its own handle on thread exit.
574            teardown_tasks_on_error(state);
575            cleanup_assertion_generation(state, generation)?;
576            return Err(e);
577        }
578    };
579    // Cleanup: remove all assertion state for this generation
580    cleanup_assertion_generation(state, generation)?;
581    Ok(flow)
582}
583
584/// Remove per-generation assertion observers. Runs on success and on step
585/// failure so a failed pipeline never leaks windows into later runs.
586fn cleanup_assertion_generation<P: ProcessManager>(
587    state: &mut ExecState<P>,
588    generation: usize,
589) -> Result<()> {
590    let mut windows = match state.assert_windows.lock() {
591        Ok(guard) => guard,
592        Err(_) => bail!("assert_windows poisoned"),
593    };
594    windows.retain(|(g, _), _| *g != generation);
595    let mut stderr_windows = match state.assert_windows_stderr.lock() {
596        Ok(guard) => guard,
597        Err(_) => bail!("assert_windows_stderr poisoned"),
598    };
599    stderr_windows.retain(|(g, _), _| *g != generation);
600    let mut exact = match state.exact_stdout.lock() {
601        Ok(guard) => guard,
602        Err(_) => bail!("exact_stdout poisoned"),
603    };
604    exact.retain(|g, _| *g != generation);
605    Ok(())
606}
607
608/// Join background work after a step failure, mirroring the end-of-pipeline
609/// fail-fast teardown. Anonymous handles always belong to the current
610/// thread. Named entries are root-owned: worker threads must never block on
611/// sibling tasks, which may depend on the worker via AWAIT.
612fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
613    for survivor in state.bg_children.iter_mut() {
614        let _ = survivor.kill();
615    }
616    state.bg_children.clear();
617    if state.inside_async {
618        return;
619    }
620    let entries: Vec<Arc<TaskEntry>> = {
621        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
622        named.values().cloned().collect()
623    };
624    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
625    for entry in &entries {
626        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
627        match guard.phase {
628            TaskPhase::Running | TaskPhase::Awaiting => {
629                guard.phase = TaskPhase::Cancelled;
630                if let Some(handle) = guard.handle.take() {
631                    to_kill.push((Arc::clone(entry), handle));
632                }
633            }
634            TaskPhase::Cancelled | TaskPhase::Completed => {}
635        }
636    }
637    for (entry, mut handle) in to_kill {
638        let _ = handle.kill();
639        entry.finish_teardown();
640    }
641}
642
643/// Execute a single step with an explicit generation and index.
644/// Used by `with_io` to preserve the parent step's index for assertion window keys.
645#[allow(clippy::too_many_arguments)]
646pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
647    state: &mut ExecState<P>,
648    process: &mut P,
649    cmd: &StepKind,
650    generation: usize,
651    idx: usize,
652    stdin: CommandStdin,
653    expose_stdin: bool,
654    out: Option<StreamHandle>,
655    err: Option<StreamHandle>,
656    out_pipe: Option<Arc<PipeInner>>,
657    stdin_pipe: Option<Arc<PipeInner>>,
658) -> Result<Flow> {
659    let mut cx = StepCtx {
660        state,
661        process,
662        stdin,
663        expose_stdin,
664        out,
665        err,
666        out_pipe,
667        stdin_pipe,
668    };
669    // Compound steps (loops, functions, scoped wrappers) participate in
670    // Flow and dispatch through the Flow path; every other variant runs
671    // the leaf pipeline below and yields Done.
672    match cmd {
673        StepKind::FuncDef { .. }
674        | StepKind::Call { .. }
675        | StepKind::Return { .. }
676        | StepKind::While { .. }
677        | StepKind::Break
678        | StepKind::Continue
679        | StepKind::For { .. }
680        | StepKind::If { .. }
681        | StepKind::Timeout { .. }
682        | StepKind::WithIo { .. }
683        | StepKind::AssignCapture { .. } => {
684            return dispatch_flow_step(cmd, &mut cx, generation, idx);
685        }
686        _ => {}
687    }
688    match cmd {
689        StepKind::Run(arg) => {
690            let cmd = super::args::resolve_arg(arg, &mut cx)?;
691            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
692            handlers::run(&mut cx, idx, &cmd)
693        }
694        StepKind::RunExec { argv } => {
695            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
696            handlers::run_argv(&mut cx, idx, &resolved)
697        }
698        StepKind::Echo(arg) => {
699            let msg = super::args::resolve_arg(arg, &mut cx)?;
700            handlers::echo(&mut cx, &msg)
701        }
702        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
703        StepKind::Workdir(arg) => {
704            let path = super::args::resolve_arg(arg, &mut cx)?;
705            handlers::workdir(&mut cx, idx, &path)
706        }
707        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
708        StepKind::RemoteBlock {
709            target,
710            vars,
711            env,
712            body,
713        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
714        StepKind::Env { key, value } => {
715            let resolved = super::args::resolve_arg(value, &mut cx)?;
716            handlers::env(&mut cx, key, &resolved)
717        }
718        StepKind::InheritEnv { keys } => {
719            handlers::inherit_env(&mut cx, keys)?;
720            sync_iteration_assert_needles(
721                cx.state,
722                &[Step {
723                    guard: None,
724                    kind: cmd.clone(),
725                    scope_enter: 0,
726                    scope_exit: 0,
727                }],
728                generation,
729            )?;
730            Ok(())
731        }
732        StepKind::Copy {
733            from_workspace,
734            from_host,
735            to_host,
736            from,
737            to,
738        } => {
739            if *from_host || *to_host {
740                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
741            } else {
742                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
743                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
744                handlers::copy(
745                    &mut cx,
746                    idx,
747                    from_workspace.clone(),
748                    &from_resolved,
749                    &to_resolved,
750                )
751            }
752        }
753        StepKind::CopyGit {
754            rev,
755            from,
756            to,
757            include_dirty,
758        } => {
759            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
760            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
761            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
762            handlers::copy_git(
763                &mut cx,
764                idx,
765                &rev_resolved,
766                &from_resolved,
767                &to_resolved,
768                *include_dirty,
769            )
770        }
771        StepKind::HashSha256 { path } => {
772            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
773            handlers::hash_sha256(&mut cx, idx, &path_resolved)
774        }
775        StepKind::Archive { src, dst, raw } => {
776            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
777            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
778            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
779        }
780        StepKind::Unarchive {
781            src,
782            dst,
783            max_bytes,
784        } => {
785            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
786            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
787            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
788            handlers::unarchive(
789                &mut cx,
790                idx,
791                &src_resolved,
792                &dst_resolved,
793                cap_resolved.as_deref(),
794            )
795        }
796        StepKind::Symlink {
797            from_workspace,
798            from,
799            to,
800        } => {
801            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
802            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
803            handlers::symlink(
804                &mut cx,
805                idx,
806                from_workspace.clone(),
807                &from_resolved,
808                &to_resolved,
809            )
810        }
811        StepKind::Mkdir(arg) => {
812            let path = super::args::resolve_arg(arg, &mut cx)?;
813            handlers::mkdir(&mut cx, idx, &path)
814        }
815        StepKind::Install { from, to } => {
816            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
817            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
818            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
819        }
820        StepKind::Ls(arg) => {
821            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
822            handlers::ls(&mut cx, idx, &resolved)
823        }
824        StepKind::Cwd => handlers::cwd(&mut cx, idx),
825        StepKind::Read(arg) => {
826            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
827            handlers::read(&mut cx, idx, &resolved)
828        }
829        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
830        StepKind::Prompt {
831            var,
832            message,
833            default,
834        } => {
835            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
836            let default_resolved = match default {
837                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
838                None => None,
839            };
840            handlers::prompt(
841                &mut cx,
842                idx,
843                var,
844                &message_resolved,
845                default_resolved.as_deref(),
846            )
847        }
848        StepKind::ListAppend { list, item } => {
849            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
850            handlers::push_into(&mut cx, idx, list, value)
851        }
852        StepKind::Write { path, contents } => {
853            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
854            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
855            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
856        }
857        StepKind::Append { path, contents } => {
858            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
859            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
860            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
861        }
862        StepKind::Remove { path, recursive } => {
863            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
864            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
865        }
866        StepKind::Expand { path, overrides } => {
867            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
868            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
869            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
870        }
871        StepKind::AssertEq {
872            hash,
873            actual,
874            expected,
875        } => {
876            let target = resolve_assert_target(actual, &mut cx)?;
877            let expected_resolved = match expected {
878                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
879                None => None,
880            };
881            handlers::assert_eq(
882                &mut cx,
883                idx,
884                generation,
885                idx,
886                hash,
887                &target,
888                expected_resolved.as_ref(),
889            )
890        }
891        StepKind::AssertContains { haystack, needle } => {
892            let target = resolve_assert_target(haystack, &mut cx)?;
893            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
894        }
895        StepKind::WithIoBlock { .. } => {
896            bail!("WITH_IO block should have been expanded during parsing")
897        }
898        StepKind::Exit(code) => {
899            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
900            handlers::exit(&mut cx, code)
901        }
902        StepKind::Assign {
903            var,
904            decl_type,
905            expr,
906        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
907        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
908        StepKind::AssignAsync {
909            var,
910            decl_type,
911            body,
912        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
913        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
914        StepKind::AwaitCapture {
915            out_var,
916            out_type,
917            task_var,
918        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
919        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
920        StepKind::Sleep { duration } => {
921            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
922            handlers::sleep(&mut cx, idx, &duration)
923        }
924        StepKind::TypeAlias { .. } => {
925            // Static declaration: collected before the run and
926            // resolved at first coercion. Nothing to execute.
927            Ok(())
928        }
929        StepKind::FuncDef { .. }
930        | StepKind::Call { .. }
931        | StepKind::Return { .. }
932        | StepKind::While { .. }
933        | StepKind::Break
934        | StepKind::Continue
935        | StepKind::For { .. }
936        | StepKind::If { .. }
937        | StepKind::Timeout { .. }
938        | StepKind::WithIo { .. }
939        | StepKind::AssignCapture { .. } => {
940            unreachable!("compound steps dispatch before this match")
941        }
942    }?;
943    Ok(Flow::Done)
944}
945
946#[allow(clippy::too_many_arguments)]
947fn execute_steps_inner<P: ProcessManager>(
948    state: &mut ExecState<P>,
949    process: &mut P,
950    generation: usize,
951    steps: &[Step],
952    stdin: CommandStdin,
953    expose_stdin: bool,
954    out: Option<StreamHandle>,
955    err: Option<StreamHandle>,
956    out_pipe: Option<Arc<PipeInner>>,
957    stdin_pipe: Option<Arc<PipeInner>>,
958    wait_at_end: bool,
959) -> Result<Flow> {
960    // Pre-register assertion windows for this generation
961    pre_register_assertions(state, steps, generation)?;
962
963    for (idx, step) in steps.iter().enumerate() {
964        // Check for cancellation before each step
965        if state.cancel_token.load(Ordering::SeqCst) {
966            bail!("ASYNC task cancelled");
967        }
968        if step.scope_enter > 0 {
969            for _ in 0..step.scope_enter {
970                state.push_scope();
971            }
972        }
973
974        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
975        let flow_result: Result<Flow> = if !should_run {
976            Ok(Flow::Done)
977        } else {
978            let mut cx = StepCtx {
979                state,
980                process,
981                stdin: stdin.clone(),
982                expose_stdin,
983                out: out.clone(),
984                err: err.clone(),
985                out_pipe: out_pipe.clone(),
986                stdin_pipe: stdin_pipe.clone(),
987            };
988            // Function/loop control steps dispatch through the Flow path;
989            // every other variant runs the leaf pipeline and yields Done.
990            let flow_result: Result<Flow> = match &step.kind {
991                StepKind::FuncDef { .. }
992                | StepKind::Call { .. }
993                | StepKind::Return { .. }
994                | StepKind::While { .. }
995                | StepKind::Break
996                | StepKind::Continue
997                | StepKind::For { .. }
998                | StepKind::If { .. }
999                | StepKind::Timeout { .. }
1000                | StepKind::WithIo { .. }
1001                | StepKind::AssignCapture { .. } => {
1002                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1003                }
1004                _ => {
1005                    match &step.kind {
1006                        StepKind::InheritEnv { keys } => {
1007                            handlers::inherit_env(&mut cx, keys)?;
1008                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1009                            Ok(())
1010                        }
1011                        StepKind::Workdir(arg) => {
1012                            let path = super::args::resolve_arg(arg, &mut cx)?;
1013                            handlers::workdir(&mut cx, idx, &path)
1014                        }
1015                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1016                        StepKind::RemoteBlock {
1017                            target,
1018                            vars,
1019                            env,
1020                            body,
1021                        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1022                        StepKind::Env { key, value } => {
1023                            let resolved = super::args::resolve_arg(value, &mut cx)?;
1024                            handlers::env(&mut cx, key, &resolved)?;
1025                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1026                            Ok(())
1027                        }
1028                        StepKind::Run(arg) => {
1029                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
1030                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
1031                            handlers::run(&mut cx, idx, &cmd)
1032                        }
1033                        StepKind::RunExec { argv } => {
1034                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1035                            handlers::run_argv(&mut cx, idx, &resolved)
1036                        }
1037                        StepKind::Echo(arg) => {
1038                            let msg = super::args::resolve_arg(arg, &mut cx)?;
1039                            handlers::echo(&mut cx, &msg)
1040                        }
1041                        StepKind::AsyncBlock { .. } => {
1042                            handlers::dispatch_async_block(&step.kind, &mut cx)
1043                        }
1044                        StepKind::Copy {
1045                            from_workspace,
1046                            from_host,
1047                            to_host,
1048                            from,
1049                            to,
1050                        } => {
1051                            if *from_host || *to_host {
1052                                super::remote::copy_transfer(
1053                                    &mut cx, *from_host, *to_host, from, to,
1054                                )
1055                            } else {
1056                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1057                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1058                                handlers::copy(
1059                                    &mut cx,
1060                                    idx,
1061                                    from_workspace.clone(),
1062                                    &from_resolved,
1063                                    &to_resolved,
1064                                )
1065                            }
1066                        }
1067                        StepKind::CopyGit {
1068                            rev,
1069                            from,
1070                            to,
1071                            include_dirty,
1072                        } => {
1073                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1074                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1075                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1076                            handlers::copy_git(
1077                                &mut cx,
1078                                idx,
1079                                &rev_resolved,
1080                                &from_resolved,
1081                                &to_resolved,
1082                                *include_dirty,
1083                            )
1084                        }
1085                        StepKind::HashSha256 { path } => {
1086                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1087                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
1088                        }
1089                        StepKind::Archive { src, dst, raw } => {
1090                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1091                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1092                            handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
1093                        }
1094                        StepKind::Unarchive {
1095                            src,
1096                            dst,
1097                            max_bytes,
1098                        } => {
1099                            let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1100                            let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1101                            let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1102                            handlers::unarchive(
1103                                &mut cx,
1104                                idx,
1105                                &src_resolved,
1106                                &dst_resolved,
1107                                cap_resolved.as_deref(),
1108                            )
1109                        }
1110                        StepKind::Symlink {
1111                            from_workspace,
1112                            from,
1113                            to,
1114                        } => {
1115                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1116                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1117                            handlers::symlink(
1118                                &mut cx,
1119                                idx,
1120                                from_workspace.clone(),
1121                                &from_resolved,
1122                                &to_resolved,
1123                            )
1124                        }
1125                        StepKind::Mkdir(arg) => {
1126                            let path = super::args::resolve_arg(arg, &mut cx)?;
1127                            handlers::mkdir(&mut cx, idx, &path)
1128                        }
1129                        StepKind::Install { from, to } => {
1130                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1131                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1132                            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1133                        }
1134                        StepKind::Ls(arg) => {
1135                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1136                            handlers::ls(&mut cx, idx, &resolved)
1137                        }
1138                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
1139                        StepKind::Read(arg) => {
1140                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1141                            handlers::read(&mut cx, idx, &resolved)
1142                        }
1143                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1144                        StepKind::Prompt {
1145                            var,
1146                            message,
1147                            default,
1148                        } => {
1149                            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1150                            let default_resolved = match default {
1151                                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1152                                None => None,
1153                            };
1154                            handlers::prompt(
1155                                &mut cx,
1156                                idx,
1157                                var,
1158                                &message_resolved,
1159                                default_resolved.as_deref(),
1160                            )
1161                        }
1162                        StepKind::ListAppend { list, item } => {
1163                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1164                            handlers::push_into(&mut cx, idx, list, value)
1165                        }
1166                        StepKind::Write { path, contents } => {
1167                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1168                            let contents_resolved =
1169                                super::args::resolve_arg_opt(contents, &mut cx)?;
1170                            handlers::write(
1171                                &mut cx,
1172                                idx,
1173                                &path_resolved,
1174                                contents_resolved.as_deref(),
1175                            )
1176                        }
1177                        StepKind::Append { path, contents } => {
1178                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1179                            let contents_resolved =
1180                                super::args::resolve_arg_opt(contents, &mut cx)?;
1181                            handlers::append(
1182                                &mut cx,
1183                                idx,
1184                                &path_resolved,
1185                                contents_resolved.as_deref(),
1186                            )
1187                        }
1188                        StepKind::Remove { path, recursive } => {
1189                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1190                            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1191                        }
1192                        StepKind::Expand { path, overrides } => {
1193                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1194                            let overrides_resolved =
1195                                super::args::resolve_overrides(overrides, &mut cx)?;
1196                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1197                        }
1198                        StepKind::AssertEq {
1199                            hash,
1200                            actual,
1201                            expected,
1202                        } => {
1203                            let target = resolve_assert_target(actual, &mut cx)?;
1204                            let expected_resolved = match expected {
1205                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1206                                None => None,
1207                            };
1208                            handlers::assert_eq(
1209                                &mut cx,
1210                                idx,
1211                                generation,
1212                                idx,
1213                                hash,
1214                                &target,
1215                                expected_resolved.as_ref(),
1216                            )
1217                        }
1218                        StepKind::AssertContains { haystack, needle } => {
1219                            let target = resolve_assert_target(haystack, &mut cx)?;
1220                            handlers::assert_contains(
1221                                &mut cx, idx, generation, idx, &target, needle,
1222                            )
1223                        }
1224                        StepKind::WithIoBlock { .. } => {
1225                            bail!("WITH_IO block should have been expanded during parsing")
1226                        }
1227                        StepKind::Exit(code) => {
1228                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1229                            handlers::exit(&mut cx, code)
1230                        }
1231                        StepKind::Assign {
1232                            var,
1233                            decl_type,
1234                            expr,
1235                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1236                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1237                        StepKind::AssignAsync {
1238                            var,
1239                            decl_type,
1240                            body,
1241                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1242                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1243                        StepKind::AwaitCapture {
1244                            out_var,
1245                            out_type,
1246                            task_var,
1247                        } => handlers::dispatch_await_capture(
1248                            out_var,
1249                            out_type.clone(),
1250                            task_var,
1251                            &mut cx,
1252                        ),
1253                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1254                        StepKind::Sleep { duration } => {
1255                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1256                            handlers::sleep(&mut cx, idx, &duration)
1257                        }
1258                        StepKind::TypeAlias { .. } => {
1259                            // Static declaration: collected before the run and
1260                            // resolved at first coercion. Nothing to execute.
1261                            Ok(())
1262                        }
1263                        StepKind::FuncDef { .. }
1264                        | StepKind::Call { .. }
1265                        | StepKind::Return { .. }
1266                        | StepKind::While { .. }
1267                        | StepKind::Break
1268                        | StepKind::Continue
1269                        | StepKind::For { .. }
1270                        | StepKind::If { .. }
1271                        | StepKind::Timeout { .. }
1272                        | StepKind::WithIo { .. }
1273                        | StepKind::AssignCapture { .. } => {
1274                            unreachable!("compound steps dispatch in the outer match")
1275                        }
1276                    }?;
1277                    Ok(Flow::Done)
1278                }
1279            };
1280            flow_result
1281        };
1282
1283        let restore_result = restore_scopes(state, step.scope_exit);
1284        // Keeper expiry: drop spawn-time pins whose final producer step
1285        // just completed, so later consumer steps in the same task observe
1286        // EOF. Gated on slice identity, so nested bodies executing through
1287        // this same loop never discharge the worker's top-level map.
1288        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1289            expiry.expire_step(steps, idx)
1290        } else {
1291            false
1292        };
1293        if expiry_drained {
1294            state.keeper_expiry = None;
1295        }
1296        let flow = flow_result?;
1297        restore_result?;
1298        match flow {
1299            Flow::Done => {}
1300            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1301                return Ok(flow);
1302            }
1303        }
1304    }
1305
1306    // Poll anonymous background handles at end-of-pipeline. The shared
1307    // named_tasks entries are reaped only by the root context: task threads
1308    // must never block on sibling tasks, which may depend on this thread
1309    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1310    // reaped by the root end-poll, and explicitly awaited tasks join via
1311    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1312    // later AWAIT/CANCEL report precise errors.
1313    let reap_named = !state.inside_async;
1314    let has_bg = !state.bg_children.is_empty();
1315    let named_pending = |state: &ExecState<P>| {
1316        reap_named
1317            && state
1318                .named_tasks
1319                .lock()
1320                .unwrap_or_else(|e| e.into_inner())
1321                .values()
1322                .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1323    };
1324    let has_named = named_pending(state);
1325    if wait_at_end && (has_bg || has_named) {
1326        loop {
1327            let mut failed_status: Option<anyhow::Error> = None;
1328
1329            // Cancellation (deadline watcher or parent teardown) must break
1330            // the poll loop: without this, a stuck background handle would
1331            // hang the reaper forever. Flows into the shared fail-fast
1332            // teardown below.
1333            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1334                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1335            }
1336
1337            // 1. Poll anonymous background handles
1338            let mut i = 0;
1339            while i < state.bg_children.len() {
1340                match state.bg_children[i].try_wait() {
1341                    Ok(Some(status)) => {
1342                        if !status.success() && failed_status.is_none() {
1343                            failed_status =
1344                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1345                            break;
1346                        }
1347                        state.bg_children.swap_remove(i);
1348                    }
1349                    Ok(None) => {
1350                        i += 1;
1351                    }
1352                    Err(e) => {
1353                        if failed_status.is_none() {
1354                            failed_status = Some(e);
1355                        }
1356                        break;
1357                    }
1358                }
1359            }
1360
1361            // 2. Poll un-awaited named tasks (root context only). Each entry
1362            // is probed under a short entry lock; terminal entries are
1363            // retained as tombstones, never removed.
1364            if failed_status.is_none() && reap_named {
1365                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1366                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1367                    named
1368                        .iter()
1369                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1370                        .collect()
1371                };
1372                for (id, entry) in &entries {
1373                    enum Poll {
1374                        Pending,
1375                        CompletedOk,
1376                        CompletedErr(anyhow::Error),
1377                    }
1378                    let poll = {
1379                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1380                        match guard.phase {
1381                            TaskPhase::Running | TaskPhase::Awaiting => {
1382                                match guard.handle.as_mut() {
1383                                    Some(handle) => match handle.try_wait() {
1384                                        Ok(Some(status)) => {
1385                                            let _ = guard.handle.take();
1386                                            guard.phase = TaskPhase::Completed;
1387                                            if status.success() {
1388                                                Poll::CompletedOk
1389                                            } else {
1390                                                Poll::CompletedErr(anyhow::anyhow!(
1391                                                    "named ASYNC task {id} exited with status {status}"
1392                                                ))
1393                                            }
1394                                        }
1395                                        Ok(None) => Poll::Pending,
1396                                        Err(e) => {
1397                                            let _ = guard.handle.take();
1398                                            guard.phase = TaskPhase::Completed;
1399                                            Poll::CompletedErr(e)
1400                                        }
1401                                    },
1402                                    // Handle taken by a concurrent CANCEL/AWAIT
1403                                    // teardown; the barrier below rendezvouses.
1404                                    None => Poll::Pending,
1405                                }
1406                            }
1407                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1408                        }
1409                    };
1410                    match poll {
1411                        Poll::Pending => {}
1412                        Poll::CompletedOk => {
1413                            entry.finish_teardown();
1414                        }
1415                        Poll::CompletedErr(e) => {
1416                            entry.finish_teardown();
1417                            if failed_status.is_none() {
1418                                failed_status = Some(e);
1419                            }
1420                            break;
1421                        }
1422                    }
1423                }
1424            }
1425
1426            // 3. Fail-fast teardown (named entries are root-owned; task
1427            // threads only tear down their own anonymous children).
1428            // Handles are taken under short locks and killed outside every
1429            // lock; tombstones are retained.
1430            if let Some(err) = failed_status {
1431                for survivor in state.bg_children.iter_mut() {
1432                    let _ = survivor.kill();
1433                }
1434                if reap_named {
1435                    let entries: Vec<Arc<TaskEntry>> = {
1436                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1437                        named.values().cloned().collect()
1438                    };
1439                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1440                    for entry in &entries {
1441                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1442                        match guard.phase {
1443                            TaskPhase::Running | TaskPhase::Awaiting => {
1444                                guard.phase = TaskPhase::Cancelled;
1445                                if let Some(handle) = guard.handle.take() {
1446                                    to_kill.push((Arc::clone(entry), handle));
1447                                }
1448                            }
1449                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1450                        }
1451                    }
1452                    for (entry, mut handle) in to_kill {
1453                        let _ = handle.kill();
1454                        entry.finish_teardown();
1455                    }
1456                }
1457                state.bg_children.clear();
1458                return Err(err);
1459            }
1460
1461            let bg_empty = state.bg_children.is_empty();
1462            if bg_empty && !named_pending(state) {
1463                return Ok(Flow::Done);
1464            }
1465            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1466            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1467            // instead of spinning, so this thread never outruns the join.
1468            if reap_named {
1469                let unreaped: Vec<Arc<TaskEntry>> = {
1470                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1471                    named
1472                        .values()
1473                        .filter(|entry| {
1474                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1475                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1476                        })
1477                        .cloned()
1478                        .collect()
1479                };
1480                for entry in &unreaped {
1481                    entry.wait_reaped();
1482                }
1483            }
1484            std::thread::sleep(std::time::Duration::from_millis(10));
1485        }
1486    }
1487
1488    Ok(Flow::Done)
1489}
1490
1491fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1492    for _ in 0..count {
1493        state.pop_scope()?;
1494    }
1495    Ok(())
1496}
1497
1498/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1499/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1500/// the session already fulfilled the transfer declarations. Scope,
1501/// pipes, and filesystem effects behave exactly like any local block;
1502/// control-flow signals crossing the block edge become step-numbered
1503/// errors, mirroring the pipeline-top mapping.
1504#[allow(clippy::too_many_arguments)]
1505pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1506    state: &mut ExecState<P>,
1507    process: &mut P,
1508    steps: &[Step],
1509    stdin: CommandStdin,
1510    expose_stdin: bool,
1511    out: Option<StreamHandle>,
1512    err: Option<StreamHandle>,
1513    out_pipe: Option<Arc<PipeInner>>,
1514    stdin_pipe: Option<Arc<PipeInner>>,
1515) -> Result<()> {
1516    let flow = execute_scoped_steps(
1517        state,
1518        process,
1519        steps,
1520        stdin,
1521        expose_stdin,
1522        out,
1523        err,
1524        out_pipe,
1525        stdin_pipe,
1526        true,
1527    )?;
1528    match flow {
1529        Flow::Done => Ok(()),
1530        Flow::Break { idx } => {
1531            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1532        }
1533        Flow::Continue { idx } => {
1534            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1535        }
1536        Flow::Return { idx, .. } => {
1537            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1538        }
1539    }
1540}
1541
1542/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1543/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1544/// filesystem effects cross. Restores even when the body fails. Propagates
1545/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1546#[allow(clippy::too_many_arguments)]
1547pub(super) fn execute_scoped_steps<P: ProcessManager>(
1548    state: &mut ExecState<P>,
1549    process: &mut P,
1550    steps: &[Step],
1551    stdin: CommandStdin,
1552    expose_stdin: bool,
1553    out: Option<StreamHandle>,
1554    err: Option<StreamHandle>,
1555    out_pipe: Option<Arc<PipeInner>>,
1556    stdin_pipe: Option<Arc<PipeInner>>,
1557    wait_at_end: bool,
1558) -> Result<Flow> {
1559    state.push_scope();
1560    let res = execute_steps(
1561        state,
1562        process,
1563        steps,
1564        stdin,
1565        expose_stdin,
1566        out,
1567        err,
1568        out_pipe,
1569        stdin_pipe,
1570        wait_at_end,
1571    );
1572    // Restore the scope even when the body failed, but never let an
1573    // unwinding failure mask the body's own error.
1574    let pop_res = state.pop_scope();
1575    match (res, pop_res) {
1576        (Ok(flow), Ok(())) => Ok(flow),
1577        (Err(e), _) => Err(e),
1578        (Ok(_), Err(e)) => Err(e),
1579    }
1580}
1581
1582/// Dispatch one compound step (loops, functions, scoped wrappers) through
1583/// the Flow path. Called with the caller's generation/idx so assertion
1584/// windows and error attribution match the leaf pipeline.
1585fn dispatch_flow_step<P: ProcessManager>(
1586    cmd: &StepKind,
1587    cx: &mut StepCtx<'_, P>,
1588    generation: usize,
1589    idx: usize,
1590) -> Result<Flow> {
1591    match cmd {
1592        StepKind::FuncDef { name, params, body } => {
1593            handlers::define_func(cx, name, params, body)?;
1594            Ok(Flow::Done)
1595        }
1596        StepKind::Call { name, args } => {
1597            let _ = handlers::call_func_value(cx, idx, name, args)?;
1598            Ok(Flow::Done)
1599        }
1600        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1601        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1602        StepKind::Break => Ok(Flow::Break { idx }),
1603        StepKind::Continue => Ok(Flow::Continue { idx }),
1604        StepKind::For {
1605            key_var,
1606            key_type,
1607            var,
1608            var_type,
1609            in_expr,
1610            body,
1611        } => handlers::for_loop(
1612            cx,
1613            key_var.as_deref(),
1614            key_type.clone(),
1615            var,
1616            var_type.clone(),
1617            in_expr,
1618            body,
1619        ),
1620        StepKind::If {
1621            cond,
1622            then_body,
1623            else_ifs,
1624            else_body,
1625        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1626        StepKind::Timeout { duration, body } => {
1627            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1628            handlers::timeout(cx, idx, &duration, body)
1629        }
1630        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1631        StepKind::AssignCapture {
1632            var,
1633            decl_type,
1634            cmd,
1635        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1636        _ => {
1637            unreachable!("dispatch_flow_step handles only compound steps")
1638        }
1639    }
1640}