1use 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#[derive(Debug, Clone)]
32pub struct ScatterOptions {
33 pub var_name: String,
35 pub limit: usize,
37 pub timeout: Option<Duration>,
41}
42
43#[derive(Debug, Clone, Default)]
45pub struct GatherOptions {
46 pub lines: bool,
51 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#[derive(Debug, Clone)]
75pub struct ScatterItem {
76 pub json: serde_json::Value,
78 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 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#[derive(Debug, Clone)]
105pub struct ScatterResult {
106 pub item: ScatterItem,
108 pub result: ExecResult,
110 pub timed_out: bool,
112}
113
114pub struct ScatterGatherRunner {
121 tools: Arc<ToolRegistry>,
122 sequential_dispatcher: Arc<dyn CommandDispatcher>,
125}
126
127impl ScatterGatherRunner {
128 pub fn new(
133 tools: Arc<ToolRegistry>,
134 dispatcher: Arc<dyn CommandDispatcher>,
135 ) -> Self {
136 Self { tools, sequential_dispatcher: dispatcher }
137 }
138
139 #[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 let (text, data) = if pre_scatter.is_empty() {
164 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 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 let results = self
194 .run_parallel(&items, &scatter_opts, parallel, ctx)
195 .await;
196
197 let gathered = gather_results(&results, &gather_opts);
201
202 let gathered = apply_redirects(gathered, gather_redirects, ctx, &*self.sequential_dispatcher).await;
214
215 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 #[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 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 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 let mut worker_ctx = base_ctx.child_for_pipeline();
278 worker_ctx.scope.set(
282 &var_name,
283 crate::interpreter::json_to_value_no_envelope(item.json.clone()),
284 );
285 worker_ctx.cancel = worker_token.clone();
288
289 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 let handle = tokio::spawn(crate::telemetry::bind_current_context(async move {
311 let _permit = permit; let mut worker_ctx = worker_ctx; let runner = PipelineRunner::new(tools);
317 let mut result =
318 runner.run_sequential(&commands, &mut worker_ctx, &*worker_dispatcher).await;
319
320 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 if let Some(h) = timer_handle {
339 h.abort();
340 }
341
342 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 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
385pub fn extract_items(data: Option<&Value>, text: &str) -> Result<Vec<ScatterItem>, String> {
403 match data {
405 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 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 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 Some(Value::Json(json)) => return Ok(vec![ScatterItem::new(json.clone())]),
447 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 None => {}
457 }
458
459 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
473fn 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
480fn 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 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
552fn gather_results(results: &[ScatterResult], opts: &GatherOptions) -> ExecResult {
567 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 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 serde_json::to_string_pretty(&rows).unwrap_or_default()
618 } else {
619 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
626fn 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
641pub 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 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 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
711fn 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
727pub const SCATTER_LIMIT_MAX: usize = 10_000;
731
732pub 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 #[tokio::test]
1260 async fn worker_spills_over_the_shared_output_limit() {
1261 use crate::output_limit::{spill_if_needed, OutputLimitConfig};
1262
1263 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 let worker_ctx = parent.child_for_pipeline();
1275 assert!(worker_ctx.output_limit.is_enabled(), "budget must reach the worker");
1276
1277 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 #[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 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 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 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}