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