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();
169 let text = match ctx.read_stdin_to_text().await {
170 Ok(s) => s.unwrap_or_default(),
171 Err(e) => return ExecResult::failure(2, format!("scatter: {e}")),
172 };
173 (text, data)
174 } else {
175 let mut result = runner.run_sequential(pre_scatter, ctx, &*self.sequential_dispatcher).await;
176 crate::output_limit::apply_spill_contract(&mut result, &ctx.output_limit).await;
193 if !result.ok() {
194 return result;
195 }
196 (result.text_out().into_owned(), result.data)
197 };
198
199 let items = match extract_items(data.as_ref(), &text) {
201 Ok(items) => items,
202 Err(msg) => return ExecResult::failure(1, msg),
203 };
204 if items.is_empty() {
205 return ExecResult::success("");
206 }
207
208 tracing::Span::current().record("item_count", items.len());
209
210 let results = self
212 .run_parallel(&items, &scatter_opts, parallel, ctx)
213 .await;
214
215 let gathered = gather_results(&results, &gather_opts);
219
220 let gathered = apply_redirects(gathered, gather_redirects, ctx, &*self.sequential_dispatcher).await;
232
233 if post_gather.is_empty() || gathered.code != 0 {
236 gathered
237 } else {
238 ctx.set_stdin_with_data(
239 gathered.text_out().into_owned(),
240 gathered.data.clone(),
241 );
242 runner.run_sequential(post_gather, ctx, &*self.sequential_dispatcher).await
243 }
244 }
245
246 #[tracing::instrument(level = "debug", skip(self, items, opts, commands, base_ctx), fields(worker_count = items.len()))]
255 async fn run_parallel(
256 &self,
257 items: &[ScatterItem],
258 opts: &ScatterOptions,
259 commands: &[Command],
260 base_ctx: &ExecContext,
261 ) -> Vec<ScatterResult> {
262 let semaphore = Arc::new(Semaphore::new(opts.limit));
263 let tools = self.tools.clone();
264 let var_name = opts.var_name.clone();
265
266 let mut handles = Vec::with_capacity(items.len());
268
269 for item in items.iter().cloned() {
270 let permit = semaphore.clone().acquire_owned().await;
271 let tools = tools.clone();
272 let worker_dispatcher = self.sequential_dispatcher.fork_attached().await;
277 let commands = commands.to_vec();
278 let parent_token = base_ctx.cancel.clone();
279 let worker_token = parent_token.child_token();
280
281 let mut worker_ctx = base_ctx.child_for_pipeline();
296 worker_ctx.scope.set(
300 &var_name,
301 crate::interpreter::json_to_value_no_envelope(item.json.clone()),
302 );
303 worker_ctx.cancel = worker_token.clone();
306
307 let timed_out_flag = Arc::new(AtomicBool::new(false));
313 let timer_handle: Option<tokio::task::JoinHandle<()>> = opts.timeout.map(|d| {
314 let cancel = worker_token.clone();
315 let flag = timed_out_flag.clone();
316 tokio::spawn(async move {
317 tokio::time::sleep(d).await;
318 flag.store(true, Ordering::SeqCst);
319 cancel.cancel();
320 })
321 });
322 let timed_out_check = timed_out_flag.clone();
323
324 let worker_span = tracing::debug_span!("scatter_worker", item = %item.label);
325 let handle = tokio::spawn(crate::telemetry::bind_current_context(async move {
329 let _permit = permit; let mut worker_ctx = worker_ctx; let runner = PipelineRunner::new(tools);
335 let mut result =
336 runner.run_sequential(&commands, &mut worker_ctx, &*worker_dispatcher).await;
337
338 let genuinely_completed = result.ok();
345
346 crate::output_limit::apply_spill_contract(&mut result, &worker_ctx.output_limit).await;
359
360 if let Some(h) = timer_handle {
363 h.abort();
364 }
365
366 let timed_out = timed_out_check.load(Ordering::SeqCst) && !genuinely_completed;
381
382 ScatterResult { item, result, timed_out }
383 }.instrument(worker_span)));
384
385 handles.push(handle);
386 }
387
388 let mut results = Vec::with_capacity(handles.len());
390 for handle in handles {
391 match handle.await {
392 Ok(result) => results.push(result),
393 Err(e) => {
394 results.push(ScatterResult {
395 item: ScatterItem::new(serde_json::Value::String(
396 "<worker panicked>".to_string(),
397 )),
398 result: ExecResult::failure(1, format!("Task panicked: {}", e)),
399 timed_out: false,
400 });
401 }
402 }
403 }
404
405 results
406 }
407}
408
409pub fn extract_items(data: Option<&Value>, text: &str) -> Result<Vec<ScatterItem>, String> {
427 match data {
429 Some(Value::Json(serde_json::Value::Array(arr))) => {
431 let mut items = Vec::with_capacity(arr.len());
432 for (i, elem) in arr.iter().enumerate() {
433 if elem.is_null() {
434 return Err(format!(
435 "scatter: item {i} is null — filter nulls out first, \
436 e.g. jq 'map(select(. != null))'"
437 ));
438 }
439 items.push(ScatterItem::new(elem.clone()));
440 }
441 return Ok(items);
442 }
443 Some(Value::String(s)) => {
445 return Ok(vec![ScatterItem::new(serde_json::Value::String(s.clone()))])
446 }
447 Some(Value::Int(i)) => return Ok(vec![ScatterItem::new(serde_json::json!(i))]),
448 Some(Value::Float(f)) => return Ok(vec![ScatterItem::new(serde_json::json!(f))]),
449 Some(Value::Bool(b)) => return Ok(vec![ScatterItem::new(serde_json::json!(b))]),
450 Some(Value::Null) => {
451 return Err("scatter: input is null — nothing to fan out".to_string())
452 }
453 Some(Value::Json(serde_json::Value::Object(map))) => {
456 let hint = map
457 .iter()
458 .find(|(_, v)| v.is_array())
459 .map(|(k, _)| format!(" (did you mean jq '.{k}'?)"))
460 .unwrap_or_default();
461 return Err(format!(
462 "scatter: input is a single object, not an array — select the array to \
463 fan out over{hint}"
464 ));
465 }
466 Some(Value::Json(serde_json::Value::Null)) => {
467 return Err("scatter: input is null — nothing to fan out".to_string())
468 }
469 Some(Value::Json(json)) => return Ok(vec![ScatterItem::new(json.clone())]),
471 Some(Value::Bytes(b)) => {
474 return Err(format!(
475 "scatter: input is binary ({} bytes) — decode it to text or JSON first",
476 b.len()
477 ))
478 }
479 None => {}
481 }
482
483 let trimmed = text.trim_end_matches(['\n', '\r']);
486 if trimmed.is_empty() {
487 return Ok(vec![]);
488 }
489 Ok(trimmed
490 .split('\n')
491 .map(|line| line.trim_end_matches('\r'))
492 .filter(|line| !line.is_empty())
493 .map(ScatterItem::from_text_line)
494 .collect())
495}
496
497fn strip_one_trailing_newline(s: &str) -> &str {
500 let s = s.strip_suffix('\n').unwrap_or(s);
501 s.strip_suffix('\r').unwrap_or(s)
502}
503
504fn result_row(i: usize, r: &ScatterResult) -> serde_json::Value {
527 let mut ok = r.result.ok() && !r.timed_out;
528 let mut code = if r.timed_out { 124 } else { r.result.code };
529
530 let (out_text, err_text) = match r.result.try_text_out() {
531 Ok(text) => (
532 strip_one_trailing_newline(&text).to_string(),
533 strip_one_trailing_newline(&r.result.err).to_string(),
534 ),
535 Err(e) => {
536 ok = false;
537 if code == 0 {
538 code = 1;
539 }
540 (
541 String::new(),
542 format!(
543 "binary worker output not representable as text ({} bytes) — \
544 encode it in the worker (base64/xxd)",
545 e.len
546 ),
547 )
548 }
549 };
550
551 let mut row = serde_json::Map::new();
552 row.insert("i".into(), serde_json::json!(i));
553 row.insert("item".into(), r.item.json.clone());
554 row.insert("ok".into(), serde_json::json!(ok));
555 row.insert("code".into(), serde_json::json!(code));
556 row.insert("out".into(), serde_json::json!(out_text));
557 row.insert("err".into(), serde_json::json!(err_text));
558 if let Some(data) = &r.result.data {
559 row.insert("data".into(), kaish_types::value_to_json(data));
560 }
561 if r.timed_out {
562 row.insert("timed_out".into(), serde_json::json!(true));
563 }
564 serde_json::Value::Object(row)
565}
566
567fn gather_results(results: &[ScatterResult], opts: &GatherOptions) -> ExecResult {
582 let is_unrepresentable = |r: &ScatterResult| r.result.try_text_out().is_err();
588
589 let failed: Vec<&ScatterResult> = results
590 .iter()
591 .filter(|r| !r.result.ok() || r.timed_out || is_unrepresentable(r))
592 .collect();
593 let code = if failed.is_empty() { 0 } else { 123 };
594 let err = if failed.is_empty() {
595 String::new()
596 } else {
597 let names = failed
598 .iter()
599 .map(|r| {
600 if is_unrepresentable(r) {
601 format!("{} (binary output not representable as text)", r.item.label)
602 } else {
603 r.item.label.clone()
604 }
605 })
606 .collect::<Vec<_>>()
607 .join(", ");
608 format!("gather: {} of {} worker(s) failed: {names}", failed.len(), results.len())
609 };
610
611 if opts.lines {
612 if !failed.is_empty() {
618 return ExecResult::failure(code, format!("{err} (drop --lines to get per-worker rows)"));
619 }
620 let text = results
621 .iter()
622 .map(|r| strip_one_trailing_newline(&r.result.text_out()).to_string())
623 .collect::<Vec<_>>()
624 .join("\n");
625 return ExecResult::success(text);
626 }
627
628 let rows: Vec<serde_json::Value> =
629 results.iter().enumerate().map(|(i, r)| result_row(i, r)).collect();
630 let text = if opts.json {
631 serde_json::to_string_pretty(&rows).unwrap_or_default()
633 } else {
634 rows.iter().map(|row| row.to_string()).collect::<Vec<_>>().join("\n")
636 };
637 let array = serde_json::Value::Array(rows);
638 ExecResult::from_parts(code, text, err, Some(Value::Json(array)))
639}
640
641fn describe_value(v: &Value) -> String {
645 match v {
646 Value::Null => "null".to_string(),
647 Value::Bool(b) => b.to_string(),
648 Value::Int(n) => n.to_string(),
649 Value::Float(f) => f.to_string(),
650 Value::String(s) => format!("{s:?}"),
651 Value::Json(j) => j.to_string(),
652 Value::Bytes(b) => format!("<{} bytes>", b.len()),
653 }
654}
655
656pub fn parse_scatter_options(args: &crate::tools::ToolArgs) -> Result<ScatterOptions, String> {
665 let mut opts = ScatterOptions::default();
666
667 match args.named.get("as") {
668 None => {}
669 Some(Value::String(name)) => {
670 crate::name::validate(name)
673 .map_err(|bad| format!("scatter --as: `{name}': {bad}"))?;
674 opts.var_name = name.clone();
675 }
676 Some(other) => {
677 return Err(format!(
678 "scatter --as: expected a variable name, got {}",
679 describe_value(other)
680 ))
681 }
682 }
683
684 match args.named.get("limit") {
685 None => {}
686 Some(Value::Int(n)) => opts.limit = clamp_scatter_limit(*n),
687 Some(Value::String(s)) => match s.trim().parse::<i64>() {
690 Ok(n) => opts.limit = clamp_scatter_limit(n),
691 Err(_) => {
692 return Err(format!(
693 "scatter --limit: expected a positive integer, got {}",
694 describe_value(&Value::String(s.clone()))
695 ))
696 }
697 },
698 Some(other) => {
699 return Err(format!(
700 "scatter --limit: expected a positive integer, got {}",
701 describe_value(other)
702 ))
703 }
704 }
705
706 match args.named.get("timeout") {
710 None => {}
711 Some(Value::String(s)) => match parse_duration(s) {
712 Some(d) => opts.timeout = Some(d),
713 None => {
714 return Err(format!(
715 "scatter --timeout: invalid duration {} (try: 30, 5s, 500ms, 2m, 1h)",
716 describe_value(&Value::String(s.clone()))
717 ))
718 }
719 },
720 Some(Value::Int(n)) if *n >= 0 => opts.timeout = Some(Duration::from_secs(*n as u64)),
721 Some(other) => {
722 return Err(format!(
723 "scatter --timeout: expected a non-negative duration, got {}",
724 describe_value(other)
725 ))
726 }
727 }
728
729 Ok(opts)
730}
731
732fn clamp_scatter_limit(requested: i64) -> usize {
736 let clamped = requested.clamp(1, SCATTER_LIMIT_MAX as i64);
737 if requested > SCATTER_LIMIT_MAX as i64 {
738 tracing::warn!(
739 target: "kaish::scatter",
740 requested = requested,
741 ceiling = SCATTER_LIMIT_MAX,
742 "scatter limit clamped to ceiling"
743 );
744 }
745 clamped as usize
746}
747
748pub const SCATTER_LIMIT_MAX: usize = 10_000;
752
753pub fn parse_gather_options(args: &crate::tools::ToolArgs) -> Result<GatherOptions, String> {
761 let mut opts = GatherOptions::default();
762
763 if args.has_flag("lines") {
764 opts.lines = true;
765 }
766
767 if args.has_flag("json") {
768 opts.json = true;
769 }
770
771 Ok(opts)
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777
778 fn labels(items: &[ScatterItem]) -> Vec<String> {
779 items.iter().map(|i| i.label.clone()).collect()
780 }
781
782 fn item(s: &str) -> ScatterItem {
783 ScatterItem::new(serde_json::Value::String(s.to_string()))
784 }
785
786 #[test]
787 fn test_extract_items_structured_json_array() {
788 let data = Value::Json(serde_json::json!(["a", "b", "c"]));
789 let items = extract_items(Some(&data), "").unwrap();
790 assert_eq!(labels(&items), vec!["a", "b", "c"]);
791 }
792
793 #[test]
794 fn test_extract_items_structured_mixed_types_stay_typed() {
795 let data = Value::Json(serde_json::json!([1, "1", true, {"id": 7}]));
798 let items = extract_items(Some(&data), "").unwrap();
799 assert_eq!(items[0].json, serde_json::json!(1));
800 assert_eq!(items[1].json, serde_json::json!("1"));
801 assert_ne!(items[0].json, items[1].json, "1 and \"1\" must not conflate");
802 assert_eq!(items[2].json, serde_json::json!(true));
803 assert_eq!(items[3].json, serde_json::json!({"id": 7}));
804 }
805
806 #[test]
807 fn test_extract_items_null_element_is_loud() {
808 let data = Value::Json(serde_json::json!(["a", null, "c"]));
809 let err = extract_items(Some(&data), "").unwrap_err();
810 assert!(err.contains("null"), "should name the problem: {err}");
811 assert!(err.contains("item 1"), "should name the position: {err}");
812 }
813
814 #[test]
815 fn test_extract_items_single_object_is_loud_with_hint() {
816 let data = Value::Json(serde_json::json!({"jobs": [1, 2]}));
817 let err = extract_items(Some(&data), "").unwrap_err();
818 assert!(err.contains("single object"), "{err}");
819 assert!(err.contains("jq '.jobs'"), "should hint the array key: {err}");
820 }
821
822 #[test]
823 fn test_extract_items_binary_is_loud() {
824 let data = Value::Bytes(vec![0, 1, 2]);
825 let err = extract_items(Some(&data), "").unwrap_err();
826 assert!(err.contains("binary"), "{err}");
827 }
828
829 #[test]
830 fn test_extract_items_structured_string() {
831 let data = Value::String("single".into());
832 let items = extract_items(Some(&data), "").unwrap();
833 assert_eq!(labels(&items), vec!["single"]);
834 }
835
836 #[test]
837 fn test_extract_items_single_line_text() {
838 let items = extract_items(None, "hello").unwrap();
839 assert_eq!(labels(&items), vec!["hello"]);
840 }
841
842 #[test]
843 fn test_extract_items_empty() {
844 let items = extract_items(None, "").unwrap();
845 assert!(items.is_empty());
846 }
847
848 #[test]
849 fn test_extract_items_multiline_fans_out_per_line() {
850 let items = extract_items(None, "one\ntwo\nthree").unwrap();
851 assert_eq!(labels(&items), vec!["one", "two", "three"]);
852 }
853
854 #[test]
855 fn test_extract_items_trailing_newline_no_phantom_item() {
856 let items = extract_items(None, "one\ntwo\n").unwrap();
857 assert_eq!(labels(&items), vec!["one", "two"]);
858 }
859
860 #[test]
861 fn test_extract_items_crlf_per_line() {
862 let items = extract_items(None, "one\r\ntwo\r\n").unwrap();
863 assert_eq!(labels(&items), vec!["one", "two"]);
864 }
865
866 #[test]
867 fn test_extract_items_blank_lines_skipped() {
868 let items = extract_items(None, "a\n\nb").unwrap();
871 assert_eq!(labels(&items), vec!["a", "b"]);
872 }
873
874 #[test]
875 fn test_extract_items_whitespace_within_line_not_split() {
876 let items = extract_items(None, "a b\nc d").unwrap();
877 assert_eq!(labels(&items), vec!["a b", "c d"]);
878 }
879
880 #[test]
881 fn test_extract_items_only_newlines_is_empty() {
882 let items = extract_items(None, "\n\n").unwrap();
883 assert!(items.is_empty());
884 }
885
886 #[test]
887 fn test_extract_items_structured_overrides_text() {
888 let data = Value::Json(serde_json::json!(["x", "y"]));
889 let items = extract_items(Some(&data), "ignored\ntext").unwrap();
890 assert_eq!(labels(&items), vec!["x", "y"]);
891 }
892
893 #[test]
894 fn test_item_label_truncates_on_char_boundary() {
895 let long: String = "é".repeat(100);
897 let it = ScatterItem::new(serde_json::Value::String(long));
898 assert!(it.label.ends_with("..."));
899 assert_eq!(it.label.chars().count(), 67);
900 }
901
902 #[test]
903 fn test_gather_results_jsonl_rows_carry_everything() {
904 let results = vec![
905 ScatterResult {
906 item: item("a"),
907 result: ExecResult::success("result_a\n"),
908 timed_out: false,
909 },
910 ScatterResult {
911 item: item("b"),
912 result: ExecResult::failure(7, "boom\n"),
913 timed_out: false,
914 },
915 ];
916 let out = gather_results(&results, &GatherOptions::default());
917 assert_eq!(out.code, 123, "any failure → 123 (A′)");
918 let rows: Vec<serde_json::Value> = out
919 .text_out()
920 .lines()
921 .map(|l| serde_json::from_str(l).unwrap())
922 .collect();
923 assert_eq!(rows.len(), 2, "every worker gets a row, failures included");
924 assert_eq!(rows[0]["i"], 0);
925 assert_eq!(rows[0]["item"], "a");
926 assert_eq!(rows[0]["ok"], true);
927 assert_eq!(rows[0]["out"], "result_a", "trailing newline stripped");
928 assert_eq!(rows[0]["err"], "", "err always present");
929 assert!(rows[0].get("timed_out").is_none(), "omit-false");
930 assert!(rows[0].get("data").is_none(), "omit-empty");
931 assert_eq!(rows[1]["i"], 1);
932 assert_eq!(rows[1]["ok"], false);
933 assert_eq!(rows[1]["code"], 7);
934 assert_eq!(rows[1]["err"], "boom");
935 assert!(matches!(out.data, Some(Value::Json(serde_json::Value::Array(_)))));
937 }
938
939 #[test]
940 fn test_gather_results_all_ok_is_zero() {
941 let results = vec![ScatterResult {
942 item: item("a"),
943 result: ExecResult::success("x"),
944 timed_out: false,
945 }];
946 let out = gather_results(&results, &GatherOptions::default());
947 assert_eq!(out.code, 0);
948 assert!(out.err.is_empty());
949 }
950
951 #[test]
952 fn test_gather_results_timeout_row_is_124() {
953 let results = vec![ScatterResult {
954 item: item("slow"),
955 result: ExecResult::failure(1, "cancelled"),
956 timed_out: true,
957 }];
958 let out = gather_results(&results, &GatherOptions::default());
959 assert_eq!(out.code, 123);
960 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
961 assert_eq!(row["code"], 124, "timeout reports the timeout(1) code");
962 assert_eq!(row["ok"], false);
963 assert_eq!(row["timed_out"], true);
964 }
965
966 #[test]
967 fn test_gather_results_typed_record_item_in_row() {
968 let results = vec![ScatterResult {
969 item: ScatterItem::new(serde_json::json!({"id": 3, "host": "web1"})),
970 result: ExecResult::success("ok"),
971 timed_out: false,
972 }];
973 let out = gather_results(&results, &GatherOptions::default());
974 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
975 assert_eq!(row["item"]["id"], 3, "row item is the TYPED value, not a string");
976 }
977
978 #[test]
979 fn test_gather_results_worker_data_rides_the_row() {
980 let mut r = ExecResult::success("text");
981 r.data = Some(Value::Json(serde_json::json!({"k": 1})));
982 let results = vec![ScatterResult { item: item("a"), result: r, timed_out: false }];
983 let out = gather_results(&results, &GatherOptions::default());
984 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
985 assert_eq!(row["data"]["k"], 1, "worker .data lands typed in the row");
986 assert_eq!(row["out"], "text", "out stays alongside data");
987 }
988
989 #[test]
999 fn test_gather_results_spilled_worker_counts_as_failed() {
1000 let mut spilled = ExecResult::success("truncated preview");
1001 spilled.did_spill = true;
1002 spilled.original_code = Some(0);
1003 spilled.code = 3; let results = vec![
1006 ScatterResult { item: item("a"), result: spilled, timed_out: false },
1007 ScatterResult { item: item("b"), result: ExecResult::success("clean"), timed_out: false },
1008 ];
1009 let out = gather_results(&results, &GatherOptions::default());
1010 assert_eq!(
1011 out.code, 123,
1012 "a spilled worker (code remapped to 3) must count as failed, not silently succeed"
1013 );
1014 let rows: Vec<serde_json::Value> = out
1015 .text_out()
1016 .lines()
1017 .map(|l| serde_json::from_str(l).unwrap())
1018 .collect();
1019 assert_eq!(rows[0]["ok"], false, "spilled row must read ok:false: {:?}", rows[0]);
1020 assert_eq!(rows[0]["code"], 3, "spilled row must carry the remapped exit 3: {:?}", rows[0]);
1021 assert_eq!(rows[1]["ok"], true, "the clean worker's own row is unaffected: {:?}", rows[1]);
1022 }
1023
1024 #[test]
1025 fn test_gather_results_lines_happy_path() {
1026 let results = vec![
1027 ScatterResult { item: item("a"), result: ExecResult::success("result_a\n"), timed_out: false },
1028 ScatterResult { item: item("b"), result: ExecResult::success("result_b"), timed_out: false },
1029 ];
1030 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1031 assert_eq!(out.code, 0);
1032 assert_eq!(&*out.text_out(), "result_a\nresult_b");
1033 }
1034
1035 #[test]
1036 fn test_gather_results_lines_hard_errors_on_any_failure() {
1037 let results = vec![
1039 ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1040 ScatterResult { item: item("b"), result: ExecResult::failure(1, "boom"), timed_out: false },
1041 ];
1042 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1043 assert_eq!(out.code, 123);
1044 assert!(out.text_out().is_empty(), "no partial text on --lines failure");
1045 assert!(out.err.contains("b"), "names the failed item: {}", out.err);
1046 }
1047
1048 #[test]
1049 fn test_parse_scatter_options() {
1050 use crate::tools::ToolArgs;
1051
1052 let mut args = ToolArgs::new();
1053 args.named.insert("as".to_string(), Value::String("URL".to_string()));
1054 args.named.insert("limit".to_string(), Value::Int(4));
1055
1056 let opts = parse_scatter_options(&args).unwrap();
1057 assert_eq!(opts.var_name, "URL");
1058 assert_eq!(opts.limit, 4);
1059 }
1060
1061 #[test]
1062 fn test_parse_gather_options() {
1063 use crate::tools::ToolArgs;
1064
1065 let mut args = ToolArgs::new();
1066 args.flags.insert("lines".to_string());
1067
1068 let opts = parse_gather_options(&args).unwrap();
1069 assert!(opts.lines);
1070 assert!(!parse_gather_options(&ToolArgs::new()).unwrap().lines, "default is JSONL");
1071 }
1072
1073 #[test]
1074 fn scatter_limit_clamps_to_ceiling() {
1075 use crate::tools::ToolArgs;
1076
1077 let mut args = ToolArgs::new();
1078 args.named.insert("limit".to_string(), Value::Int(999_999));
1079 let opts = parse_scatter_options(&args).unwrap();
1080 assert_eq!(opts.limit, SCATTER_LIMIT_MAX);
1081 }
1082
1083 #[test]
1084 fn scatter_limit_raises_zero_to_one() {
1085 use crate::tools::ToolArgs;
1086
1087 let mut args = ToolArgs::new();
1088 args.named.insert("limit".to_string(), Value::Int(0));
1089 let opts = parse_scatter_options(&args).unwrap();
1090 assert_eq!(opts.limit, 1);
1091 }
1092
1093 #[test]
1094 fn scatter_limit_raises_negative_to_one() {
1095 use crate::tools::ToolArgs;
1096
1097 let mut args = ToolArgs::new();
1098 args.named.insert("limit".to_string(), Value::Int(-42));
1099 let opts = parse_scatter_options(&args).unwrap();
1100 assert_eq!(opts.limit, 1);
1101 }
1102
1103 #[test]
1104 fn scatter_limit_preserves_valid_values() {
1105 use crate::tools::ToolArgs;
1106
1107 let mut args = ToolArgs::new();
1108 args.named.insert("limit".to_string(), Value::Int(500));
1109 let opts = parse_scatter_options(&args).unwrap();
1110 assert_eq!(opts.limit, 500);
1111 }
1112
1113 #[test]
1116 fn scatter_limit_wrong_type_is_loud_error() {
1117 use crate::tools::ToolArgs;
1118
1119 let mut args = ToolArgs::new();
1120 args.named.insert("limit".to_string(), Value::String("five".to_string()));
1121 let err = parse_scatter_options(&args).unwrap_err();
1122 assert!(err.contains("--limit"), "{err}");
1123 assert!(err.contains("five"), "{err}");
1124 }
1125
1126 #[test]
1127 fn scatter_limit_bool_is_loud_error() {
1128 use crate::tools::ToolArgs;
1129
1130 let mut args = ToolArgs::new();
1131 args.named.insert("limit".to_string(), Value::Bool(true));
1132 let err = parse_scatter_options(&args).unwrap_err();
1133 assert!(err.contains("--limit"), "{err}");
1134 }
1135
1136 #[test]
1137 fn scatter_limit_numeric_string_coerces() {
1138 use crate::tools::ToolArgs;
1140
1141 let mut args = ToolArgs::new();
1142 args.named.insert("limit".to_string(), Value::String("5".to_string()));
1143 let opts = parse_scatter_options(&args).unwrap();
1144 assert_eq!(opts.limit, 5);
1145 }
1146
1147 #[test]
1148 fn scatter_as_wrong_type_is_loud_error() {
1149 use crate::tools::ToolArgs;
1150
1151 let mut args = ToolArgs::new();
1152 args.named.insert("as".to_string(), Value::Int(42));
1153 let err = parse_scatter_options(&args).unwrap_err();
1154 assert!(err.contains("--as"), "{err}");
1155 assert!(err.contains("42"), "{err}");
1156 }
1157
1158 #[test]
1159 fn scatter_timeout_negative_int_is_loud_error() {
1160 use crate::tools::ToolArgs;
1161
1162 let mut args = ToolArgs::new();
1163 args.named.insert("timeout".to_string(), Value::Int(-5));
1164 let err = parse_scatter_options(&args).unwrap_err();
1165 assert!(err.contains("--timeout"), "{err}");
1166 }
1167
1168 #[test]
1169 fn scatter_timeout_unparseable_string_is_loud_error() {
1170 use crate::tools::ToolArgs;
1171
1172 let mut args = ToolArgs::new();
1173 args.named.insert("timeout".to_string(), Value::String("banana".to_string()));
1174 let err = parse_scatter_options(&args).unwrap_err();
1175 assert!(err.contains("--timeout"), "{err}");
1176 assert!(err.contains("banana"), "{err}");
1177 }
1178
1179 #[test]
1180 fn scatter_timeout_valid_duration_string_parses() {
1181 use crate::tools::ToolArgs;
1182
1183 let mut args = ToolArgs::new();
1184 args.named.insert("timeout".to_string(), Value::String("5s".to_string()));
1185 let opts = parse_scatter_options(&args).unwrap();
1186 assert_eq!(opts.timeout, Some(Duration::from_secs(5)));
1187 }
1188
1189 #[test]
1190 fn scatter_timeout_nonnegative_int_is_seconds() {
1191 use crate::tools::ToolArgs;
1192
1193 let mut args = ToolArgs::new();
1194 args.named.insert("timeout".to_string(), Value::Int(30));
1195 let opts = parse_scatter_options(&args).unwrap();
1196 assert_eq!(opts.timeout, Some(Duration::from_secs(30)));
1197 }
1198
1199 fn binary_result(invalid_utf8: Vec<u8>) -> ExecResult {
1202 ExecResult::success_bytes(invalid_utf8)
1203 }
1204
1205 #[test]
1206 fn gather_row_goes_loud_not_lossy_on_binary_out() {
1207 let results = vec![ScatterResult {
1210 item: item("bin"),
1211 result: binary_result(vec![0xFF, 0xFE, 0x00, 0x01]),
1212 timed_out: false,
1213 }];
1214 let out = gather_results(&results, &GatherOptions::default());
1215 assert_eq!(out.code, 123, "a binary row flips the overall exit code too");
1216 let row: serde_json::Value =
1217 serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
1218 assert_eq!(row["ok"], false, "binary output must not be silently ok:true");
1219 assert_ne!(row["code"], 0, "must carry a nonzero code");
1220 assert!(row["out"].as_str().unwrap().is_empty(), "no lossy text in out");
1221 let err_text = row["err"].as_str().unwrap();
1222 assert!(err_text.contains("binary"), "{err_text}");
1223 assert!(!err_text.contains('\u{FFFD}'), "must not carry U+FFFD: {err_text}");
1224 }
1225
1226 #[test]
1227 fn gather_lines_hard_errors_on_binary_out() {
1228 let results = vec![
1231 ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1232 ScatterResult {
1233 item: item("bin"),
1234 result: binary_result(vec![0xFF, 0xFE]),
1235 timed_out: false,
1236 },
1237 ];
1238 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1239 assert_eq!(out.code, 123);
1240 assert!(out.text_out().is_empty(), "no partial/lossy text on binary --lines failure");
1241 assert!(!out.err.contains('\u{FFFD}'), "must not carry U+FFFD: {}", out.err);
1242 assert!(out.err.contains("binary") || out.err.contains("bin"), "{}", out.err);
1243 }
1244
1245 fn ctx_with_memory_fs() -> ExecContext {
1248 use crate::vfs::{MemoryFs, VfsRouter};
1249 use std::sync::Arc;
1250 let mut vfs = VfsRouter::new();
1251 vfs.mount("/", MemoryFs::new());
1252 ExecContext::new(Arc::new(vfs))
1253 }
1254
1255 #[test]
1256 fn worker_ctx_inherits_parent_watchdog() {
1257 use crate::watchdog::Watchdog;
1258 use std::sync::Arc;
1259
1260 let mut parent = ctx_with_memory_fs();
1261 parent.watchdog = Some(Arc::new(Watchdog::new(Duration::from_secs(30))));
1262
1263 let worker_ctx = parent.child_for_pipeline();
1267 assert!(
1268 worker_ctx.watchdog.is_some(),
1269 "worker must carry the parent's script watchdog, not None"
1270 );
1271
1272 let from_scratch =
1275 ExecContext::with_backend_and_scope(parent.backend.clone(), parent.scope.clone());
1276 assert!(
1277 from_scratch.watchdog.is_none(),
1278 "the abandoned from-scratch path is exactly why the worker lost its watchdog"
1279 );
1280 }
1281
1282 #[tokio::test]
1285 async fn worker_spills_over_the_shared_output_limit() {
1286 use crate::output_limit::{apply_spill_contract, OutputLimitConfig};
1287
1288 let mut cfg = OutputLimitConfig::agent().in_memory();
1290 cfg.set_limit(Some(64));
1291
1292 let mut parent = ctx_with_memory_fs();
1293 parent.output_limit = cfg;
1294
1295 let worker_ctx = parent.child_for_pipeline();
1300 assert!(worker_ctx.output_limit.is_enabled(), "budget must reach the worker");
1301
1302 let mut result = ExecResult::success("x".repeat(4096));
1307 assert!(worker_ctx.output_limit.is_enabled());
1308 apply_spill_contract(&mut result, &worker_ctx.output_limit).await;
1309
1310 assert!(result.did_spill, "worker output over the limit must spill, not stay resident");
1311 assert_eq!(
1312 result.code, 3,
1313 "a spilled worker must exit 3 so gather's ok()-based aggregation counts it as failed"
1314 );
1315 assert_eq!(result.original_code, Some(0), "the worker's own clean exit is preserved");
1316 assert!(
1317 result.text_out().len() < 4096,
1318 "spilled output must be truncated, not the full payload: {} bytes",
1319 result.text_out().len()
1320 );
1321 }
1322
1323 #[tokio::test(flavor = "current_thread", start_paused = true)]
1351 async fn worker_completing_at_timeout_boundary_is_not_misclassified() {
1352 use crate::ast::{Arg, Expr};
1353 use crate::dispatch::BackendDispatcher;
1354 use crate::tools::register_builtins;
1355 use crate::vfs::{MemoryFs, VfsRouter};
1356
1357 let mut registry = ToolRegistry::new();
1358 register_builtins(&mut registry);
1359 let tools = Arc::new(registry);
1360 let dispatcher: Arc<dyn CommandDispatcher> =
1361 Arc::new(BackendDispatcher::new(tools.clone()));
1362 let runner = ScatterGatherRunner::new(tools.clone(), dispatcher);
1363
1364 let commands = vec![Command {
1366 name: "sleep".to_string(),
1367 args: vec![Arg::Positional(Expr::Literal(Value::String("0.02".to_string())))],
1368 redirects: vec![],
1369 }];
1370 let opts = ScatterOptions {
1371 timeout: Some(Duration::from_millis(20)),
1372 ..ScatterOptions::default()
1373 };
1374
1375 let mut false_positives = 0;
1376 let mut genuine_timeouts = 0;
1377 let mut clean_success = 0;
1378 let iterations = 300;
1379 for _ in 0..iterations {
1380 let mut vfs = VfsRouter::new();
1385 vfs.mount("/", MemoryFs::new());
1386 let ctx = ExecContext::with_vfs_and_tools(Arc::new(vfs), tools.clone());
1387 let items = vec![item("x")];
1388 let results = runner.run_parallel(&items, &opts, &commands, &ctx).await;
1389 assert_eq!(results.len(), 1);
1390 let r = &results[0];
1391 match (r.timed_out, r.result.ok()) {
1392 (true, true) => false_positives += 1,
1393 (true, false) => genuine_timeouts += 1,
1394 (false, _) => clean_success += 1,
1395 }
1396 }
1397
1398 eprintln!(
1399 "worker_completing_at_timeout_boundary: {false_positives} false-positive(s), \
1400 {genuine_timeouts} genuine timeout(s), {clean_success} clean success(es) out of \
1401 {iterations} iterations"
1402 );
1403 assert!(
1409 genuine_timeouts > 0 && clean_success > 0,
1410 "the tie never formed (genuine_timeouts={genuine_timeouts}, \
1411 clean_success={clean_success}) — this test needs the race to actually occur to \
1412 mean anything; check the tied durations still create a real contest"
1413 );
1414 assert_eq!(
1415 false_positives, 0,
1416 "GH #132: a worker whose operation genuinely completed (result.ok()) must never \
1417 be reported timed_out — completion should win the tie"
1418 );
1419 }
1420}