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::Symlink {
776            from_workspace,
777            from,
778            to,
779        } => {
780            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
781            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
782            handlers::symlink(
783                &mut cx,
784                idx,
785                from_workspace.clone(),
786                &from_resolved,
787                &to_resolved,
788            )
789        }
790        StepKind::Mkdir(arg) => {
791            let path = super::args::resolve_arg(arg, &mut cx)?;
792            handlers::mkdir(&mut cx, idx, &path)
793        }
794        StepKind::Install { from, to } => {
795            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
796            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
797            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
798        }
799        StepKind::Ls(arg) => {
800            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
801            handlers::ls(&mut cx, idx, &resolved)
802        }
803        StepKind::Cwd => handlers::cwd(&mut cx, idx),
804        StepKind::Read(arg) => {
805            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
806            handlers::read(&mut cx, idx, &resolved)
807        }
808        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
809        StepKind::Prompt {
810            var,
811            message,
812            default,
813        } => {
814            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
815            let default_resolved = match default {
816                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
817                None => None,
818            };
819            handlers::prompt(
820                &mut cx,
821                idx,
822                var,
823                &message_resolved,
824                default_resolved.as_deref(),
825            )
826        }
827        StepKind::ListAppend { list, item } => {
828            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
829            handlers::push_into(&mut cx, idx, list, value)
830        }
831        StepKind::Write { path, contents } => {
832            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
833            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
834            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
835        }
836        StepKind::Append { path, contents } => {
837            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
838            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
839            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
840        }
841        StepKind::Remove { path, recursive } => {
842            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
843            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
844        }
845        StepKind::Expand { path, overrides } => {
846            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
847            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
848            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
849        }
850        StepKind::AssertEq {
851            hash,
852            actual,
853            expected,
854        } => {
855            let target = resolve_assert_target(actual, &mut cx)?;
856            let expected_resolved = match expected {
857                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
858                None => None,
859            };
860            handlers::assert_eq(
861                &mut cx,
862                idx,
863                generation,
864                idx,
865                hash,
866                &target,
867                expected_resolved.as_ref(),
868            )
869        }
870        StepKind::AssertContains { haystack, needle } => {
871            let target = resolve_assert_target(haystack, &mut cx)?;
872            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
873        }
874        StepKind::WithIoBlock { .. } => {
875            bail!("WITH_IO block should have been expanded during parsing")
876        }
877        StepKind::Exit(code) => {
878            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
879            handlers::exit(&mut cx, code)
880        }
881        StepKind::Assign {
882            var,
883            decl_type,
884            expr,
885        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
886        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
887        StepKind::AssignAsync {
888            var,
889            decl_type,
890            body,
891        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
892        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
893        StepKind::AwaitCapture {
894            out_var,
895            out_type,
896            task_var,
897        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
898        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
899        StepKind::Sleep { duration } => {
900            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
901            handlers::sleep(&mut cx, idx, &duration)
902        }
903        StepKind::TypeAlias { .. } => {
904            // Static declaration: collected before the run and
905            // resolved at first coercion. Nothing to execute.
906            Ok(())
907        }
908        StepKind::FuncDef { .. }
909        | StepKind::Call { .. }
910        | StepKind::Return { .. }
911        | StepKind::While { .. }
912        | StepKind::Break
913        | StepKind::Continue
914        | StepKind::For { .. }
915        | StepKind::If { .. }
916        | StepKind::Timeout { .. }
917        | StepKind::WithIo { .. }
918        | StepKind::AssignCapture { .. } => {
919            unreachable!("compound steps dispatch before this match")
920        }
921    }?;
922    Ok(Flow::Done)
923}
924
925#[allow(clippy::too_many_arguments)]
926fn execute_steps_inner<P: ProcessManager>(
927    state: &mut ExecState<P>,
928    process: &mut P,
929    generation: usize,
930    steps: &[Step],
931    stdin: CommandStdin,
932    expose_stdin: bool,
933    out: Option<StreamHandle>,
934    err: Option<StreamHandle>,
935    out_pipe: Option<Arc<PipeInner>>,
936    stdin_pipe: Option<Arc<PipeInner>>,
937    wait_at_end: bool,
938) -> Result<Flow> {
939    // Pre-register assertion windows for this generation
940    pre_register_assertions(state, steps, generation)?;
941
942    for (idx, step) in steps.iter().enumerate() {
943        // Check for cancellation before each step
944        if state.cancel_token.load(Ordering::SeqCst) {
945            bail!("ASYNC task cancelled");
946        }
947        if step.scope_enter > 0 {
948            for _ in 0..step.scope_enter {
949                state.push_scope();
950            }
951        }
952
953        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
954        let flow_result: Result<Flow> = if !should_run {
955            Ok(Flow::Done)
956        } else {
957            let mut cx = StepCtx {
958                state,
959                process,
960                stdin: stdin.clone(),
961                expose_stdin,
962                out: out.clone(),
963                err: err.clone(),
964                out_pipe: out_pipe.clone(),
965                stdin_pipe: stdin_pipe.clone(),
966            };
967            // Function/loop control steps dispatch through the Flow path;
968            // every other variant runs the leaf pipeline and yields Done.
969            let flow_result: Result<Flow> = match &step.kind {
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::WithIo { .. }
980                | StepKind::AssignCapture { .. } => {
981                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
982                }
983                _ => {
984                    match &step.kind {
985                        StepKind::InheritEnv { keys } => {
986                            handlers::inherit_env(&mut cx, keys)?;
987                            sync_iteration_assert_needles(cx.state, steps, generation)?;
988                            Ok(())
989                        }
990                        StepKind::Workdir(arg) => {
991                            let path = super::args::resolve_arg(arg, &mut cx)?;
992                            handlers::workdir(&mut cx, idx, &path)
993                        }
994                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
995                        StepKind::RemoteBlock {
996                            target,
997                            vars,
998                            env,
999                            body,
1000                        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1001                        StepKind::Env { key, value } => {
1002                            let resolved = super::args::resolve_arg(value, &mut cx)?;
1003                            handlers::env(&mut cx, key, &resolved)?;
1004                            sync_iteration_assert_needles(cx.state, steps, generation)?;
1005                            Ok(())
1006                        }
1007                        StepKind::Run(arg) => {
1008                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
1009                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
1010                            handlers::run(&mut cx, idx, &cmd)
1011                        }
1012                        StepKind::RunExec { argv } => {
1013                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1014                            handlers::run_argv(&mut cx, idx, &resolved)
1015                        }
1016                        StepKind::Echo(arg) => {
1017                            let msg = super::args::resolve_arg(arg, &mut cx)?;
1018                            handlers::echo(&mut cx, &msg)
1019                        }
1020                        StepKind::AsyncBlock { .. } => {
1021                            handlers::dispatch_async_block(&step.kind, &mut cx)
1022                        }
1023                        StepKind::Copy {
1024                            from_workspace,
1025                            from_host,
1026                            to_host,
1027                            from,
1028                            to,
1029                        } => {
1030                            if *from_host || *to_host {
1031                                super::remote::copy_transfer(
1032                                    &mut cx, *from_host, *to_host, from, to,
1033                                )
1034                            } else {
1035                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1036                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1037                                handlers::copy(
1038                                    &mut cx,
1039                                    idx,
1040                                    from_workspace.clone(),
1041                                    &from_resolved,
1042                                    &to_resolved,
1043                                )
1044                            }
1045                        }
1046                        StepKind::CopyGit {
1047                            rev,
1048                            from,
1049                            to,
1050                            include_dirty,
1051                        } => {
1052                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1053                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1054                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1055                            handlers::copy_git(
1056                                &mut cx,
1057                                idx,
1058                                &rev_resolved,
1059                                &from_resolved,
1060                                &to_resolved,
1061                                *include_dirty,
1062                            )
1063                        }
1064                        StepKind::HashSha256 { path } => {
1065                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1066                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
1067                        }
1068                        StepKind::Symlink {
1069                            from_workspace,
1070                            from,
1071                            to,
1072                        } => {
1073                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1074                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1075                            handlers::symlink(
1076                                &mut cx,
1077                                idx,
1078                                from_workspace.clone(),
1079                                &from_resolved,
1080                                &to_resolved,
1081                            )
1082                        }
1083                        StepKind::Mkdir(arg) => {
1084                            let path = super::args::resolve_arg(arg, &mut cx)?;
1085                            handlers::mkdir(&mut cx, idx, &path)
1086                        }
1087                        StepKind::Install { from, to } => {
1088                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1089                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1090                            handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1091                        }
1092                        StepKind::Ls(arg) => {
1093                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1094                            handlers::ls(&mut cx, idx, &resolved)
1095                        }
1096                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
1097                        StepKind::Read(arg) => {
1098                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1099                            handlers::read(&mut cx, idx, &resolved)
1100                        }
1101                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1102                        StepKind::Prompt {
1103                            var,
1104                            message,
1105                            default,
1106                        } => {
1107                            let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1108                            let default_resolved = match default {
1109                                Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1110                                None => None,
1111                            };
1112                            handlers::prompt(
1113                                &mut cx,
1114                                idx,
1115                                var,
1116                                &message_resolved,
1117                                default_resolved.as_deref(),
1118                            )
1119                        }
1120                        StepKind::ListAppend { list, item } => {
1121                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1122                            handlers::push_into(&mut cx, idx, list, value)
1123                        }
1124                        StepKind::Write { path, contents } => {
1125                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1126                            let contents_resolved =
1127                                super::args::resolve_arg_opt(contents, &mut cx)?;
1128                            handlers::write(
1129                                &mut cx,
1130                                idx,
1131                                &path_resolved,
1132                                contents_resolved.as_deref(),
1133                            )
1134                        }
1135                        StepKind::Append { path, contents } => {
1136                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1137                            let contents_resolved =
1138                                super::args::resolve_arg_opt(contents, &mut cx)?;
1139                            handlers::append(
1140                                &mut cx,
1141                                idx,
1142                                &path_resolved,
1143                                contents_resolved.as_deref(),
1144                            )
1145                        }
1146                        StepKind::Remove { path, recursive } => {
1147                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1148                            handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1149                        }
1150                        StepKind::Expand { path, overrides } => {
1151                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1152                            let overrides_resolved =
1153                                super::args::resolve_overrides(overrides, &mut cx)?;
1154                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1155                        }
1156                        StepKind::AssertEq {
1157                            hash,
1158                            actual,
1159                            expected,
1160                        } => {
1161                            let target = resolve_assert_target(actual, &mut cx)?;
1162                            let expected_resolved = match expected {
1163                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1164                                None => None,
1165                            };
1166                            handlers::assert_eq(
1167                                &mut cx,
1168                                idx,
1169                                generation,
1170                                idx,
1171                                hash,
1172                                &target,
1173                                expected_resolved.as_ref(),
1174                            )
1175                        }
1176                        StepKind::AssertContains { haystack, needle } => {
1177                            let target = resolve_assert_target(haystack, &mut cx)?;
1178                            handlers::assert_contains(
1179                                &mut cx, idx, generation, idx, &target, needle,
1180                            )
1181                        }
1182                        StepKind::WithIoBlock { .. } => {
1183                            bail!("WITH_IO block should have been expanded during parsing")
1184                        }
1185                        StepKind::Exit(code) => {
1186                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1187                            handlers::exit(&mut cx, code)
1188                        }
1189                        StepKind::Assign {
1190                            var,
1191                            decl_type,
1192                            expr,
1193                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1194                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1195                        StepKind::AssignAsync {
1196                            var,
1197                            decl_type,
1198                            body,
1199                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1200                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1201                        StepKind::AwaitCapture {
1202                            out_var,
1203                            out_type,
1204                            task_var,
1205                        } => handlers::dispatch_await_capture(
1206                            out_var,
1207                            out_type.clone(),
1208                            task_var,
1209                            &mut cx,
1210                        ),
1211                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1212                        StepKind::Sleep { duration } => {
1213                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1214                            handlers::sleep(&mut cx, idx, &duration)
1215                        }
1216                        StepKind::TypeAlias { .. } => {
1217                            // Static declaration: collected before the run and
1218                            // resolved at first coercion. Nothing to execute.
1219                            Ok(())
1220                        }
1221                        StepKind::FuncDef { .. }
1222                        | StepKind::Call { .. }
1223                        | StepKind::Return { .. }
1224                        | StepKind::While { .. }
1225                        | StepKind::Break
1226                        | StepKind::Continue
1227                        | StepKind::For { .. }
1228                        | StepKind::If { .. }
1229                        | StepKind::Timeout { .. }
1230                        | StepKind::WithIo { .. }
1231                        | StepKind::AssignCapture { .. } => {
1232                            unreachable!("compound steps dispatch in the outer match")
1233                        }
1234                    }?;
1235                    Ok(Flow::Done)
1236                }
1237            };
1238            flow_result
1239        };
1240
1241        let restore_result = restore_scopes(state, step.scope_exit);
1242        // Keeper expiry: drop spawn-time pins whose final producer step
1243        // just completed, so later consumer steps in the same task observe
1244        // EOF. Gated on slice identity, so nested bodies executing through
1245        // this same loop never discharge the worker's top-level map.
1246        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1247            expiry.expire_step(steps, idx)
1248        } else {
1249            false
1250        };
1251        if expiry_drained {
1252            state.keeper_expiry = None;
1253        }
1254        let flow = flow_result?;
1255        restore_result?;
1256        match flow {
1257            Flow::Done => {}
1258            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1259                return Ok(flow);
1260            }
1261        }
1262    }
1263
1264    // Poll anonymous background handles at end-of-pipeline. The shared
1265    // named_tasks entries are reaped only by the root context: task threads
1266    // must never block on sibling tasks, which may depend on this thread
1267    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1268    // reaped by the root end-poll, and explicitly awaited tasks join via
1269    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1270    // later AWAIT/CANCEL report precise errors.
1271    let reap_named = !state.inside_async;
1272    let has_bg = !state.bg_children.is_empty();
1273    let named_pending = |state: &ExecState<P>| {
1274        reap_named
1275            && state
1276                .named_tasks
1277                .lock()
1278                .unwrap_or_else(|e| e.into_inner())
1279                .values()
1280                .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1281    };
1282    let has_named = named_pending(state);
1283    if wait_at_end && (has_bg || has_named) {
1284        loop {
1285            let mut failed_status: Option<anyhow::Error> = None;
1286
1287            // Cancellation (deadline watcher or parent teardown) must break
1288            // the poll loop: without this, a stuck background handle would
1289            // hang the reaper forever. Flows into the shared fail-fast
1290            // teardown below.
1291            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1292                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1293            }
1294
1295            // 1. Poll anonymous background handles
1296            let mut i = 0;
1297            while i < state.bg_children.len() {
1298                match state.bg_children[i].try_wait() {
1299                    Ok(Some(status)) => {
1300                        if !status.success() && failed_status.is_none() {
1301                            failed_status =
1302                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1303                            break;
1304                        }
1305                        state.bg_children.swap_remove(i);
1306                    }
1307                    Ok(None) => {
1308                        i += 1;
1309                    }
1310                    Err(e) => {
1311                        if failed_status.is_none() {
1312                            failed_status = Some(e);
1313                        }
1314                        break;
1315                    }
1316                }
1317            }
1318
1319            // 2. Poll un-awaited named tasks (root context only). Each entry
1320            // is probed under a short entry lock; terminal entries are
1321            // retained as tombstones, never removed.
1322            if failed_status.is_none() && reap_named {
1323                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1324                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1325                    named
1326                        .iter()
1327                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1328                        .collect()
1329                };
1330                for (id, entry) in &entries {
1331                    enum Poll {
1332                        Pending,
1333                        CompletedOk,
1334                        CompletedErr(anyhow::Error),
1335                    }
1336                    let poll = {
1337                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1338                        match guard.phase {
1339                            TaskPhase::Running | TaskPhase::Awaiting => {
1340                                match guard.handle.as_mut() {
1341                                    Some(handle) => match handle.try_wait() {
1342                                        Ok(Some(status)) => {
1343                                            let _ = guard.handle.take();
1344                                            guard.phase = TaskPhase::Completed;
1345                                            if status.success() {
1346                                                Poll::CompletedOk
1347                                            } else {
1348                                                Poll::CompletedErr(anyhow::anyhow!(
1349                                                    "named ASYNC task {id} exited with status {status}"
1350                                                ))
1351                                            }
1352                                        }
1353                                        Ok(None) => Poll::Pending,
1354                                        Err(e) => {
1355                                            let _ = guard.handle.take();
1356                                            guard.phase = TaskPhase::Completed;
1357                                            Poll::CompletedErr(e)
1358                                        }
1359                                    },
1360                                    // Handle taken by a concurrent CANCEL/AWAIT
1361                                    // teardown; the barrier below rendezvouses.
1362                                    None => Poll::Pending,
1363                                }
1364                            }
1365                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1366                        }
1367                    };
1368                    match poll {
1369                        Poll::Pending => {}
1370                        Poll::CompletedOk => {
1371                            entry.finish_teardown();
1372                        }
1373                        Poll::CompletedErr(e) => {
1374                            entry.finish_teardown();
1375                            if failed_status.is_none() {
1376                                failed_status = Some(e);
1377                            }
1378                            break;
1379                        }
1380                    }
1381                }
1382            }
1383
1384            // 3. Fail-fast teardown (named entries are root-owned; task
1385            // threads only tear down their own anonymous children).
1386            // Handles are taken under short locks and killed outside every
1387            // lock; tombstones are retained.
1388            if let Some(err) = failed_status {
1389                for survivor in state.bg_children.iter_mut() {
1390                    let _ = survivor.kill();
1391                }
1392                if reap_named {
1393                    let entries: Vec<Arc<TaskEntry>> = {
1394                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1395                        named.values().cloned().collect()
1396                    };
1397                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1398                    for entry in &entries {
1399                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1400                        match guard.phase {
1401                            TaskPhase::Running | TaskPhase::Awaiting => {
1402                                guard.phase = TaskPhase::Cancelled;
1403                                if let Some(handle) = guard.handle.take() {
1404                                    to_kill.push((Arc::clone(entry), handle));
1405                                }
1406                            }
1407                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1408                        }
1409                    }
1410                    for (entry, mut handle) in to_kill {
1411                        let _ = handle.kill();
1412                        entry.finish_teardown();
1413                    }
1414                }
1415                state.bg_children.clear();
1416                return Err(err);
1417            }
1418
1419            let bg_empty = state.bg_children.is_empty();
1420            if bg_empty && !named_pending(state) {
1421                return Ok(Flow::Done);
1422            }
1423            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1424            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1425            // instead of spinning, so this thread never outruns the join.
1426            if reap_named {
1427                let unreaped: Vec<Arc<TaskEntry>> = {
1428                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1429                    named
1430                        .values()
1431                        .filter(|entry| {
1432                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1433                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1434                        })
1435                        .cloned()
1436                        .collect()
1437                };
1438                for entry in &unreaped {
1439                    entry.wait_reaped();
1440                }
1441            }
1442            std::thread::sleep(std::time::Duration::from_millis(10));
1443        }
1444    }
1445
1446    Ok(Flow::Done)
1447}
1448
1449fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1450    for _ in 0..count {
1451        state.pop_scope()?;
1452    }
1453    Ok(())
1454}
1455
1456/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1457/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1458/// the session already fulfilled the transfer declarations. Scope,
1459/// pipes, and filesystem effects behave exactly like any local block;
1460/// control-flow signals crossing the block edge become step-numbered
1461/// errors, mirroring the pipeline-top mapping.
1462#[allow(clippy::too_many_arguments)]
1463pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1464    state: &mut ExecState<P>,
1465    process: &mut P,
1466    steps: &[Step],
1467    stdin: CommandStdin,
1468    expose_stdin: bool,
1469    out: Option<StreamHandle>,
1470    err: Option<StreamHandle>,
1471    out_pipe: Option<Arc<PipeInner>>,
1472    stdin_pipe: Option<Arc<PipeInner>>,
1473) -> Result<()> {
1474    let flow = execute_scoped_steps(
1475        state,
1476        process,
1477        steps,
1478        stdin,
1479        expose_stdin,
1480        out,
1481        err,
1482        out_pipe,
1483        stdin_pipe,
1484        true,
1485    )?;
1486    match flow {
1487        Flow::Done => Ok(()),
1488        Flow::Break { idx } => {
1489            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1490        }
1491        Flow::Continue { idx } => {
1492            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1493        }
1494        Flow::Return { idx, .. } => {
1495            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1496        }
1497    }
1498}
1499
1500/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1501/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1502/// filesystem effects cross. Restores even when the body fails. Propagates
1503/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1504#[allow(clippy::too_many_arguments)]
1505pub(super) fn execute_scoped_steps<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    wait_at_end: bool,
1516) -> Result<Flow> {
1517    state.push_scope();
1518    let res = execute_steps(
1519        state,
1520        process,
1521        steps,
1522        stdin,
1523        expose_stdin,
1524        out,
1525        err,
1526        out_pipe,
1527        stdin_pipe,
1528        wait_at_end,
1529    );
1530    // Restore the scope even when the body failed, but never let an
1531    // unwinding failure mask the body's own error.
1532    let pop_res = state.pop_scope();
1533    match (res, pop_res) {
1534        (Ok(flow), Ok(())) => Ok(flow),
1535        (Err(e), _) => Err(e),
1536        (Ok(_), Err(e)) => Err(e),
1537    }
1538}
1539
1540/// Dispatch one compound step (loops, functions, scoped wrappers) through
1541/// the Flow path. Called with the caller's generation/idx so assertion
1542/// windows and error attribution match the leaf pipeline.
1543fn dispatch_flow_step<P: ProcessManager>(
1544    cmd: &StepKind,
1545    cx: &mut StepCtx<'_, P>,
1546    generation: usize,
1547    idx: usize,
1548) -> Result<Flow> {
1549    match cmd {
1550        StepKind::FuncDef { name, params, body } => {
1551            handlers::define_func(cx, name, params, body)?;
1552            Ok(Flow::Done)
1553        }
1554        StepKind::Call { name, args } => {
1555            let _ = handlers::call_func_value(cx, idx, name, args)?;
1556            Ok(Flow::Done)
1557        }
1558        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1559        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1560        StepKind::Break => Ok(Flow::Break { idx }),
1561        StepKind::Continue => Ok(Flow::Continue { idx }),
1562        StepKind::For {
1563            key_var,
1564            key_type,
1565            var,
1566            var_type,
1567            in_expr,
1568            body,
1569        } => handlers::for_loop(
1570            cx,
1571            key_var.as_deref(),
1572            key_type.clone(),
1573            var,
1574            var_type.clone(),
1575            in_expr,
1576            body,
1577        ),
1578        StepKind::If {
1579            cond,
1580            then_body,
1581            else_ifs,
1582            else_body,
1583        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1584        StepKind::Timeout { duration, body } => {
1585            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1586            handlers::timeout(cx, idx, &duration, body)
1587        }
1588        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1589        StepKind::AssignCapture {
1590            var,
1591            decl_type,
1592            cmd,
1593        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1594        _ => {
1595            unreachable!("dispatch_flow_step handles only compound steps")
1596        }
1597    }
1598}