Skip to main content

kaish_kernel/scheduler/
scatter.rs

1//! Scatter/Gather — Parallel pipeline execution.
2//!
3//! Scatter splits input into items and runs the pipeline in parallel.
4//! Gather collects the parallel results.
5//!
6//! # Example
7//!
8//! ```text
9//! cat urls.txt | scatter | fetch url=${ITEM} | gather
10//! ```
11//!
12//! This reads URLs, then for each URL runs `fetch` in parallel,
13//! then collects all results.
14
15use std::sync::Arc;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::time::Duration;
18
19use tokio::sync::Semaphore;
20use tracing::Instrument;
21
22use crate::ast::{Command, Redirect, Value};
23use crate::dispatch::CommandDispatcher;
24use crate::duration::parse_duration;
25use crate::interpreter::ExecResult;
26use crate::tools::{ExecContext, ToolRegistry};
27
28use super::pipeline::{apply_redirects, PipelineRunner};
29
30/// Options for scatter operation.
31#[derive(Debug, Clone)]
32pub struct ScatterOptions {
33    /// Variable name to bind each item to (default: "ITEM").
34    pub var_name: String,
35    /// Maximum parallelism (default: 8).
36    pub limit: usize,
37    /// Per-worker timeout. When `Some`, each worker is cancelled after this
38    /// duration; the worker's external children get SIGTERM/SIGKILL and the
39    /// `ScatterResult.timed_out` flag is set.
40    pub timeout: Option<Duration>,
41}
42
43/// Options for gather operation.
44#[derive(Debug, Clone, Default)]
45pub struct GatherOptions {
46    /// `--lines`: emit each successful worker's raw `out` in item order instead
47    /// of JSONL rows — and HARD-ERROR (exit 123, no partial text) if any worker
48    /// failed, since bare lines cannot represent a failure. The text escape
49    /// hatch that keeps the old line mode's safety property.
50    pub lines: bool,
51    /// `--json` (the kernel-wide flag; scatter/gather own their output, so it
52    /// reaches the tool): render the result records as ONE JSON array instead
53    /// of JSONL rows. Same records, same `.data`.
54    pub json: bool,
55}
56
57impl Default for ScatterOptions {
58    fn default() -> Self {
59        Self {
60            var_name: "ITEM".to_string(),
61            limit: 8,
62            timeout: None,
63        }
64    }
65}
66
67/// One typed scatter item: the JSON element that fans out to a worker.
68///
69/// `json` is the source of truth — the worker binding derives from it via
70/// [`json_to_value_no_envelope`](crate::interpreter::json_to_value_no_envelope)
71/// (the exact conversion `for v in $(cmd)` uses), and the gather row's `item`
72/// field carries it typed. `label` is a char-safe truncated display form for
73/// spans and error messages.
74#[derive(Debug, Clone)]
75pub struct ScatterItem {
76    /// The element as JSON (string items are JSON strings).
77    pub json: serde_json::Value,
78    /// Compact display label for tracing and error text.
79    pub label: String,
80}
81
82impl ScatterItem {
83    fn new(json: serde_json::Value) -> Self {
84        let full = match &json {
85            serde_json::Value::String(s) => s.clone(),
86            other => other.to_string(),
87        };
88        // Char-safe truncation (a byte slice at 64 can split a UTF-8 char).
89        let label = if full.chars().count() > 64 {
90            let head: String = full.chars().take(64).collect();
91            format!("{head}...")
92        } else {
93            full
94        };
95        Self { json, label }
96    }
97
98    fn from_text_line(line: &str) -> Self {
99        Self::new(serde_json::Value::String(line.to_string()))
100    }
101}
102
103/// Result from a single scatter worker.
104#[derive(Debug, Clone)]
105pub struct ScatterResult {
106    /// The input item that was processed.
107    pub item: ScatterItem,
108    /// The execution result.
109    pub result: ExecResult,
110    /// Whether the worker was cancelled by the per-worker `--timeout`.
111    pub timed_out: bool,
112}
113
114/// Runs scatter/gather pipelines.
115///
116/// Uses a single dispatcher for sequential stages (pre_scatter, post_gather),
117/// and forks it per parallel worker via [`CommandDispatcher::fork`]. Each
118/// worker gets its own subkernel with snapshotted session state so they can
119/// run concurrently without racing on scope/cwd/aliases.
120pub struct ScatterGatherRunner {
121    tools: Arc<ToolRegistry>,
122    /// Full dispatch chain for sequential stages (pre_scatter, post_gather).
123    /// Parallel workers fork from this dispatcher.
124    sequential_dispatcher: Arc<dyn CommandDispatcher>,
125}
126
127impl ScatterGatherRunner {
128    /// Create a new scatter/gather runner.
129    ///
130    /// `dispatcher` drives sequential stages directly and serves as the fork
131    /// source for parallel workers.
132    pub fn new(
133        tools: Arc<ToolRegistry>,
134        dispatcher: Arc<dyn CommandDispatcher>,
135    ) -> Self {
136        Self { tools, sequential_dispatcher: dispatcher }
137    }
138
139    /// Execute a scatter/gather pipeline.
140    ///
141    /// The pipeline is split into three parts:
142    /// - pre_scatter: commands before scatter
143    /// - parallel: commands between scatter and gather
144    /// - post_gather: commands after gather
145    ///
146    /// Returns the final result after all stages complete.
147    #[tracing::instrument(level = "info", skip(self, pre_scatter, scatter_opts, parallel, gather_opts, post_gather, ctx), fields(item_count = tracing::field::Empty, parallelism = scatter_opts.limit))]
148    #[allow(clippy::too_many_arguments)]
149    pub async fn run(
150        &self,
151        pre_scatter: &[Command],
152        scatter_opts: ScatterOptions,
153        parallel: &[Command],
154        gather_opts: GatherOptions,
155        gather_redirects: &[Redirect],
156        post_gather: &[Command],
157        ctx: &mut ExecContext,
158    ) -> ExecResult {
159        let runner = PipelineRunner::new(self.tools.clone());
160
161        // Run pre-scatter commands to get input.
162        // Uses run_sequential to avoid async recursion (scatter → run → scatter).
163        let (text, data) = if pre_scatter.is_empty() {
164            // Use existing stdin — structured data, a buffered byte vector, or
165            // a lazy `pipe_stdin` (a frontend-seeded process-stdin pipe).
166            // `take_stdin` alone would miss the pipe; `read_stdin_to_text`
167            // prefers it.
168            let data = ctx.take_stdin_data();
169            let text = match ctx.read_stdin_to_text().await {
170                Ok(s) => s.unwrap_or_default(),
171                Err(e) => return ExecResult::failure(2, format!("scatter: {e}")),
172            };
173            (text, data)
174        } else {
175            let result = runner.run_sequential(pre_scatter, ctx, &*self.sequential_dispatcher).await;
176            if !result.ok() {
177                return result;
178            }
179            (result.text_out().into_owned(), result.data)
180        };
181
182        // Extract items from structured data or text
183        let items = match extract_items(data.as_ref(), &text) {
184            Ok(items) => items,
185            Err(msg) => return ExecResult::failure(1, msg),
186        };
187        if items.is_empty() {
188            return ExecResult::success("");
189        }
190
191        tracing::Span::current().record("item_count", items.len());
192
193        // Run parallel stage
194        let results = self
195            .run_parallel(&items, &scatter_opts, parallel, ctx)
196            .await;
197
198        // Gather per the GH #73 contract: JSONL result records by default (one
199        // row per worker, failures included), or `--lines` raw text. Exit codes
200        // are A′: 0 all ok · 123 any worker failed · 2 usage (clap layer).
201        let gathered = gather_results(&results, &gather_opts);
202
203        // `gather`'s own trailing redirect (`… | gather > results.jsonl | …`)
204        // must apply to gather's OWN result before anything downstream sees
205        // it — matching shell semantics where a file redirect on a pipeline
206        // stage wins over the pipe (`cmd > file | next` sends cmd's real
207        // stdout to the file; `next` reads nothing from cmd). Applying it
208        // unconditionally (regardless of exit code) matches a redirect being
209        // a file-descriptor operation independent of the command's success —
210        // `false > file` still creates the file. Previously this only ran
211        // when gather was the pipeline's last command, so a trailing
212        // `gather > file | jq` silently skipped the file and let the
213        // unredirected rows flow to `jq` instead.
214        let gathered = apply_redirects(gathered, gather_redirects, ctx, &*self.sequential_dispatcher).await;
215
216        // Run post-gather commands if any. A failed gather short-circuits —
217        // feeding partial/failed output onward would propagate corruption.
218        if post_gather.is_empty() || gathered.code != 0 {
219            gathered
220        } else {
221            ctx.set_stdin_with_data(
222                gathered.text_out().into_owned(),
223                gathered.data.clone(),
224            );
225            runner.run_sequential(post_gather, ctx, &*self.sequential_dispatcher).await
226        }
227    }
228
229    /// Run the parallel stage for all items.
230    ///
231    /// Each worker gets its own forked dispatcher via
232    /// [`CommandDispatcher::fork`]. The fork snapshots per-session state
233    /// (scope, cwd, aliases, user tools) so workers can run concurrently
234    /// without racing. Forks are cheap (Scope is COW, plus a few Arc bumps),
235    /// and they unlock the full dispatch chain inside workers — user tools,
236    /// `.kai` scripts, and `$(...)` in args all work.
237    #[tracing::instrument(level = "debug", skip(self, items, opts, commands, base_ctx), fields(worker_count = items.len()))]
238    async fn run_parallel(
239        &self,
240        items: &[ScatterItem],
241        opts: &ScatterOptions,
242        commands: &[Command],
243        base_ctx: &ExecContext,
244    ) -> Vec<ScatterResult> {
245        let semaphore = Arc::new(Semaphore::new(opts.limit));
246        let tools = self.tools.clone();
247        let var_name = opts.var_name.clone();
248
249        // Spawn parallel tasks
250        let mut handles = Vec::with_capacity(items.len());
251
252        for item in items.iter().cloned() {
253            let permit = semaphore.clone().acquire_owned().await;
254            let tools = tools.clone();
255            // Fork attached: the worker's cancel token is a child of the
256            // parent kernel's, so a parent cancel (request timeout, embedder
257            // Kernel::cancel) cascades into the worker and kills its
258            // external children via the wait_or_kill discipline.
259            let worker_dispatcher = self.sequential_dispatcher.fork_attached().await;
260            let commands = commands.to_vec();
261            let parent_token = base_ctx.cancel.clone();
262            let worker_token = parent_token.child_token();
263
264            // Build the worker context FROM THE PARENT, not from scratch. A
265            // from-scratch `ExecContext::with_backend_and_scope` starts
266            // `watchdog = None`; `dispatch_command` then syncs that `None` INTO
267            // the subkernel (kernel.rs `ec.watchdog = ctx.watchdog.clone()`),
268            // clobbering the fork's inherited watchdog — so inside a worker the
269            // script clock is gone and any `ctx.patient` hold suspends a
270            // *missing* timer, yielding false-positive request timeouts that
271            // kill the worker. `child_for_pipeline` clones exactly what a worker
272            // needs in one shot — watchdog, vfs_budget, aliases, ignore_config,
273            // output_limit, allow_external_commands, backend, cwd, scope,
274            // dispatcher — replacing the manual field-copy that was easy to let
275            // drift (and that dropped the watchdog). `base_ctx` is a borrow (not
276            // `'static`), so the child MUST be built here and MOVED into the
277            // spawn — it cannot be constructed inside the closure.
278            let mut worker_ctx = base_ctx.child_for_pipeline();
279            // Per-worker TYPED binding — the same json→Value conversion the
280            // for-loop uses for `$(cmd)` items (GH #73), so a record element
281            // subscripts as `${ITEM[k]}`.
282            worker_ctx.scope.set(
283                &var_name,
284                crate::interpreter::json_to_value_no_envelope(item.json.clone()),
285            );
286            // Per-worker cancel token (a child of the parent's), so the timeout
287            // timer and a parent cancel both reach this worker's externals.
288            worker_ctx.cancel = worker_token.clone();
289
290            // Per-worker timeout: spawn a delay task that cancels the worker's
291            // child token after `opts.timeout`. The cancel cascades into the
292            // worker's externals via the fork's cancel link. `timed_out_flag`
293            // distinguishes timeout from explicit parent cancellation when
294            // tagging ScatterResult.
295            let timed_out_flag = Arc::new(AtomicBool::new(false));
296            let timer_handle: Option<tokio::task::JoinHandle<()>> = opts.timeout.map(|d| {
297                let cancel = worker_token.clone();
298                let flag = timed_out_flag.clone();
299                tokio::spawn(async move {
300                    tokio::time::sleep(d).await;
301                    flag.store(true, Ordering::SeqCst);
302                    cancel.cancel();
303                })
304            });
305            let timed_out_check = timed_out_flag.clone();
306
307            let worker_span = tracing::debug_span!("scatter_worker", item = %item.label);
308            // Propagate the embedder's trace context across the spawn boundary so
309            // each worker's spans stay in the same trace. `.instrument` below
310            // provides the tracing parent; this provides the OTel parent.
311            let handle = tokio::spawn(crate::telemetry::bind_current_context(async move {
312                let _permit = permit; // Hold permit until done
313                let mut worker_ctx = worker_ctx; // moved in; built from parent above
314
315                // Run through PipelineRunner + dispatcher (full resolution chain).
316                // Uses run_sequential to avoid async recursion and infinite future size.
317                let runner = PipelineRunner::new(tools);
318                let mut result =
319                    runner.run_sequential(&commands, &mut worker_ctx, &*worker_dispatcher).await;
320
321                // Per-worker spill boundary. `run_sequential` never reaches the
322                // kernel's top-level post-run spill check (kernel.rs:2704), so
323                // without this each worker holds its FULL output in memory —
324                // N concurrent workers × large output evades the sandbox
325                // `output_limit` (10 workers × 1 GB = 10 GB resident before
326                // anything spills). Cap here, where the N× multiplication lives;
327                // `child_for_pipeline` shares the parent's `output_limit`, so
328                // workers cap against the same budget.
329                if worker_ctx.output_limit.is_enabled() {
330                    let _ = crate::output_limit::spill_if_needed(
331                        &mut result,
332                        &worker_ctx.output_limit,
333                    )
334                    .await;
335                }
336
337                // Worker finished — abort the timer if still pending so it
338                // doesn't fire a now-pointless cancel and idle resources.
339                if let Some(h) = timer_handle {
340                    h.abort();
341                }
342
343                // Completion wins ties (GH #132): a worker whose command
344                // finishes right as its timeout timer fires can read the
345                // flag AFTER the delay task sets it, even though its own
346                // result is a genuine, clean success. This isn't just a
347                // stale-read gap — `sleep`'s (and any similarly-built
348                // builtin's) own `tokio::select! { operation, cancelled() }`
349                // is unbiased: if cancellation has *already* been signaled by
350                // the time the operation's own timer also matures, tokio can
351                // still pick the operation's branch, so `result.ok()` can be
352                // `true` even after the flag was set and `cancel.cancel()`
353                // was called. The result's own success is the ground truth
354                // the flag can't override — a worker that truly finished
355                // successfully must never be reported as timed out, no
356                // matter what the racing flag says.
357                let timed_out = timed_out_check.load(Ordering::SeqCst) && !result.ok();
358
359                ScatterResult { item, result, timed_out }
360            }.instrument(worker_span)));
361
362            handles.push(handle);
363        }
364
365        // Collect results
366        let mut results = Vec::with_capacity(handles.len());
367        for handle in handles {
368            match handle.await {
369                Ok(result) => results.push(result),
370                Err(e) => {
371                    results.push(ScatterResult {
372                        item: ScatterItem::new(serde_json::Value::String(
373                            "<worker panicked>".to_string(),
374                        )),
375                        result: ExecResult::failure(1, format!("Task panicked: {}", e)),
376                        timed_out: false,
377                    });
378                }
379            }
380        }
381
382        results
383    }
384}
385
386/// Extract typed items from structured data or text (GH #73 contract).
387///
388/// Structured `.data` wins and fans out TYPED: a JSON array yields one item per
389/// element with the element's real type (a record element subscripts as
390/// `${ITEM[k]}` in the worker; number `1` and string `"1"` stay distinct). A
391/// `null` element is a loud error — a worker silently running with a null
392/// binding is corruption. A single non-array OBJECT is a loud error with a
393/// select-the-array hint (one worker running on the `{"jobs":[…]}` envelope is
394/// never what was meant); a single scalar is one item. Binary data is a loud
395/// error.
396///
397/// Plain-text stdin is split on newlines only — one item per line, each a
398/// string — matching the for-loop `$(cmd)` contract: trailing newlines trimmed
399/// once, each line's trailing `\r` stripped, whitespace within a line never
400/// split. Blank lines are SKIPPED (panel-ratified: a worker spawned on `""` is
401/// silent corruption of the most common input shape). Empty input yields zero
402/// items (the caller exits 0 with no rows).
403pub fn extract_items(data: Option<&Value>, text: &str) -> Result<Vec<ScatterItem>, String> {
404    // 1. Structured data wins over text (arch_data_iteration contract).
405    match data {
406        // JSON array — fan out per element, typed (seq/split/glob/find/jq).
407        Some(Value::Json(serde_json::Value::Array(arr))) => {
408            let mut items = Vec::with_capacity(arr.len());
409            for (i, elem) in arr.iter().enumerate() {
410                if elem.is_null() {
411                    return Err(format!(
412                        "scatter: item {i} is null — refusing to bind a worker to null \
413                         (filter it out first, e.g. jq 'map(select(. != null))')"
414                    ));
415                }
416                items.push(ScatterItem::new(elem.clone()));
417            }
418            return Ok(items);
419        }
420        // Kaish scalars — one typed item each.
421        Some(Value::String(s)) => {
422            return Ok(vec![ScatterItem::new(serde_json::Value::String(s.clone()))])
423        }
424        Some(Value::Int(i)) => return Ok(vec![ScatterItem::new(serde_json::json!(i))]),
425        Some(Value::Float(f)) => return Ok(vec![ScatterItem::new(serde_json::json!(f))]),
426        Some(Value::Bool(b)) => return Ok(vec![ScatterItem::new(serde_json::json!(b))]),
427        Some(Value::Null) => {
428            return Err("scatter: input is null — nothing to fan out".to_string())
429        }
430        // A single JSON object is almost always the unselected envelope around
431        // the array the caller meant — loud, with the fix in the message.
432        Some(Value::Json(serde_json::Value::Object(map))) => {
433            let hint = map
434                .iter()
435                .find(|(_, v)| v.is_array())
436                .map(|(k, _)| format!(" (did you mean jq '.{k}'?)"))
437                .unwrap_or_default();
438            return Err(format!(
439                "scatter: input is a single object, not an array — select the array to \
440                 fan out over{hint}"
441            ));
442        }
443        Some(Value::Json(serde_json::Value::Null)) => {
444            return Err("scatter: input is null — nothing to fan out".to_string())
445        }
446        // Single JSON scalar — one typed item.
447        Some(Value::Json(json)) => return Ok(vec![ScatterItem::new(json.clone())]),
448        // Binary can't bind a worker variable meaningfully — loud, never a
449        // placeholder string item.
450        Some(Value::Bytes(b)) => {
451            return Err(format!(
452                "scatter: input is binary ({} bytes) — decode it to text or JSON first",
453                b.len()
454            ))
455        }
456        // No structured data — fall through to plain-text newline-split.
457        None => {}
458    }
459
460    // 2. Plain text — newline-split, mirroring kernel.rs for-loop $(cmd)
461    // semantics; every text item is a string.
462    let trimmed = text.trim_end_matches(['\n', '\r']);
463    if trimmed.is_empty() {
464        return Ok(vec![]);
465    }
466    Ok(trimmed
467        .split('\n')
468        .map(|line| line.trim_end_matches('\r'))
469        .filter(|line| !line.is_empty())
470        .map(ScatterItem::from_text_line)
471        .collect())
472}
473
474/// Strip exactly one trailing newline (`\n` or `\r\n`), leaving everything
475/// else raw — the GH #73 contract for the row's `out` and `err` fields.
476fn strip_one_trailing_newline(s: &str) -> &str {
477    let s = s.strip_suffix('\n').unwrap_or(s);
478    s.strip_suffix('\r').unwrap_or(s)
479}
480
481/// Build one JSONL result record for a worker (GH #73 row schema).
482///
483/// `{"i":N, "item":<typed>, "ok":bool, "code":N, "out":"…", "err":"…"}` plus
484/// `data` (the worker's structured output, typed) when present and
485/// `timed_out:true` when it was. `i`/`item`/`ok`/`code`/`out`/`err` are always
486/// present (`err` deliberately so — omit-empty on the most-read field would
487/// make `${r[err]}` a loud missing-key error on every successful row). A
488/// timed-out worker reports `code` 124 (the `timeout(1)` prior) and `ok` false.
489///
490/// # Binary-output hazard
491///
492/// A worker's `out` is a `text_out()`-shaped string field, but the worker's
493/// `ExecResult` payload can be `OutputPayload::Bytes` — several builtins
494/// already produce it (`cat`/`head`/`tail`/`base64 -d`/`xxd -r`/`dd`/`tee`/
495/// external commands via `env`/`spawn`), so a worker running e.g. `cat
496/// binary.file` is not a hypothetical, it is reachable today. `text_out()`
497/// would lossily replace invalid UTF-8 with U+FFFD — silent data corruption
498/// riding through the row as if it were the worker's real text output. Per
499/// "crash beats corrupt" we go loud at row granularity instead: `try_text_out`
500/// catches it, the row is forced `ok:false` with a clear `err` (never a
501/// lossily-decoded `out`), and the OTHER rows are unaffected — see
502/// `docs/binary-data.md` for the broader binary-data plan.
503fn result_row(i: usize, r: &ScatterResult) -> serde_json::Value {
504    let mut ok = r.result.ok() && !r.timed_out;
505    let mut code = if r.timed_out { 124 } else { r.result.code };
506
507    let (out_text, err_text) = match r.result.try_text_out() {
508        Ok(text) => (
509            strip_one_trailing_newline(&text).to_string(),
510            strip_one_trailing_newline(&r.result.err).to_string(),
511        ),
512        Err(e) => {
513            ok = false;
514            if code == 0 {
515                code = 1;
516            }
517            (
518                String::new(),
519                format!(
520                    "binary worker output not representable as text ({} bytes) — \
521                     encode it in the worker (base64/xxd)",
522                    e.len
523                ),
524            )
525        }
526    };
527
528    let mut row = serde_json::Map::new();
529    row.insert("i".into(), serde_json::json!(i));
530    row.insert("item".into(), r.item.json.clone());
531    row.insert("ok".into(), serde_json::json!(ok));
532    row.insert("code".into(), serde_json::json!(code));
533    row.insert("out".into(), serde_json::json!(out_text));
534    row.insert("err".into(), serde_json::json!(err_text));
535    if let Some(data) = &r.result.data {
536        row.insert("data".into(), kaish_types::value_to_json(data));
537    }
538    // A latched worker (exit 2 under `set -o latch`) is otherwise
539    // indistinguishable from a plain failure in the row — carry the nonce so a
540    // caller can act on the gate straight from the row (GH #124 part 3).
541    // Infallible: LatchRequest is String/Vec<String>/u64 fields only.
542    if let Some(latch) = &r.result.latch
543        && let Ok(v) = serde_json::to_value(latch)
544    {
545        row.insert("latch".into(), v);
546    }
547    if r.timed_out {
548        row.insert("timed_out".into(), serde_json::json!(true));
549    }
550    serde_json::Value::Object(row)
551}
552
553/// Render gathered worker results as an [`ExecResult`] (GH #73 contract).
554///
555/// Default: JSONL — one compact result record per worker, in item order, EVERY
556/// worker including failures. One source, three views: the pipe text is the
557/// JSONL, `.data` is the typed record array (so `for r in $(… | gather)`
558/// iterates records and post-gather stages see typed stdin), and the kernel
559/// `--json` flag renders the same array as one JSON document via `rich_json`.
560///
561/// `--lines`: each successful worker's raw `out` in item order — and a HARD
562/// error (no partial text) if any worker failed, because bare lines cannot
563/// represent a failure (the old line mode's safety property, kept as a flag).
564///
565/// Exit codes (A′): `0` all workers ok · `123` any worker failed, partial or
566/// total (timeouts count) — partial-vs-total is distinguished in the rows.
567fn gather_results(results: &[ScatterResult], opts: &GatherOptions) -> ExecResult {
568    // A worker's binary stdout that can't decode as text is a failure for
569    // gather's purposes too — see `result_row`'s hazard doc. Folding it into
570    // `failed` here keeps the overall exit code (0 vs 123) honest: a `--lines`
571    // or JSONL caller checking `$?` must see non-zero, not a silent "0 all
572    // ok" while one row was actually corruption-guarded away.
573    let is_unrepresentable = |r: &ScatterResult| r.result.try_text_out().is_err();
574
575    let failed: Vec<&ScatterResult> = results
576        .iter()
577        .filter(|r| !r.result.ok() || r.timed_out || is_unrepresentable(r))
578        .collect();
579    let code = if failed.is_empty() { 0 } else { 123 };
580    let err = if failed.is_empty() {
581        String::new()
582    } else {
583        let names = failed
584            .iter()
585            .map(|r| {
586                if is_unrepresentable(r) {
587                    format!("{} (binary output not representable as text)", r.item.label)
588                } else {
589                    r.item.label.clone()
590                }
591            })
592            .collect::<Vec<_>>()
593            .join(", ");
594        format!("gather: {} of {} worker(s) failed: {names}", failed.len(), results.len())
595    };
596
597    if opts.lines {
598        // Bare lines can't carry a failure — refuse with no partial text
599        // rather than silently dropping rows. This also covers binary output
600        // (folded into `failed` above): `--lines` is a text-only escape
601        // hatch, and a U+FFFD-laden line would be exactly the silent
602        // corruption this hardening pass exists to prevent.
603        if !failed.is_empty() {
604            return ExecResult::failure(code, format!("{err} (drop --lines to get per-worker rows)"));
605        }
606        let text = results
607            .iter()
608            .map(|r| strip_one_trailing_newline(&r.result.text_out()).to_string())
609            .collect::<Vec<_>>()
610            .join("\n");
611        return ExecResult::success(text);
612    }
613
614    let rows: Vec<serde_json::Value> =
615        results.iter().enumerate().map(|(i, r)| result_row(i, r)).collect();
616    let text = if opts.json {
617        // `--json`: the same records as one JSON document.
618        serde_json::to_string_pretty(&rows).unwrap_or_default()
619    } else {
620        // Default: JSONL — one compact record per line.
621        rows.iter().map(|row| row.to_string()).collect::<Vec<_>>().join("\n")
622    };
623    let array = serde_json::Value::Array(rows);
624    ExecResult::from_parts(code, text, err, Some(Value::Json(array)))
625}
626
627/// Human-readable repr of a `Value` for a "wrong type" error message —
628/// deliberately not `Debug` (whose `String("five")` quoting/enum-tag noise
629/// reads badly to a user who just typed `--limit five`).
630fn describe_value(v: &Value) -> String {
631    match v {
632        Value::Null => "null".to_string(),
633        Value::Bool(b) => b.to_string(),
634        Value::Int(n) => n.to_string(),
635        Value::Float(f) => f.to_string(),
636        Value::String(s) => format!("{s:?}"),
637        Value::Json(j) => j.to_string(),
638        Value::Bytes(b) => format!("<{} bytes>", b.len()),
639    }
640}
641
642/// Parse scatter options from tool args.
643///
644/// A flag key *present* in `args.named` with a value of the wrong type is a
645/// loud `Err`, never a silent fall-back to the default — `scatter --limit
646/// five` must not quietly run at the default limit, and `scatter --as 42`
647/// must not quietly bind `$ITEM`. (An *absent* or unresolved flag falls back
648/// to a bare boolean earlier, at the pipeline arg-binding layer — that lenient
649/// path is unrelated and untouched here.)
650pub fn parse_scatter_options(args: &crate::tools::ToolArgs) -> Result<ScatterOptions, String> {
651    let mut opts = ScatterOptions::default();
652
653    match args.named.get("as") {
654        None => {}
655        Some(Value::String(name)) => opts.var_name = name.clone(),
656        Some(other) => {
657            return Err(format!(
658                "scatter --as: expected a variable name, got {}",
659                describe_value(other)
660            ))
661        }
662    }
663
664    match args.named.get("limit") {
665        None => {}
666        Some(Value::Int(n)) => opts.limit = clamp_scatter_limit(*n),
667        // Values from variables often stringify (`--limit "$n"`) — coerce a
668        // numeric string the same as an int.
669        Some(Value::String(s)) => match s.trim().parse::<i64>() {
670            Ok(n) => opts.limit = clamp_scatter_limit(n),
671            Err(_) => {
672                return Err(format!(
673                    "scatter --limit: expected a positive integer, got {}",
674                    describe_value(&Value::String(s.clone()))
675                ))
676            }
677        },
678        Some(other) => {
679            return Err(format!(
680                "scatter --limit: expected a positive integer, got {}",
681                describe_value(other)
682            ))
683        }
684    }
685
686    // --timeout DURATION: per-worker timeout. Accepts the same forms as the
687    // `timeout` builtin (30, 5s, 500ms, 2m, 1h). A present-but-invalid value
688    // is a loud Err — a typo here must not silently disable cancellation.
689    match args.named.get("timeout") {
690        None => {}
691        Some(Value::String(s)) => match parse_duration(s) {
692            Some(d) => opts.timeout = Some(d),
693            None => {
694                return Err(format!(
695                    "scatter --timeout: invalid duration {} (try: 30, 5s, 500ms, 2m, 1h)",
696                    describe_value(&Value::String(s.clone()))
697                ))
698            }
699        },
700        Some(Value::Int(n)) if *n >= 0 => opts.timeout = Some(Duration::from_secs(*n as u64)),
701        Some(other) => {
702            return Err(format!(
703                "scatter --timeout: expected a non-negative duration, got {}",
704                describe_value(other)
705            ))
706        }
707    }
708
709    Ok(opts)
710}
711
712/// Clamp a requested `--limit` to `[1, SCATTER_LIMIT_MAX]`, warning (not
713/// erroring) when the ceiling clamps a value down — this ceiling exists to
714/// protect the host, not to reject user input, so it stays a warn+clamp.
715fn clamp_scatter_limit(requested: i64) -> usize {
716    let clamped = requested.clamp(1, SCATTER_LIMIT_MAX as i64);
717    if requested > SCATTER_LIMIT_MAX as i64 {
718        tracing::warn!(
719            target: "kaish::scatter",
720            requested = requested,
721            ceiling = SCATTER_LIMIT_MAX,
722            "scatter limit clamped to ceiling"
723        );
724    }
725    clamped as usize
726}
727
728/// Upper bound on the concurrency `scatter --limit N` accepts. Users who
729/// ask for more get a `tracing::warn` and are clamped to this value —
730/// silent clamping would violate the "no silent fallbacks" rule.
731pub const SCATTER_LIMIT_MAX: usize = 10_000;
732
733/// Parse gather options from tool args.
734///
735/// Returns `Err` for a present-but-wrong-typed flag value, mirroring
736/// [`parse_scatter_options`]. Today gather's only value-carrying flags are
737/// boolean (`--lines`/`--json`), so this can't yet fail — the `Result` return
738/// keeps the signature symmetric with scatter's and ready for the next
739/// value-carrying gather flag.
740pub fn parse_gather_options(args: &crate::tools::ToolArgs) -> Result<GatherOptions, String> {
741    let mut opts = GatherOptions::default();
742
743    if args.has_flag("lines") {
744        opts.lines = true;
745    }
746
747    if args.has_flag("json") {
748        opts.json = true;
749    }
750
751    Ok(opts)
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757
758    fn labels(items: &[ScatterItem]) -> Vec<String> {
759        items.iter().map(|i| i.label.clone()).collect()
760    }
761
762    fn item(s: &str) -> ScatterItem {
763        ScatterItem::new(serde_json::Value::String(s.to_string()))
764    }
765
766    #[test]
767    fn test_extract_items_structured_json_array() {
768        let data = Value::Json(serde_json::json!(["a", "b", "c"]));
769        let items = extract_items(Some(&data), "").unwrap();
770        assert_eq!(labels(&items), vec!["a", "b", "c"]);
771    }
772
773    #[test]
774    fn test_extract_items_structured_mixed_types_stay_typed() {
775        // GH #73: number 1 and string "1" must remain distinct through the
776        // fan-out — the old Vec<String> path conflated them silently.
777        let data = Value::Json(serde_json::json!([1, "1", true, {"id": 7}]));
778        let items = extract_items(Some(&data), "").unwrap();
779        assert_eq!(items[0].json, serde_json::json!(1));
780        assert_eq!(items[1].json, serde_json::json!("1"));
781        assert_ne!(items[0].json, items[1].json, "1 and \"1\" must not conflate");
782        assert_eq!(items[2].json, serde_json::json!(true));
783        assert_eq!(items[3].json, serde_json::json!({"id": 7}));
784    }
785
786    #[test]
787    fn test_extract_items_null_element_is_loud() {
788        let data = Value::Json(serde_json::json!(["a", null, "c"]));
789        let err = extract_items(Some(&data), "").unwrap_err();
790        assert!(err.contains("null"), "should name the problem: {err}");
791        assert!(err.contains("item 1"), "should name the position: {err}");
792    }
793
794    #[test]
795    fn test_extract_items_single_object_is_loud_with_hint() {
796        let data = Value::Json(serde_json::json!({"jobs": [1, 2]}));
797        let err = extract_items(Some(&data), "").unwrap_err();
798        assert!(err.contains("single object"), "{err}");
799        assert!(err.contains("jq '.jobs'"), "should hint the array key: {err}");
800    }
801
802    #[test]
803    fn test_extract_items_binary_is_loud() {
804        let data = Value::Bytes(vec![0, 1, 2]);
805        let err = extract_items(Some(&data), "").unwrap_err();
806        assert!(err.contains("binary"), "{err}");
807    }
808
809    #[test]
810    fn test_extract_items_structured_string() {
811        let data = Value::String("single".into());
812        let items = extract_items(Some(&data), "").unwrap();
813        assert_eq!(labels(&items), vec!["single"]);
814    }
815
816    #[test]
817    fn test_extract_items_single_line_text() {
818        let items = extract_items(None, "hello").unwrap();
819        assert_eq!(labels(&items), vec!["hello"]);
820    }
821
822    #[test]
823    fn test_extract_items_empty() {
824        let items = extract_items(None, "").unwrap();
825        assert!(items.is_empty());
826    }
827
828    #[test]
829    fn test_extract_items_multiline_fans_out_per_line() {
830        let items = extract_items(None, "one\ntwo\nthree").unwrap();
831        assert_eq!(labels(&items), vec!["one", "two", "three"]);
832    }
833
834    #[test]
835    fn test_extract_items_trailing_newline_no_phantom_item() {
836        let items = extract_items(None, "one\ntwo\n").unwrap();
837        assert_eq!(labels(&items), vec!["one", "two"]);
838    }
839
840    #[test]
841    fn test_extract_items_crlf_per_line() {
842        let items = extract_items(None, "one\r\ntwo\r\n").unwrap();
843        assert_eq!(labels(&items), vec!["one", "two"]);
844    }
845
846    #[test]
847    fn test_extract_items_blank_lines_skipped() {
848        // GH #73 panel finding: a worker spawned on "" is silent corruption of
849        // the most common input shape — blank lines are skipped, not items.
850        let items = extract_items(None, "a\n\nb").unwrap();
851        assert_eq!(labels(&items), vec!["a", "b"]);
852    }
853
854    #[test]
855    fn test_extract_items_whitespace_within_line_not_split() {
856        let items = extract_items(None, "a b\nc d").unwrap();
857        assert_eq!(labels(&items), vec!["a b", "c d"]);
858    }
859
860    #[test]
861    fn test_extract_items_only_newlines_is_empty() {
862        let items = extract_items(None, "\n\n").unwrap();
863        assert!(items.is_empty());
864    }
865
866    #[test]
867    fn test_extract_items_structured_overrides_text() {
868        let data = Value::Json(serde_json::json!(["x", "y"]));
869        let items = extract_items(Some(&data), "ignored\ntext").unwrap();
870        assert_eq!(labels(&items), vec!["x", "y"]);
871    }
872
873    #[test]
874    fn test_item_label_truncates_on_char_boundary() {
875        // 100 multibyte chars — a byte-slice truncation would panic.
876        let long: String = "é".repeat(100);
877        let it = ScatterItem::new(serde_json::Value::String(long));
878        assert!(it.label.ends_with("..."));
879        assert_eq!(it.label.chars().count(), 67);
880    }
881
882    #[test]
883    fn test_gather_results_jsonl_rows_carry_everything() {
884        let results = vec![
885            ScatterResult {
886                item: item("a"),
887                result: ExecResult::success("result_a\n"),
888                timed_out: false,
889            },
890            ScatterResult {
891                item: item("b"),
892                result: ExecResult::failure(7, "boom\n"),
893                timed_out: false,
894            },
895        ];
896        let out = gather_results(&results, &GatherOptions::default());
897        assert_eq!(out.code, 123, "any failure → 123 (A′)");
898        let rows: Vec<serde_json::Value> = out
899            .text_out()
900            .lines()
901            .map(|l| serde_json::from_str(l).unwrap())
902            .collect();
903        assert_eq!(rows.len(), 2, "every worker gets a row, failures included");
904        assert_eq!(rows[0]["i"], 0);
905        assert_eq!(rows[0]["item"], "a");
906        assert_eq!(rows[0]["ok"], true);
907        assert_eq!(rows[0]["out"], "result_a", "trailing newline stripped");
908        assert_eq!(rows[0]["err"], "", "err always present");
909        assert!(rows[0].get("timed_out").is_none(), "omit-false");
910        assert!(rows[0].get("data").is_none(), "omit-empty");
911        assert_eq!(rows[1]["i"], 1);
912        assert_eq!(rows[1]["ok"], false);
913        assert_eq!(rows[1]["code"], 7);
914        assert_eq!(rows[1]["err"], "boom");
915        // .data carries the typed array for iteration / post-gather.
916        assert!(matches!(out.data, Some(Value::Json(serde_json::Value::Array(_)))));
917    }
918
919    #[test]
920    fn test_gather_results_all_ok_is_zero() {
921        let results = vec![ScatterResult {
922            item: item("a"),
923            result: ExecResult::success("x"),
924            timed_out: false,
925        }];
926        let out = gather_results(&results, &GatherOptions::default());
927        assert_eq!(out.code, 0);
928        assert!(out.err.is_empty());
929    }
930
931    #[test]
932    fn test_gather_results_timeout_row_is_124() {
933        let results = vec![ScatterResult {
934            item: item("slow"),
935            result: ExecResult::failure(1, "cancelled"),
936            timed_out: true,
937        }];
938        let out = gather_results(&results, &GatherOptions::default());
939        assert_eq!(out.code, 123);
940        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
941        assert_eq!(row["code"], 124, "timeout reports the timeout(1) code");
942        assert_eq!(row["ok"], false);
943        assert_eq!(row["timed_out"], true);
944    }
945
946    #[test]
947    fn test_gather_results_typed_record_item_in_row() {
948        let results = vec![ScatterResult {
949            item: ScatterItem::new(serde_json::json!({"id": 3, "host": "web1"})),
950            result: ExecResult::success("ok"),
951            timed_out: false,
952        }];
953        let out = gather_results(&results, &GatherOptions::default());
954        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
955        assert_eq!(row["item"]["id"], 3, "row item is the TYPED value, not a string");
956    }
957
958    #[test]
959    fn test_gather_results_worker_data_rides_the_row() {
960        let mut r = ExecResult::success("text");
961        r.data = Some(Value::Json(serde_json::json!({"k": 1})));
962        let results = vec![ScatterResult { item: item("a"), result: r, timed_out: false }];
963        let out = gather_results(&results, &GatherOptions::default());
964        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
965        assert_eq!(row["data"]["k"], 1, "worker .data lands typed in the row");
966        assert_eq!(row["out"], "text", "out stays alongside data");
967    }
968
969    #[test]
970    fn test_gather_results_worker_latch_rides_the_row() {
971        // GH #124 part 3: a latched worker (exit 2 under `set -o latch`) is
972        // otherwise indistinguishable from a plain failure in the row — the
973        // nonce must ride along so a caller can act on the gate from the row.
974        use kaish_types::result::LatchRequest;
975
976        let mut r = ExecResult::failure(2, "rm: confirmation required (latch enabled)");
977        r.latch = Some(Box::new(LatchRequest {
978            nonce: "a3f7b2c1".to_string(),
979            command: "rm".to_string(),
980            paths: vec!["precious.txt".to_string()],
981            hint: "rm --confirm=\"a3f7b2c1\" precious.txt".to_string(),
982            tool: "rm".to_string(),
983            argv: vec!["precious.txt".to_string()],
984            ttl: 60,
985            job_id: None,
986        }));
987        let results = vec![ScatterResult { item: item("a"), result: r, timed_out: false }];
988        let out = gather_results(&results, &GatherOptions::default());
989        assert_eq!(out.code, 123, "a latched worker still counts as failed for gather's exit code");
990        let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
991        assert_eq!(row["ok"], false);
992        assert_eq!(row["code"], 2);
993        assert_eq!(
994            row["latch"]["nonce"], "a3f7b2c1",
995            "the latch nonce must ride the row: {row}"
996        );
997        assert_eq!(row["latch"]["command"], "rm");
998    }
999
1000    #[test]
1001    fn test_gather_results_lines_happy_path() {
1002        let results = vec![
1003            ScatterResult { item: item("a"), result: ExecResult::success("result_a\n"), timed_out: false },
1004            ScatterResult { item: item("b"), result: ExecResult::success("result_b"), timed_out: false },
1005        ];
1006        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1007        assert_eq!(out.code, 0);
1008        assert_eq!(&*out.text_out(), "result_a\nresult_b");
1009    }
1010
1011    #[test]
1012    fn test_gather_results_lines_hard_errors_on_any_failure() {
1013        // Bare lines can't represent a failure — no partial text, loud 123.
1014        let results = vec![
1015            ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1016            ScatterResult { item: item("b"), result: ExecResult::failure(1, "boom"), timed_out: false },
1017        ];
1018        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1019        assert_eq!(out.code, 123);
1020        assert!(out.text_out().is_empty(), "no partial text on --lines failure");
1021        assert!(out.err.contains("b"), "names the failed item: {}", out.err);
1022    }
1023
1024    #[test]
1025    fn test_parse_scatter_options() {
1026        use crate::tools::ToolArgs;
1027
1028        let mut args = ToolArgs::new();
1029        args.named.insert("as".to_string(), Value::String("URL".to_string()));
1030        args.named.insert("limit".to_string(), Value::Int(4));
1031
1032        let opts = parse_scatter_options(&args).unwrap();
1033        assert_eq!(opts.var_name, "URL");
1034        assert_eq!(opts.limit, 4);
1035    }
1036
1037    #[test]
1038    fn test_parse_gather_options() {
1039        use crate::tools::ToolArgs;
1040
1041        let mut args = ToolArgs::new();
1042        args.flags.insert("lines".to_string());
1043
1044        let opts = parse_gather_options(&args).unwrap();
1045        assert!(opts.lines);
1046        assert!(!parse_gather_options(&ToolArgs::new()).unwrap().lines, "default is JSONL");
1047    }
1048
1049    #[test]
1050    fn scatter_limit_clamps_to_ceiling() {
1051        use crate::tools::ToolArgs;
1052
1053        let mut args = ToolArgs::new();
1054        args.named.insert("limit".to_string(), Value::Int(999_999));
1055        let opts = parse_scatter_options(&args).unwrap();
1056        assert_eq!(opts.limit, SCATTER_LIMIT_MAX);
1057    }
1058
1059    #[test]
1060    fn scatter_limit_raises_zero_to_one() {
1061        use crate::tools::ToolArgs;
1062
1063        let mut args = ToolArgs::new();
1064        args.named.insert("limit".to_string(), Value::Int(0));
1065        let opts = parse_scatter_options(&args).unwrap();
1066        assert_eq!(opts.limit, 1);
1067    }
1068
1069    #[test]
1070    fn scatter_limit_raises_negative_to_one() {
1071        use crate::tools::ToolArgs;
1072
1073        let mut args = ToolArgs::new();
1074        args.named.insert("limit".to_string(), Value::Int(-42));
1075        let opts = parse_scatter_options(&args).unwrap();
1076        assert_eq!(opts.limit, 1);
1077    }
1078
1079    #[test]
1080    fn scatter_limit_preserves_valid_values() {
1081        use crate::tools::ToolArgs;
1082
1083        let mut args = ToolArgs::new();
1084        args.named.insert("limit".to_string(), Value::Int(500));
1085        let opts = parse_scatter_options(&args).unwrap();
1086        assert_eq!(opts.limit, 500);
1087    }
1088
1089    // ── FIX A: loud on present-but-wrong-typed flag values ──
1090
1091    #[test]
1092    fn scatter_limit_wrong_type_is_loud_error() {
1093        use crate::tools::ToolArgs;
1094
1095        let mut args = ToolArgs::new();
1096        args.named.insert("limit".to_string(), Value::String("five".to_string()));
1097        let err = parse_scatter_options(&args).unwrap_err();
1098        assert!(err.contains("--limit"), "{err}");
1099        assert!(err.contains("five"), "{err}");
1100    }
1101
1102    #[test]
1103    fn scatter_limit_bool_is_loud_error() {
1104        use crate::tools::ToolArgs;
1105
1106        let mut args = ToolArgs::new();
1107        args.named.insert("limit".to_string(), Value::Bool(true));
1108        let err = parse_scatter_options(&args).unwrap_err();
1109        assert!(err.contains("--limit"), "{err}");
1110    }
1111
1112    #[test]
1113    fn scatter_limit_numeric_string_coerces() {
1114        // Values from variables often stringify: `scatter --limit "$n"`.
1115        use crate::tools::ToolArgs;
1116
1117        let mut args = ToolArgs::new();
1118        args.named.insert("limit".to_string(), Value::String("5".to_string()));
1119        let opts = parse_scatter_options(&args).unwrap();
1120        assert_eq!(opts.limit, 5);
1121    }
1122
1123    #[test]
1124    fn scatter_as_wrong_type_is_loud_error() {
1125        use crate::tools::ToolArgs;
1126
1127        let mut args = ToolArgs::new();
1128        args.named.insert("as".to_string(), Value::Int(42));
1129        let err = parse_scatter_options(&args).unwrap_err();
1130        assert!(err.contains("--as"), "{err}");
1131        assert!(err.contains("42"), "{err}");
1132    }
1133
1134    #[test]
1135    fn scatter_timeout_negative_int_is_loud_error() {
1136        use crate::tools::ToolArgs;
1137
1138        let mut args = ToolArgs::new();
1139        args.named.insert("timeout".to_string(), Value::Int(-5));
1140        let err = parse_scatter_options(&args).unwrap_err();
1141        assert!(err.contains("--timeout"), "{err}");
1142    }
1143
1144    #[test]
1145    fn scatter_timeout_unparseable_string_is_loud_error() {
1146        use crate::tools::ToolArgs;
1147
1148        let mut args = ToolArgs::new();
1149        args.named.insert("timeout".to_string(), Value::String("banana".to_string()));
1150        let err = parse_scatter_options(&args).unwrap_err();
1151        assert!(err.contains("--timeout"), "{err}");
1152        assert!(err.contains("banana"), "{err}");
1153    }
1154
1155    #[test]
1156    fn scatter_timeout_valid_duration_string_parses() {
1157        use crate::tools::ToolArgs;
1158
1159        let mut args = ToolArgs::new();
1160        args.named.insert("timeout".to_string(), Value::String("5s".to_string()));
1161        let opts = parse_scatter_options(&args).unwrap();
1162        assert_eq!(opts.timeout, Some(Duration::from_secs(5)));
1163    }
1164
1165    #[test]
1166    fn scatter_timeout_nonnegative_int_is_seconds() {
1167        use crate::tools::ToolArgs;
1168
1169        let mut args = ToolArgs::new();
1170        args.named.insert("timeout".to_string(), Value::Int(30));
1171        let opts = parse_scatter_options(&args).unwrap();
1172        assert_eq!(opts.timeout, Some(Duration::from_secs(30)));
1173    }
1174
1175    // ── FIX C: binary worker output must not silently corrupt to U+FFFD ──
1176
1177    fn binary_result(invalid_utf8: Vec<u8>) -> ExecResult {
1178        ExecResult::success_bytes(invalid_utf8)
1179    }
1180
1181    #[test]
1182    fn gather_row_goes_loud_not_lossy_on_binary_out() {
1183        // 0xFF is never valid UTF-8 on its own — text_out() would replace it
1184        // with U+FFFD; try_text_out() must catch it instead.
1185        let results = vec![ScatterResult {
1186            item: item("bin"),
1187            result: binary_result(vec![0xFF, 0xFE, 0x00, 0x01]),
1188            timed_out: false,
1189        }];
1190        let out = gather_results(&results, &GatherOptions::default());
1191        assert_eq!(out.code, 123, "a binary row flips the overall exit code too");
1192        let row: serde_json::Value =
1193            serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
1194        assert_eq!(row["ok"], false, "binary output must not be silently ok:true");
1195        assert_ne!(row["code"], 0, "must carry a nonzero code");
1196        assert!(row["out"].as_str().unwrap().is_empty(), "no lossy text in out");
1197        let err_text = row["err"].as_str().unwrap();
1198        assert!(err_text.contains("binary"), "{err_text}");
1199        assert!(!err_text.contains('\u{FFFD}'), "must not carry U+FFFD: {err_text}");
1200    }
1201
1202    #[test]
1203    fn gather_lines_hard_errors_on_binary_out() {
1204        // --lines is the raw-text escape hatch; binary must hard-error the
1205        // whole gather rather than emit a U+FFFD-laden line.
1206        let results = vec![
1207            ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1208            ScatterResult {
1209                item: item("bin"),
1210                result: binary_result(vec![0xFF, 0xFE]),
1211                timed_out: false,
1212            },
1213        ];
1214        let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1215        assert_eq!(out.code, 123);
1216        assert!(out.text_out().is_empty(), "no partial/lossy text on binary --lines failure");
1217        assert!(!out.err.contains('\u{FFFD}'), "must not carry U+FFFD: {}", out.err);
1218        assert!(out.err.contains("binary") || out.err.contains("bin"), "{}", out.err);
1219    }
1220
1221    // ── FIX D: workers must inherit the parent's watchdog ──
1222
1223    fn ctx_with_memory_fs() -> ExecContext {
1224        use crate::vfs::{MemoryFs, VfsRouter};
1225        use std::sync::Arc;
1226        let mut vfs = VfsRouter::new();
1227        vfs.mount("/", MemoryFs::new());
1228        ExecContext::new(Arc::new(vfs))
1229    }
1230
1231    #[test]
1232    fn worker_ctx_inherits_parent_watchdog() {
1233        use crate::watchdog::Watchdog;
1234        use std::sync::Arc;
1235
1236        let mut parent = ctx_with_memory_fs();
1237        parent.watchdog = Some(Arc::new(Watchdog::new(Duration::from_secs(30))));
1238
1239        // The fix: workers are built via `child_for_pipeline`, which clones the
1240        // parent's watchdog. The old from-scratch `with_backend_and_scope`
1241        // path (below) dropped it — this test would fail against that path.
1242        let worker_ctx = parent.child_for_pipeline();
1243        assert!(
1244            worker_ctx.watchdog.is_some(),
1245            "worker must carry the parent's script watchdog, not None"
1246        );
1247
1248        // Document the trap the fix closes: the old construction starts with a
1249        // None watchdog, which dispatch_command then syncs into the subkernel.
1250        let from_scratch =
1251            ExecContext::with_backend_and_scope(parent.backend.clone(), parent.scope.clone());
1252        assert!(
1253            from_scratch.watchdog.is_none(),
1254            "the abandoned from-scratch path is exactly why the worker lost its watchdog"
1255        );
1256    }
1257
1258    // ── FIX E: workers cap output against the shared spill budget ──
1259
1260    #[tokio::test]
1261    async fn worker_spills_over_the_shared_output_limit() {
1262        use crate::output_limit::{spill_if_needed, OutputLimitConfig};
1263
1264        // Small in-memory limit (no disk writes in tests — CLAUDE.md).
1265        let mut cfg = OutputLimitConfig::agent().in_memory();
1266        cfg.set_limit(Some(64));
1267
1268        let mut parent = ctx_with_memory_fs();
1269        parent.output_limit = cfg;
1270
1271        // `child_for_pipeline` shares the parent's output_limit, so the worker
1272        // caps against the same budget — this is exactly what the worker path
1273        // now reads (`worker_ctx.output_limit`) before building its
1274        // ScatterResult.
1275        let worker_ctx = parent.child_for_pipeline();
1276        assert!(worker_ctx.output_limit.is_enabled(), "budget must reach the worker");
1277
1278        // Mirror the worker sequence: a large result, then the per-worker spill.
1279        let mut result = ExecResult::success("x".repeat(4096));
1280        assert!(worker_ctx.output_limit.is_enabled());
1281        let _ = spill_if_needed(&mut result, &worker_ctx.output_limit).await;
1282
1283        assert!(result.did_spill, "worker output over the limit must spill, not stay resident");
1284        assert!(
1285            result.text_out().len() < 4096,
1286            "spilled output must be truncated, not the full payload: {} bytes",
1287            result.text_out().len()
1288        );
1289    }
1290
1291    // ── GH #132: a worker completing at the timeout boundary was
1292    // misclassified as timed out — reproduced and fixed ──
1293    //
1294    // Confirmed mechanism: the per-worker timer task does, in order,
1295    // `flag.store(true, SeqCst); cancel.cancel();` — both statements on the
1296    // SAME task, so by the time `cancel()` runs the flag is already true.
1297    // `sleep`'s own `tokio::select! { sleep(d) => success, cancelled() =>
1298    // failure(130) }` is unbiased: if BOTH branches are ready at the same
1299    // poll (the worker's own timer AND the just-cancelled token), tokio picks
1300    // between them pseudo-randomly. If it picks the sleep branch,
1301    // `run_sequential` returns a genuine success — but the flag was already
1302    // set moments earlier by the same timer task. Before the fix, the worker
1303    // trusted the flag unconditionally (`timed_out_check.load()`), tagging a
1304    // truly-successful result `timed_out: true` / code 124. The fix (see
1305    // `let timed_out = timed_out_check.load(...) && !result.ok();` above)
1306    // makes the result's own success authoritative: completion wins ties.
1307    //
1308    // Repro strategy: tie the worker's own `sleep <D>` EXACTLY to `scatter
1309    // --timeout <D>` so both timers mature at the identical virtual instant
1310    // under `start_paused`, then run many iterations. `start_paused` requires
1311    // the `current_thread` flavor (tokio rejects it combined with
1312    // `multi_thread`), so there's no genuine OS-thread-scheduling
1313    // non-determinism here — the variance across iterations comes entirely
1314    // from `tokio::select!`'s own pseudo-random tie-break (fastrand,
1315    // advancing per call) when `sleep`'s internal select has both branches
1316    // ready at once. Verified: this test fails ~45% of iterations against
1317    // the pre-fix code (a plain flag load) and passes 100% against the fix.
1318    #[tokio::test(flavor = "current_thread", start_paused = true)]
1319    async fn worker_completing_at_timeout_boundary_is_not_misclassified() {
1320        use crate::ast::{Arg, Expr};
1321        use crate::dispatch::BackendDispatcher;
1322        use crate::tools::register_builtins;
1323        use crate::vfs::{MemoryFs, VfsRouter};
1324
1325        let mut registry = ToolRegistry::new();
1326        register_builtins(&mut registry);
1327        let tools = Arc::new(registry);
1328        let dispatcher: Arc<dyn CommandDispatcher> =
1329            Arc::new(BackendDispatcher::new(tools.clone()));
1330        let runner = ScatterGatherRunner::new(tools.clone(), dispatcher);
1331
1332        // 20ms on both sides — the exact tie the race depends on.
1333        let commands = vec![Command {
1334            name: "sleep".to_string(),
1335            args: vec![Arg::Positional(Expr::Literal(Value::String("0.02".to_string())))],
1336            redirects: vec![],
1337        }];
1338        let opts = ScatterOptions {
1339            timeout: Some(Duration::from_millis(20)),
1340            ..ScatterOptions::default()
1341        };
1342
1343        let mut false_positives = 0;
1344        let mut genuine_timeouts = 0;
1345        let mut clean_success = 0;
1346        let iterations = 300;
1347        for _ in 0..iterations {
1348            // `BackendDispatcher::dispatch` routes through `ctx.backend.call_tool`,
1349            // not the registry directly — `with_vfs_and_tools` wires a
1350            // `LocalBackend` backed by OUR registry, so `sleep` actually
1351            // resolves instead of falling through to "command not found".
1352            let mut vfs = VfsRouter::new();
1353            vfs.mount("/", MemoryFs::new());
1354            let ctx = ExecContext::with_vfs_and_tools(Arc::new(vfs), tools.clone());
1355            let items = vec![item("x")];
1356            let results = runner.run_parallel(&items, &opts, &commands, &ctx).await;
1357            assert_eq!(results.len(), 1);
1358            let r = &results[0];
1359            match (r.timed_out, r.result.ok()) {
1360                (true, true) => false_positives += 1,
1361                (true, false) => genuine_timeouts += 1,
1362                (false, _) => clean_success += 1,
1363            }
1364        }
1365
1366        eprintln!(
1367            "worker_completing_at_timeout_boundary: {false_positives} false-positive(s), \
1368             {genuine_timeouts} genuine timeout(s), {clean_success} clean success(es) out of \
1369             {iterations} iterations"
1370        );
1371        // Silence isn't success: if the tie stopped forming (e.g. a tokio
1372        // upgrade changes select!'s tie-break behavior), 0 false positives
1373        // would be meaningless rather than reassuring. Assert the race
1374        // actually fires both ways, so this test can't quietly stop testing
1375        // anything.
1376        assert!(
1377            genuine_timeouts > 0 && clean_success > 0,
1378            "the tie never formed (genuine_timeouts={genuine_timeouts}, \
1379             clean_success={clean_success}) — this test needs the race to actually occur to \
1380             mean anything; check the tied durations still create a real contest"
1381        );
1382        assert_eq!(
1383            false_positives, 0,
1384            "GH #132: a worker whose operation genuinely completed (result.ok()) must never \
1385             be reported timed_out — completion should win the tie"
1386        );
1387    }
1388}