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