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