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