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::state::{ExecState, TaskEntry, TaskPhase};
29use oxdock_pipe::PipeInner;
30
31/// A background handle wrapping a `std::thread::JoinHandle` for ASYNC blocks
32/// that execute commands in a background thread.
33pub(super) struct ThreadJoinHandle {
34    join: Option<std::thread::JoinHandle<Result<()>>>,
35    cancel_token: Arc<AtomicBool>,
36    active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
37    /// Identity of the worker thread, published by the child on entry.
38    /// Forked worker state shares the parent task registry via `Arc`, so a
39    /// parent that errors out can drop its registry reference while the
40    /// worker is still alive. The worker then becomes the last registry
41    /// owner and would drop (and join) its own handle on thread exit, which
42    /// is undefined behavior (`pthread_join` on self). Detect that case and
43    /// detach instead of joining.
44    worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
45    /// Preserved error from the child thread, if any.
46    thread_error: Option<anyhow::Error>,
47}
48
49impl ThreadJoinHandle {
50    pub(super) fn new(
51        join: std::thread::JoinHandle<Result<()>>,
52        cancel_token: Arc<AtomicBool>,
53        active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
54        worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
55    ) -> Self {
56        Self {
57            join: Some(join),
58            cancel_token,
59            active_process,
60            worker,
61            thread_error: None,
62        }
63    }
64
65    /// Whether the caller is the worker thread owned by this handle.
66    fn is_self(&self) -> bool {
67        let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
68        guard.is_some_and(|id| id == std::thread::current().id())
69    }
70
71    /// Reap the thread if finished, preserving any error.
72    fn reap(&mut self) {
73        if self.join.is_none() {
74            return;
75        }
76        if self.is_self() {
77            // The worker is dropping the last registry reference on its own
78            // exit path (parent already tore down or errored out). Detach
79            // instead of joining self, which is undefined behavior.
80            let _ = self.join.take();
81            return;
82        }
83        let handle = self.join.take().unwrap();
84        match handle.join() {
85            Ok(Ok(())) => {}
86            Ok(Err(e)) => {
87                self.thread_error = Some(e);
88            }
89            Err(panic) => {
90                let msg = if let Some(s) = panic.downcast_ref::<&str>() {
91                    s.to_string()
92                } else if let Some(s) = panic.downcast_ref::<String>() {
93                    s.clone()
94                } else {
95                    "thread panicked".to_string()
96                };
97                self.thread_error = Some(anyhow::anyhow!("{msg}"));
98            }
99        }
100    }
101}
102
103impl BackgroundHandle for ThreadJoinHandle {
104    fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
105        if let Some(join) = &self.join {
106            if join.is_finished() {
107                self.reap();
108            } else {
109                return Ok(None);
110            }
111        }
112        // anyhow::Error is not Clone and this method may run repeatedly,
113        // so the preserved error is re-emitted rather than moved. The
114        // alternate display (`{err:#}`) flattens the full causal chain
115        // into the new message: `{err}` alone would drop every
116        // `Caused by` layer at the ASYNC task boundary.
117        if let Some(ref err) = self.thread_error {
118            Err(anyhow::anyhow!("{err:#}"))
119        } else {
120            Ok(Some(exit_status_from_code(0)))
121        }
122    }
123
124    fn kill(&mut self) -> Result<()> {
125        // Signal cancellation
126        self.cancel_token.store(true, Ordering::SeqCst);
127        // Kill any active OS process to interrupt blocking wait
128        if let Ok(mut guard) = self.active_process.lock()
129            && let Some(ref mut proc) = *guard
130        {
131            let _ = proc.kill();
132        }
133        // Join the thread to ensure it completes before returning
134        self.reap();
135        Ok(())
136    }
137
138    fn wait(&mut self) -> Result<ExitStatus> {
139        self.reap();
140        // Same chain-preserving re-emit as `try_wait` above.
141        if let Some(ref err) = self.thread_error {
142            Err(anyhow::anyhow!("{err:#}"))
143        } else {
144            Ok(exit_status_from_code(0))
145        }
146    }
147}
148
149impl Drop for ThreadJoinHandle {
150    fn drop(&mut self) {
151        let _ = self.kill();
152    }
153}
154
155/// Monotonically increasing generation counter for assert_windows key scoping.
156/// Each execute_steps invocation gets a unique generation, preventing key
157/// collisions between nested scopes (for_loop bodies, WithIo blocks).
158static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
159
160/// Intra-thread control-flow signal (`BREAK`/`CONTINUE`/`RETURN`).
161/// Produced by steps, consumed by the nearest loop (`Break`/`Continue`) or
162/// `call_func` (`Return`). Anything reaching a thread boundary (`ASYNC`
163/// spawn, `await` reaping) or the pipeline top becomes a step-numbered
164/// error. `idx` is the 0-based index of the originating step in its own
165/// body, so boundary errors can name it.
166#[derive(Debug)]
167pub(super) enum Flow {
168    Done,
169    Break { idx: usize },
170    Continue { idx: usize },
171    Return { idx: usize, value: Value },
172}
173
174pub(super) fn allocate_assert_generation() -> usize {
175    ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
176}
177
178/// Which stream a stream-targeted assertion observes.
179#[derive(Clone, Copy, PartialEq, Eq)]
180pub(super) enum AssertStream {
181    Stdout,
182    Stderr,
183}
184
185/// Extract the substring needle from a step asserting over a stream:
186/// `ASSERT_CONTAINS stdout|stderr`, handling both top-level and
187/// WITH_IO-wrapped variants. Returns the observed stream and the needle.
188fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
189    let step = match kind {
190        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
191        other => other,
192    };
193    match step {
194        StepKind::AssertContains { haystack, needle } => match haystack {
195            AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
196            AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
197            _ => None,
198        },
199        _ => None,
200    }
201}
202
203/// Whether the step needs the exact-match stdout accumulator:
204/// `ASSERT_EQ stdout`, top-level or WITH_IO-wrapped.
205fn needs_exact_stdout(kind: &StepKind) -> bool {
206    let step = match kind {
207        StepKind::WithIo { cmd, .. } => cmd.as_ref(),
208        other => other,
209    };
210    matches!(
211        step,
212        StepKind::AssertEq {
213            actual: AssertTarget::Stdout,
214            ..
215        }
216    )
217}
218
219/// An assertion first argument evaluated far enough to check:
220/// values stay typed, streams stay references to live buffers.
221pub(super) enum ResolvedAssertTarget {
222    Value(Value),
223    Stdout,
224    Stderr,
225    Pipe(Vec<u8>),
226}
227
228/// Evaluate an assertion target. `Arg::Expr` evaluates typed;
229/// strings, templates, and parts render to `String`; stream markers
230/// resolve to live buffers (peeked, never consumed). A `$var` holding a
231/// `PIPE` likewise peeks its backend bytes: lowering cannot know variable
232/// types, so the pipe dispatch lives here where the value exists.
233pub(super) fn resolve_assert_target<P: ProcessManager>(
234    target: &AssertTarget,
235    cx: &mut StepCtx<'_, P>,
236) -> Result<ResolvedAssertTarget> {
237    match target {
238        AssertTarget::Value(arg) => {
239            let value = super::args::evaluate_assert_operand(arg, cx)?;
240            if let Some(handle) = value.as_pipe_handle() {
241                let bytes =
242                    cx.state.io.peek_pipe_content(&handle).map_err(|e| {
243                        anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
244                    })?;
245                return Ok(ResolvedAssertTarget::Pipe(bytes));
246            }
247            Ok(ResolvedAssertTarget::Value(value))
248        }
249        AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
250        AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
251    }
252}
253
254/// Pre-register stream assertion observers so tees feed them data before
255/// the steps execute. Substring needles (`ASSERT_CONTAINS stdout|stderr`)
256/// get per-step `SlidingWindow`s; `ASSERT_EQ stdout` allocates the
257/// generation's exact accumulator. Uses `args::resolve_arg_state` for
258/// actual template expansion. Handles both top-level and WITH_IO-wrapped
259/// assertions via `extract_stream_needle` / `needs_exact_stdout`.
260pub(super) fn pre_register_assertions<P: ProcessManager>(
261    state: &mut ExecState<P>,
262    steps: &[Step],
263    generation: usize,
264) -> Result<()> {
265    let mut windows = match state.assert_windows.lock() {
266        Ok(guard) => guard,
267        Err(_) => bail!("assert_windows poisoned"),
268    };
269    let mut stderr_windows = match state.assert_windows_stderr.lock() {
270        Ok(guard) => guard,
271        Err(_) => bail!("assert_windows_stderr poisoned"),
272    };
273    let mut exact = match state.exact_stdout.lock() {
274        Ok(guard) => guard,
275        Err(_) => bail!("exact_stdout poisoned"),
276    };
277    for (idx, step) in steps.iter().enumerate() {
278        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
279            let resolved = super::args::resolve_arg_state(arg, state)?;
280            let map = match stream {
281                AssertStream::Stdout => &mut windows,
282                AssertStream::Stderr => &mut stderr_windows,
283            };
284            map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
285        }
286        if needs_exact_stdout(&step.kind) {
287            exact.entry(generation).or_insert_with(ExactCapture::new);
288        }
289    }
290    Ok(())
291}
292
293/// After an environment mutation (ENV or INHERIT_ENV), re-expand all
294/// substring assertion needles for the current generation to reflect new
295/// env values. Preserves ring buffer history via `update_needle`. Handles
296/// both top-level and WITH_IO-wrapped assertions. Exact accumulators hold
297/// no needle and need no sync.
298#[allow(clippy::collapsible_if)]
299pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
300    state: &ExecState<P>,
301    steps: &[Step],
302    generation: usize,
303) -> Result<()> {
304    let mut windows = match state.assert_windows.lock() {
305        Ok(guard) => guard,
306        Err(_) => bail!("assert_windows poisoned"),
307    };
308    let mut stderr_windows = match state.assert_windows_stderr.lock() {
309        Ok(guard) => guard,
310        Err(_) => bail!("assert_windows_stderr poisoned"),
311    };
312    for (idx, step) in steps.iter().enumerate() {
313        if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
314            let map = match stream {
315                AssertStream::Stdout => &mut windows,
316                AssertStream::Stderr => &mut stderr_windows,
317            };
318            if let Some(w) = map.get_mut(&(generation, idx)) {
319                let resolved = super::args::resolve_arg_state(arg, state)?;
320                w.update_needle(resolved.into_bytes());
321            }
322        }
323    }
324    Ok(())
325}
326
327/// Per-step execution context handed to every command handler.
328///
329/// Host-registered functions receive this context: read script state through
330/// the public accessors (`get_var`, `get_env`, `cwd`) and return a `Value`.
331/// The fields stay crate-private so execution invariants hold for hosts.
332///
333/// Output contract (load-bearing for `LET`-capture, pipes, and stream assertions):
334/// handlers must emit stdout/stderr ONLY through `out`/`err` : via
335/// `write_stdout` or `StreamHandle::to_stdout`/`to_stderr` : and never write
336/// to host stdout directly. The step runner swaps these handles per context:
337/// `LET $x: STRING = <command>` installs a spillable capture sink, `WITH_IO`
338/// installs named-pipe endpoints, and the root installs the assertion tee. A handler that bypasses its context handles silently breaks all three.
339pub struct StepCtx<'a, P: ProcessManager> {
340    pub(super) state: &'a mut ExecState<P>,
341    pub(super) process: &'a mut P,
342    pub(super) stdin: CommandStdin,
343    pub(super) expose_stdin: bool,
344    pub(super) out: Option<StreamHandle>,
345    pub(super) err: Option<StreamHandle>,
346    /// Pipe backend backing `out`, when a `WITH_IO` stdout binding resolved
347    /// to a script pipe. Uniform context enrichment (populated for every
348    /// command, read only by consumers that need the backend, like the
349    /// network bridge). `None` for inherited, captured, and tee outputs,
350    /// and for OS pairs (kernel bytes are invisible).
351    pub(super) out_pipe: Option<Arc<PipeInner>>,
352    /// Pipe backend backing `stdin`, when a `WITH_IO` stdin binding
353    /// resolved to a script pipe. Lets bridge workers run timeout-bounded
354    /// reads without touching shared pipe semantics (`None` for OS pairs,
355    /// which fall back to blocking reads).
356    pub(super) stdin_pipe: Option<Arc<PipeInner>>,
357}
358
359impl<'a, P: ProcessManager> StepCtx<'a, P> {
360    /// Shared writer behind the step error stream, when one exists (never
361    /// for OS kernel pairs). Lets streaming hosts pump guest stderr live
362    /// instead of buffering it to the end of the block.
363    pub(super) fn err_shared(&self) -> Option<SharedOutput> {
364        match self.err.clone() {
365            Some(StreamHandle::Stream(writer)) => Some(writer),
366            _ => None,
367        }
368    }
369
370    /// Look up a script variable by name (innermost scope first).
371    pub fn get_var(&self, key: &str) -> Option<Value> {
372        self.state.get_var(key)
373    }
374
375    /// Look up an environment variable visible to the script.
376    pub fn get_env(&self, key: &str) -> Option<String> {
377        self.state.envs.get(key).cloned()
378    }
379
380    /// Snapshot of the script-visible environment: `ENV` assignments
381    /// layered over inherited entries, as currently scoped. Hosts staging
382    /// child processes layer this over the host environment (the same
383    /// contract `RUN` honors through `CommandContext`), so block-scoped
384    /// `ENV` reaches the child and reverts at scope exit with no extra
385    /// machinery.
386    pub fn env_snapshot(&self) -> HashMap<String, String> {
387        self.state.envs.as_ref().clone()
388    }
389
390    /// Current working directory (guarded; stays inside the workspace).
391    pub fn cwd(&self) -> &GuardedPath {
392        &self.state.cwd
393    }
394
395    /// Mint a fresh unbound pipe handle, like bare `LET $p: PIPE`. The
396    /// backend materializes lazily on first binding; return it from a
397    /// host function to hand the DSL a pipe it can bind. Tagged with the
398    /// current task so promotion checks see the declaration origin.
399    pub fn new_pipe(&self) -> Value {
400        Value::pipe_fresh_in_task(self.state.task_id)
401    }
402
403    /// Borrow the read half of a `PIPE` value for byte streaming (see
404    /// [`PipeStream`](super::PipeStream)). Unbound handles materialize as script pipes :
405    /// hosts cannot spawn `RUN`, so script is the only sensible kind,
406    /// and a later `RUN` binding adapts through the shared path. DSL,
407    /// bridge, and host bindings on an OS-materialized handle resolve
408    /// through the single-take bridge: the first call takes, repeats bail
409    /// loudly (same contract as DSL consumers; use script-backed pipes
410    /// for repeat or multi access).
411    pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
412        use oxdock_pipe::{Materialized, materialize};
413        let Some(handle) = value.as_pipe_handle() else {
414            anyhow::bail!(
415                "host pipe_reader needs a PIPE value, got {}",
416                value.type_name()
417            );
418        };
419        match materialize(&handle, false)? {
420            Materialized::Script(backend) => Ok(backend.reader_handle()),
421            #[cfg(not(miri))]
422            Materialized::Os(entry) => {
423                let owned = entry.reader.take().map_err(|_| {
424                    anyhow::anyhow!(
425                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
426                    )
427                })?;
428                Ok(Arc::new(Mutex::new(owned)))
429            }
430        }
431    }
432
433    /// Borrow the write half of a `PIPE` value for byte streaming (see
434    /// [`PipeStream`](super::PipeStream)). Same materialization and take-once contract as
435    /// [`StepCtx::pipe_reader`].
436    pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
437        use oxdock_pipe::{Materialized, materialize};
438        let Some(handle) = value.as_pipe_handle() else {
439            anyhow::bail!(
440                "host pipe_writer needs a PIPE value, got {}",
441                value.type_name()
442            );
443        };
444        match materialize(&handle, false)? {
445            Materialized::Script(backend) => Ok(backend.writer_handle()),
446            #[cfg(not(miri))]
447            Materialized::Os(entry) => {
448                let owned = entry.writer.take().map_err(|_| {
449                    anyhow::anyhow!(
450                        "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
451                    )
452                })?;
453                Ok(Arc::new(Mutex::new(owned)))
454            }
455        }
456    }
457
458    /// Explicitly close a script pipe: readers drain buffered bytes, then
459    /// observe EOF regardless of live writers or keeper pins. Unbound
460    /// handles bail (closing a never-bound pipe is a caller bug), and
461    /// OS-materialized handles bail (kernel pairs close by dropping their
462    /// taken halves : drop the value instead).
463    pub fn close_pipe(&self, value: &Value) -> Result<()> {
464        let Some(handle) = value.as_pipe_handle() else {
465            anyhow::bail!(
466                "host close_pipe needs a PIPE value, got {}",
467                value.type_name()
468            );
469        };
470        let Some(backend) = oxdock_pipe::script_backend(&handle) else {
471            anyhow::bail!(
472                "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
473            );
474        };
475        backend.force_close();
476        Ok(())
477    }
478
479    /// Whether the current task was cancelled (`CANCEL`/`TIMEOUT`). For
480    /// external host modules running blocking pumps: poll each tick so
481    /// silent-but-open pipes cannot strand the task thread.
482    pub fn is_cancelled(&self) -> bool {
483        self.state
484            .cancel_token
485            .load(std::sync::atomic::Ordering::SeqCst)
486    }
487
488    /// Whether this step runs on an `ASYNC` task thread. Blocking pumps
489    /// must refuse the main sequential flow.
490    pub fn is_async_task(&self) -> bool {
491        self.state.inside_async
492    }
493
494    /// Resolve an explicitly passed `PIPE` value to its script backend for
495    /// timeout-bounded reads (`read_into_timeout`). This is value-based on
496    /// purpose: the ambient `out_pipe`/`stdin_pipe` fields only populate via
497    /// engine-level `WITH_IO` resolution, which never runs for host function
498    /// calls. Returns `None` for unbound and OS-materialized handles, which
499    /// fall back to blocking reads.
500    pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
501        let handle = value.as_pipe_handle()?;
502        oxdock_pipe::script_backend(&handle)
503    }
504}
505
506#[allow(clippy::too_many_arguments)]
507pub(super) fn execute_steps<P: ProcessManager>(
508    state: &mut ExecState<P>,
509    process: &mut P,
510    steps: &[Step],
511    stdin: CommandStdin,
512    expose_stdin: bool,
513    out: Option<StreamHandle>,
514    err: Option<StreamHandle>,
515    out_pipe: Option<Arc<PipeInner>>,
516    stdin_pipe: Option<Arc<PipeInner>>,
517    wait_at_end: bool,
518) -> Result<Flow> {
519    let generation = allocate_assert_generation();
520    let flow = match execute_steps_inner(
521        state,
522        process,
523        generation,
524        steps,
525        stdin,
526        expose_stdin,
527        out,
528        err,
529        out_pipe,
530        stdin_pipe,
531        wait_at_end,
532    ) {
533        Ok(flow) => flow,
534        Err(e) => {
535            // A step failed before end-of-pipeline reaping ran. Join
536            // background work now so the parent owns teardown: otherwise the
537            // parent drops its task-registry reference while a worker still
538            // lives, leaving the worker as the last registry owner to drop
539            // (and join) its own handle on thread exit.
540            teardown_tasks_on_error(state);
541            cleanup_assertion_generation(state, generation)?;
542            return Err(e);
543        }
544    };
545    // Cleanup: remove all assertion state for this generation
546    cleanup_assertion_generation(state, generation)?;
547    Ok(flow)
548}
549
550/// Remove per-generation assertion observers. Runs on success and on step
551/// failure so a failed pipeline never leaks windows into later runs.
552fn cleanup_assertion_generation<P: ProcessManager>(
553    state: &mut ExecState<P>,
554    generation: usize,
555) -> Result<()> {
556    let mut windows = match state.assert_windows.lock() {
557        Ok(guard) => guard,
558        Err(_) => bail!("assert_windows poisoned"),
559    };
560    windows.retain(|(g, _), _| *g != generation);
561    let mut stderr_windows = match state.assert_windows_stderr.lock() {
562        Ok(guard) => guard,
563        Err(_) => bail!("assert_windows_stderr poisoned"),
564    };
565    stderr_windows.retain(|(g, _), _| *g != generation);
566    let mut exact = match state.exact_stdout.lock() {
567        Ok(guard) => guard,
568        Err(_) => bail!("exact_stdout poisoned"),
569    };
570    exact.retain(|g, _| *g != generation);
571    Ok(())
572}
573
574/// Join background work after a step failure, mirroring the end-of-pipeline
575/// fail-fast teardown. Anonymous handles always belong to the current
576/// thread. Named entries are root-owned: worker threads must never block on
577/// sibling tasks, which may depend on the worker via AWAIT.
578fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
579    for survivor in state.bg_children.iter_mut() {
580        let _ = survivor.kill();
581    }
582    state.bg_children.clear();
583    if state.inside_async {
584        return;
585    }
586    let entries: Vec<Arc<TaskEntry>> = {
587        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
588        named.values().cloned().collect()
589    };
590    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
591    for entry in &entries {
592        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
593        match guard.phase {
594            TaskPhase::Running | TaskPhase::Awaiting => {
595                guard.phase = TaskPhase::Cancelled;
596                if let Some(handle) = guard.handle.take() {
597                    to_kill.push((Arc::clone(entry), handle));
598                }
599            }
600            TaskPhase::Cancelled | TaskPhase::Completed => {}
601        }
602    }
603    for (entry, mut handle) in to_kill {
604        let _ = handle.kill();
605        entry.finish_teardown();
606    }
607}
608
609/// Execute a single step with an explicit generation and index.
610/// Used by `with_io` to preserve the parent step's index for assertion window keys.
611#[allow(clippy::too_many_arguments)]
612pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
613    state: &mut ExecState<P>,
614    process: &mut P,
615    cmd: &StepKind,
616    generation: usize,
617    idx: usize,
618    stdin: CommandStdin,
619    expose_stdin: bool,
620    out: Option<StreamHandle>,
621    err: Option<StreamHandle>,
622    out_pipe: Option<Arc<PipeInner>>,
623    stdin_pipe: Option<Arc<PipeInner>>,
624) -> Result<Flow> {
625    let mut cx = StepCtx {
626        state,
627        process,
628        stdin,
629        expose_stdin,
630        out,
631        err,
632        out_pipe,
633        stdin_pipe,
634    };
635    // Compound steps (loops, functions, scoped wrappers) participate in
636    // Flow and dispatch through the Flow path; every other variant runs
637    // the leaf pipeline below and yields Done.
638    match cmd {
639        StepKind::FuncDef { .. }
640        | StepKind::Call { .. }
641        | StepKind::Return { .. }
642        | StepKind::While { .. }
643        | StepKind::Break
644        | StepKind::Continue
645        | StepKind::For { .. }
646        | StepKind::If { .. }
647        | StepKind::Timeout { .. }
648        | StepKind::WithIo { .. }
649        | StepKind::AssignCapture { .. } => {
650            return dispatch_flow_step(cmd, &mut cx, generation, idx);
651        }
652        _ => {}
653    }
654    match cmd {
655        StepKind::Run(arg) => {
656            let cmd = super::args::resolve_arg(arg, &mut cx)?;
657            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
658            handlers::run(&mut cx, idx, &cmd)
659        }
660        StepKind::RunExec { argv } => {
661            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
662            handlers::run_argv(&mut cx, idx, &resolved)
663        }
664        StepKind::Echo(arg) => {
665            let msg = super::args::resolve_arg(arg, &mut cx)?;
666            handlers::echo(&mut cx, &msg)
667        }
668        StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
669        StepKind::Workdir(arg) => {
670            let path = super::args::resolve_arg(arg, &mut cx)?;
671            handlers::workdir(&mut cx, idx, &path)
672        }
673        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
674        StepKind::RemoteBlock {
675            target,
676            vars,
677            env,
678            body,
679        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
680        StepKind::Env { key, value } => {
681            let resolved = super::args::resolve_arg(value, &mut cx)?;
682            handlers::env(&mut cx, key, &resolved)
683        }
684        StepKind::InheritEnv { keys } => {
685            handlers::inherit_env(&mut cx, keys)?;
686            sync_iteration_assert_needles(
687                cx.state,
688                &[Step {
689                    guard: None,
690                    kind: cmd.clone(),
691                    scope_enter: 0,
692                    scope_exit: 0,
693                }],
694                generation,
695            )?;
696            Ok(())
697        }
698        StepKind::Copy {
699            from_workspace,
700            from_host,
701            to_host,
702            from,
703            to,
704        } => {
705            if *from_host || *to_host {
706                super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
707            } else {
708                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
709                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
710                handlers::copy(
711                    &mut cx,
712                    idx,
713                    from_workspace.clone(),
714                    &from_resolved,
715                    &to_resolved,
716                )
717            }
718        }
719        StepKind::CopyGit {
720            rev,
721            from,
722            to,
723            include_dirty,
724        } => {
725            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
726            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
727            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
728            handlers::copy_git(
729                &mut cx,
730                idx,
731                &rev_resolved,
732                &from_resolved,
733                &to_resolved,
734                *include_dirty,
735            )
736        }
737        StepKind::HashSha256 { path } => {
738            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
739            handlers::hash_sha256(&mut cx, idx, &path_resolved)
740        }
741        StepKind::Symlink {
742            from_workspace,
743            from,
744            to,
745        } => {
746            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
747            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
748            handlers::symlink(
749                &mut cx,
750                idx,
751                from_workspace.clone(),
752                &from_resolved,
753                &to_resolved,
754            )
755        }
756        StepKind::Mkdir(arg) => {
757            let path = super::args::resolve_arg(arg, &mut cx)?;
758            handlers::mkdir(&mut cx, idx, &path)
759        }
760        StepKind::Ls(arg) => {
761            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
762            handlers::ls(&mut cx, idx, &resolved)
763        }
764        StepKind::Cwd => handlers::cwd(&mut cx, idx),
765        StepKind::Read(arg) => {
766            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
767            handlers::read(&mut cx, idx, &resolved)
768        }
769        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
770        StepKind::ListAppend { list, item } => {
771            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
772            handlers::push_into(&mut cx, idx, list, value)
773        }
774        StepKind::Write { path, contents } => {
775            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
776            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
777            handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
778        }
779        StepKind::Append { path, contents } => {
780            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
781            let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
782            handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
783        }
784        StepKind::Expand { path, overrides } => {
785            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
786            let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
787            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
788        }
789        StepKind::AssertEq {
790            hash,
791            actual,
792            expected,
793        } => {
794            let target = resolve_assert_target(actual, &mut cx)?;
795            let expected_resolved = match expected {
796                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
797                None => None,
798            };
799            handlers::assert_eq(
800                &mut cx,
801                idx,
802                generation,
803                idx,
804                hash,
805                &target,
806                expected_resolved.as_ref(),
807            )
808        }
809        StepKind::AssertContains { haystack, needle } => {
810            let target = resolve_assert_target(haystack, &mut cx)?;
811            handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
812        }
813        StepKind::WithIoBlock { .. } => {
814            bail!("WITH_IO block should have been expanded during parsing")
815        }
816        StepKind::Exit(code) => {
817            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
818            handlers::exit(&mut cx, code)
819        }
820        StepKind::Assign {
821            var,
822            decl_type,
823            expr,
824        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
825        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
826        StepKind::AssignAsync {
827            var,
828            decl_type,
829            body,
830        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
831        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
832        StepKind::AwaitCapture {
833            out_var,
834            out_type,
835            task_var,
836        } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
837        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
838        StepKind::Sleep { duration } => {
839            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
840            handlers::sleep(&mut cx, idx, &duration)
841        }
842        StepKind::FuncDef { .. }
843        | StepKind::Call { .. }
844        | StepKind::Return { .. }
845        | StepKind::While { .. }
846        | StepKind::Break
847        | StepKind::Continue
848        | StepKind::For { .. }
849        | StepKind::If { .. }
850        | StepKind::Timeout { .. }
851        | StepKind::WithIo { .. }
852        | StepKind::AssignCapture { .. } => {
853            unreachable!("compound steps dispatch before this match")
854        }
855    }?;
856    Ok(Flow::Done)
857}
858
859#[allow(clippy::too_many_arguments)]
860fn execute_steps_inner<P: ProcessManager>(
861    state: &mut ExecState<P>,
862    process: &mut P,
863    generation: usize,
864    steps: &[Step],
865    stdin: CommandStdin,
866    expose_stdin: bool,
867    out: Option<StreamHandle>,
868    err: Option<StreamHandle>,
869    out_pipe: Option<Arc<PipeInner>>,
870    stdin_pipe: Option<Arc<PipeInner>>,
871    wait_at_end: bool,
872) -> Result<Flow> {
873    // Pre-register assertion windows for this generation
874    pre_register_assertions(state, steps, generation)?;
875
876    for (idx, step) in steps.iter().enumerate() {
877        // Check for cancellation before each step
878        if state.cancel_token.load(Ordering::SeqCst) {
879            bail!("ASYNC task cancelled");
880        }
881        if step.scope_enter > 0 {
882            for _ in 0..step.scope_enter {
883                state.push_scope();
884            }
885        }
886
887        let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
888        let flow_result: Result<Flow> = if !should_run {
889            Ok(Flow::Done)
890        } else {
891            let mut cx = StepCtx {
892                state,
893                process,
894                stdin: stdin.clone(),
895                expose_stdin,
896                out: out.clone(),
897                err: err.clone(),
898                out_pipe: out_pipe.clone(),
899                stdin_pipe: stdin_pipe.clone(),
900            };
901            // Function/loop control steps dispatch through the Flow path;
902            // every other variant runs the leaf pipeline and yields Done.
903            let flow_result: Result<Flow> = match &step.kind {
904                StepKind::FuncDef { .. }
905                | StepKind::Call { .. }
906                | StepKind::Return { .. }
907                | StepKind::While { .. }
908                | StepKind::Break
909                | StepKind::Continue
910                | StepKind::For { .. }
911                | StepKind::If { .. }
912                | StepKind::Timeout { .. }
913                | StepKind::WithIo { .. }
914                | StepKind::AssignCapture { .. } => {
915                    dispatch_flow_step(&step.kind, &mut cx, generation, idx)
916                }
917                _ => {
918                    match &step.kind {
919                        StepKind::InheritEnv { keys } => {
920                            handlers::inherit_env(&mut cx, keys)?;
921                            sync_iteration_assert_needles(cx.state, steps, generation)?;
922                            Ok(())
923                        }
924                        StepKind::Workdir(arg) => {
925                            let path = super::args::resolve_arg(arg, &mut cx)?;
926                            handlers::workdir(&mut cx, idx, &path)
927                        }
928                        StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
929                        StepKind::RemoteBlock {
930                            target,
931                            vars,
932                            env,
933                            body,
934                        } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
935                        StepKind::Env { key, value } => {
936                            let resolved = super::args::resolve_arg(value, &mut cx)?;
937                            handlers::env(&mut cx, key, &resolved)?;
938                            sync_iteration_assert_needles(cx.state, steps, generation)?;
939                            Ok(())
940                        }
941                        StepKind::Run(arg) => {
942                            let cmd = super::args::resolve_arg(arg, &mut cx)?;
943                            let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
944                            handlers::run(&mut cx, idx, &cmd)
945                        }
946                        StepKind::RunExec { argv } => {
947                            let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
948                            handlers::run_argv(&mut cx, idx, &resolved)
949                        }
950                        StepKind::Echo(arg) => {
951                            let msg = super::args::resolve_arg(arg, &mut cx)?;
952                            handlers::echo(&mut cx, &msg)
953                        }
954                        StepKind::AsyncBlock { .. } => {
955                            handlers::dispatch_async_block(&step.kind, &mut cx)
956                        }
957                        StepKind::Copy {
958                            from_workspace,
959                            from_host,
960                            to_host,
961                            from,
962                            to,
963                        } => {
964                            if *from_host || *to_host {
965                                super::remote::copy_transfer(
966                                    &mut cx, *from_host, *to_host, from, to,
967                                )
968                            } else {
969                                let from_resolved = super::args::resolve_arg(from, &mut cx)?;
970                                let to_resolved = super::args::resolve_arg(to, &mut cx)?;
971                                handlers::copy(
972                                    &mut cx,
973                                    idx,
974                                    from_workspace.clone(),
975                                    &from_resolved,
976                                    &to_resolved,
977                                )
978                            }
979                        }
980                        StepKind::CopyGit {
981                            rev,
982                            from,
983                            to,
984                            include_dirty,
985                        } => {
986                            let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
987                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
988                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
989                            handlers::copy_git(
990                                &mut cx,
991                                idx,
992                                &rev_resolved,
993                                &from_resolved,
994                                &to_resolved,
995                                *include_dirty,
996                            )
997                        }
998                        StepKind::HashSha256 { path } => {
999                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1000                            handlers::hash_sha256(&mut cx, idx, &path_resolved)
1001                        }
1002                        StepKind::Symlink {
1003                            from_workspace,
1004                            from,
1005                            to,
1006                        } => {
1007                            let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1008                            let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1009                            handlers::symlink(
1010                                &mut cx,
1011                                idx,
1012                                from_workspace.clone(),
1013                                &from_resolved,
1014                                &to_resolved,
1015                            )
1016                        }
1017                        StepKind::Mkdir(arg) => {
1018                            let path = super::args::resolve_arg(arg, &mut cx)?;
1019                            handlers::mkdir(&mut cx, idx, &path)
1020                        }
1021                        StepKind::Ls(arg) => {
1022                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1023                            handlers::ls(&mut cx, idx, &resolved)
1024                        }
1025                        StepKind::Cwd => handlers::cwd(&mut cx, idx),
1026                        StepKind::Read(arg) => {
1027                            let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1028                            handlers::read(&mut cx, idx, &resolved)
1029                        }
1030                        StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1031                        StepKind::ListAppend { list, item } => {
1032                            let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1033                            handlers::push_into(&mut cx, idx, list, value)
1034                        }
1035                        StepKind::Write { path, contents } => {
1036                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1037                            let contents_resolved =
1038                                super::args::resolve_arg_opt(contents, &mut cx)?;
1039                            handlers::write(
1040                                &mut cx,
1041                                idx,
1042                                &path_resolved,
1043                                contents_resolved.as_deref(),
1044                            )
1045                        }
1046                        StepKind::Append { path, contents } => {
1047                            let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1048                            let contents_resolved =
1049                                super::args::resolve_arg_opt(contents, &mut cx)?;
1050                            handlers::append(
1051                                &mut cx,
1052                                idx,
1053                                &path_resolved,
1054                                contents_resolved.as_deref(),
1055                            )
1056                        }
1057                        StepKind::Expand { path, overrides } => {
1058                            let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1059                            let overrides_resolved =
1060                                super::args::resolve_overrides(overrides, &mut cx)?;
1061                            handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1062                        }
1063                        StepKind::AssertEq {
1064                            hash,
1065                            actual,
1066                            expected,
1067                        } => {
1068                            let target = resolve_assert_target(actual, &mut cx)?;
1069                            let expected_resolved = match expected {
1070                                Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1071                                None => None,
1072                            };
1073                            handlers::assert_eq(
1074                                &mut cx,
1075                                idx,
1076                                generation,
1077                                idx,
1078                                hash,
1079                                &target,
1080                                expected_resolved.as_ref(),
1081                            )
1082                        }
1083                        StepKind::AssertContains { haystack, needle } => {
1084                            let target = resolve_assert_target(haystack, &mut cx)?;
1085                            handlers::assert_contains(
1086                                &mut cx, idx, generation, idx, &target, needle,
1087                            )
1088                        }
1089                        StepKind::WithIoBlock { .. } => {
1090                            bail!("WITH_IO block should have been expanded during parsing")
1091                        }
1092                        StepKind::Exit(code) => {
1093                            let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1094                            handlers::exit(&mut cx, code)
1095                        }
1096                        StepKind::Assign {
1097                            var,
1098                            decl_type,
1099                            expr,
1100                        } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1101                        StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1102                        StepKind::AssignAsync {
1103                            var,
1104                            decl_type,
1105                            body,
1106                        } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1107                        StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1108                        StepKind::AwaitCapture {
1109                            out_var,
1110                            out_type,
1111                            task_var,
1112                        } => handlers::dispatch_await_capture(
1113                            out_var,
1114                            out_type.clone(),
1115                            task_var,
1116                            &mut cx,
1117                        ),
1118                        StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1119                        StepKind::Sleep { duration } => {
1120                            let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1121                            handlers::sleep(&mut cx, idx, &duration)
1122                        }
1123                        StepKind::FuncDef { .. }
1124                        | StepKind::Call { .. }
1125                        | StepKind::Return { .. }
1126                        | StepKind::While { .. }
1127                        | StepKind::Break
1128                        | StepKind::Continue
1129                        | StepKind::For { .. }
1130                        | StepKind::If { .. }
1131                        | StepKind::Timeout { .. }
1132                        | StepKind::WithIo { .. }
1133                        | StepKind::AssignCapture { .. } => {
1134                            unreachable!("compound steps dispatch in the outer match")
1135                        }
1136                    }?;
1137                    Ok(Flow::Done)
1138                }
1139            };
1140            flow_result
1141        };
1142
1143        let restore_result = restore_scopes(state, step.scope_exit);
1144        // Keeper expiry: drop spawn-time pins whose final producer step
1145        // just completed, so later consumer steps in the same task observe
1146        // EOF. Gated on slice identity, so nested bodies executing through
1147        // this same loop never discharge the worker's top-level map.
1148        let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1149            expiry.expire_step(steps, idx)
1150        } else {
1151            false
1152        };
1153        if expiry_drained {
1154            state.keeper_expiry = None;
1155        }
1156        let flow = flow_result?;
1157        restore_result?;
1158        match flow {
1159            Flow::Done => {}
1160            Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1161                return Ok(flow);
1162            }
1163        }
1164    }
1165
1166    // Poll anonymous background handles at end-of-pipeline. The shared
1167    // named_tasks entries are reaped only by the root context: task threads
1168    // must never block on sibling tasks, which may depend on this thread
1169    // via AWAIT (three-way deadlock). Un-awaited named tasks are still
1170    // reaped by the root end-poll, and explicitly awaited tasks join via
1171    // AWAIT. Entries are retained as Cancelled/Completed tombstones so
1172    // later AWAIT/CANCEL report precise errors.
1173    let reap_named = !state.inside_async;
1174    let has_bg = !state.bg_children.is_empty();
1175    let named_pending = |state: &ExecState<P>| {
1176        reap_named
1177            && state
1178                .named_tasks
1179                .lock()
1180                .unwrap_or_else(|e| e.into_inner())
1181                .values()
1182                .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1183    };
1184    let has_named = named_pending(state);
1185    if wait_at_end && (has_bg || has_named) {
1186        loop {
1187            let mut failed_status: Option<anyhow::Error> = None;
1188
1189            // Cancellation (deadline watcher or parent teardown) must break
1190            // the poll loop: without this, a stuck background handle would
1191            // hang the reaper forever. Flows into the shared fail-fast
1192            // teardown below.
1193            if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1194                failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1195            }
1196
1197            // 1. Poll anonymous background handles
1198            let mut i = 0;
1199            while i < state.bg_children.len() {
1200                match state.bg_children[i].try_wait() {
1201                    Ok(Some(status)) => {
1202                        if !status.success() && failed_status.is_none() {
1203                            failed_status =
1204                                Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1205                            break;
1206                        }
1207                        state.bg_children.swap_remove(i);
1208                    }
1209                    Ok(None) => {
1210                        i += 1;
1211                    }
1212                    Err(e) => {
1213                        if failed_status.is_none() {
1214                            failed_status = Some(e);
1215                        }
1216                        break;
1217                    }
1218                }
1219            }
1220
1221            // 2. Poll un-awaited named tasks (root context only). Each entry
1222            // is probed under a short entry lock; terminal entries are
1223            // retained as tombstones, never removed.
1224            if failed_status.is_none() && reap_named {
1225                let entries: Vec<(u64, Arc<TaskEntry>)> = {
1226                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1227                    named
1228                        .iter()
1229                        .map(|(id, entry)| (*id, Arc::clone(entry)))
1230                        .collect()
1231                };
1232                for (id, entry) in &entries {
1233                    enum Poll {
1234                        Pending,
1235                        CompletedOk,
1236                        CompletedErr(anyhow::Error),
1237                    }
1238                    let poll = {
1239                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1240                        match guard.phase {
1241                            TaskPhase::Running | TaskPhase::Awaiting => {
1242                                match guard.handle.as_mut() {
1243                                    Some(handle) => match handle.try_wait() {
1244                                        Ok(Some(status)) => {
1245                                            let _ = guard.handle.take();
1246                                            guard.phase = TaskPhase::Completed;
1247                                            if status.success() {
1248                                                Poll::CompletedOk
1249                                            } else {
1250                                                Poll::CompletedErr(anyhow::anyhow!(
1251                                                    "named ASYNC task {id} exited with status {status}"
1252                                                ))
1253                                            }
1254                                        }
1255                                        Ok(None) => Poll::Pending,
1256                                        Err(e) => {
1257                                            let _ = guard.handle.take();
1258                                            guard.phase = TaskPhase::Completed;
1259                                            Poll::CompletedErr(e)
1260                                        }
1261                                    },
1262                                    // Handle taken by a concurrent CANCEL/AWAIT
1263                                    // teardown; the barrier below rendezvouses.
1264                                    None => Poll::Pending,
1265                                }
1266                            }
1267                            TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1268                        }
1269                    };
1270                    match poll {
1271                        Poll::Pending => {}
1272                        Poll::CompletedOk => {
1273                            entry.finish_teardown();
1274                        }
1275                        Poll::CompletedErr(e) => {
1276                            entry.finish_teardown();
1277                            if failed_status.is_none() {
1278                                failed_status = Some(e);
1279                            }
1280                            break;
1281                        }
1282                    }
1283                }
1284            }
1285
1286            // 3. Fail-fast teardown (named entries are root-owned; task
1287            // threads only tear down their own anonymous children).
1288            // Handles are taken under short locks and killed outside every
1289            // lock; tombstones are retained.
1290            if let Some(err) = failed_status {
1291                for survivor in state.bg_children.iter_mut() {
1292                    let _ = survivor.kill();
1293                }
1294                if reap_named {
1295                    let entries: Vec<Arc<TaskEntry>> = {
1296                        let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1297                        named.values().cloned().collect()
1298                    };
1299                    let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1300                    for entry in &entries {
1301                        let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1302                        match guard.phase {
1303                            TaskPhase::Running | TaskPhase::Awaiting => {
1304                                guard.phase = TaskPhase::Cancelled;
1305                                if let Some(handle) = guard.handle.take() {
1306                                    to_kill.push((Arc::clone(entry), handle));
1307                                }
1308                            }
1309                            TaskPhase::Cancelled | TaskPhase::Completed => {}
1310                        }
1311                    }
1312                    for (entry, mut handle) in to_kill {
1313                        let _ = handle.kill();
1314                        entry.finish_teardown();
1315                    }
1316                }
1317                state.bg_children.clear();
1318                return Err(err);
1319            }
1320
1321            let bg_empty = state.bg_children.is_empty();
1322            if bg_empty && !named_pending(state) {
1323                return Ok(Flow::Done);
1324            }
1325            // Rendezvous: a concurrent CANCEL/AWAIT on another thread may
1326            // own teardown of a Cancelled-but-unreaped entry. Wait for it
1327            // instead of spinning, so this thread never outruns the join.
1328            if reap_named {
1329                let unreaped: Vec<Arc<TaskEntry>> = {
1330                    let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1331                    named
1332                        .values()
1333                        .filter(|entry| {
1334                            let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1335                            matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1336                        })
1337                        .cloned()
1338                        .collect()
1339                };
1340                for entry in &unreaped {
1341                    entry.wait_reaped();
1342                }
1343            }
1344            std::thread::sleep(std::time::Duration::from_millis(10));
1345        }
1346    }
1347
1348    Ok(Flow::Done)
1349}
1350
1351fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1352    for _ in 0..count {
1353        state.pop_scope()?;
1354    }
1355    Ok(())
1356}
1357
1358/// Execute a `REMOTE` body locally inside a fresh lexical scope: the
1359/// guest-mode path, where the shipped text keeps its `REMOTE` wrapper and
1360/// the session already fulfilled the transfer declarations. Scope,
1361/// pipes, and filesystem effects behave exactly like any local block;
1362/// control-flow signals crossing the block edge become step-numbered
1363/// errors, mirroring the pipeline-top mapping.
1364#[allow(clippy::too_many_arguments)]
1365pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1366    state: &mut ExecState<P>,
1367    process: &mut P,
1368    steps: &[Step],
1369    stdin: CommandStdin,
1370    expose_stdin: bool,
1371    out: Option<StreamHandle>,
1372    err: Option<StreamHandle>,
1373    out_pipe: Option<Arc<PipeInner>>,
1374    stdin_pipe: Option<Arc<PipeInner>>,
1375) -> Result<()> {
1376    let flow = execute_scoped_steps(
1377        state,
1378        process,
1379        steps,
1380        stdin,
1381        expose_stdin,
1382        out,
1383        err,
1384        out_pipe,
1385        stdin_pipe,
1386        true,
1387    )?;
1388    match flow {
1389        Flow::Done => Ok(()),
1390        Flow::Break { idx } => {
1391            bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1392        }
1393        Flow::Continue { idx } => {
1394            bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1395        }
1396        Flow::Return { idx, .. } => {
1397            bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1398        }
1399    }
1400}
1401
1402/// Execute steps inside a fresh lexical scope (IF branches, TIMEOUT bodies).
1403/// Blocks scope everything (LET/ENV/WORKDIR/WORKSPACE); only pipes and
1404/// filesystem effects cross. Restores even when the body fails. Propagates
1405/// Flow signals (BREAK/CONTINUE/RETURN) to the caller after restoring.
1406#[allow(clippy::too_many_arguments)]
1407pub(super) fn execute_scoped_steps<P: ProcessManager>(
1408    state: &mut ExecState<P>,
1409    process: &mut P,
1410    steps: &[Step],
1411    stdin: CommandStdin,
1412    expose_stdin: bool,
1413    out: Option<StreamHandle>,
1414    err: Option<StreamHandle>,
1415    out_pipe: Option<Arc<PipeInner>>,
1416    stdin_pipe: Option<Arc<PipeInner>>,
1417    wait_at_end: bool,
1418) -> Result<Flow> {
1419    state.push_scope();
1420    let res = execute_steps(
1421        state,
1422        process,
1423        steps,
1424        stdin,
1425        expose_stdin,
1426        out,
1427        err,
1428        out_pipe,
1429        stdin_pipe,
1430        wait_at_end,
1431    );
1432    // Restore the scope even when the body failed, but never let an
1433    // unwinding failure mask the body's own error.
1434    let pop_res = state.pop_scope();
1435    match (res, pop_res) {
1436        (Ok(flow), Ok(())) => Ok(flow),
1437        (Err(e), _) => Err(e),
1438        (Ok(_), Err(e)) => Err(e),
1439    }
1440}
1441
1442/// Dispatch one compound step (loops, functions, scoped wrappers) through
1443/// the Flow path. Called with the caller's generation/idx so assertion
1444/// windows and error attribution match the leaf pipeline.
1445fn dispatch_flow_step<P: ProcessManager>(
1446    cmd: &StepKind,
1447    cx: &mut StepCtx<'_, P>,
1448    generation: usize,
1449    idx: usize,
1450) -> Result<Flow> {
1451    match cmd {
1452        StepKind::FuncDef { name, params, body } => {
1453            handlers::define_func(cx, name, params, body)?;
1454            Ok(Flow::Done)
1455        }
1456        StepKind::Call { name, args } => {
1457            let _ = handlers::call_func_value(cx, idx, name, args)?;
1458            Ok(Flow::Done)
1459        }
1460        StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1461        StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1462        StepKind::Break => Ok(Flow::Break { idx }),
1463        StepKind::Continue => Ok(Flow::Continue { idx }),
1464        StepKind::For {
1465            key_var,
1466            key_type,
1467            var,
1468            var_type,
1469            in_expr,
1470            body,
1471        } => handlers::for_loop(
1472            cx,
1473            key_var.as_deref(),
1474            key_type.clone(),
1475            var,
1476            var_type.clone(),
1477            in_expr,
1478            body,
1479        ),
1480        StepKind::If {
1481            cond,
1482            then_body,
1483            else_ifs,
1484            else_body,
1485        } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1486        StepKind::Timeout { duration, body } => {
1487            let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1488            handlers::timeout(cx, idx, &duration, body)
1489        }
1490        StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1491        StepKind::AssignCapture {
1492            var,
1493            decl_type,
1494            cmd,
1495        } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1496        _ => {
1497            unreachable!("dispatch_flow_step handles only compound steps")
1498        }
1499    }
1500}