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 — refusing to bind a worker to null \
436 (filter it out first, 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)) => opts.var_name = name.clone(),
670 Some(other) => {
671 return Err(format!(
672 "scatter --as: expected a variable name, got {}",
673 describe_value(other)
674 ))
675 }
676 }
677
678 match args.named.get("limit") {
679 None => {}
680 Some(Value::Int(n)) => opts.limit = clamp_scatter_limit(*n),
681 Some(Value::String(s)) => match s.trim().parse::<i64>() {
684 Ok(n) => opts.limit = clamp_scatter_limit(n),
685 Err(_) => {
686 return Err(format!(
687 "scatter --limit: expected a positive integer, got {}",
688 describe_value(&Value::String(s.clone()))
689 ))
690 }
691 },
692 Some(other) => {
693 return Err(format!(
694 "scatter --limit: expected a positive integer, got {}",
695 describe_value(other)
696 ))
697 }
698 }
699
700 match args.named.get("timeout") {
704 None => {}
705 Some(Value::String(s)) => match parse_duration(s) {
706 Some(d) => opts.timeout = Some(d),
707 None => {
708 return Err(format!(
709 "scatter --timeout: invalid duration {} (try: 30, 5s, 500ms, 2m, 1h)",
710 describe_value(&Value::String(s.clone()))
711 ))
712 }
713 },
714 Some(Value::Int(n)) if *n >= 0 => opts.timeout = Some(Duration::from_secs(*n as u64)),
715 Some(other) => {
716 return Err(format!(
717 "scatter --timeout: expected a non-negative duration, got {}",
718 describe_value(other)
719 ))
720 }
721 }
722
723 Ok(opts)
724}
725
726fn clamp_scatter_limit(requested: i64) -> usize {
730 let clamped = requested.clamp(1, SCATTER_LIMIT_MAX as i64);
731 if requested > SCATTER_LIMIT_MAX as i64 {
732 tracing::warn!(
733 target: "kaish::scatter",
734 requested = requested,
735 ceiling = SCATTER_LIMIT_MAX,
736 "scatter limit clamped to ceiling"
737 );
738 }
739 clamped as usize
740}
741
742pub const SCATTER_LIMIT_MAX: usize = 10_000;
746
747pub fn parse_gather_options(args: &crate::tools::ToolArgs) -> Result<GatherOptions, String> {
755 let mut opts = GatherOptions::default();
756
757 if args.has_flag("lines") {
758 opts.lines = true;
759 }
760
761 if args.has_flag("json") {
762 opts.json = true;
763 }
764
765 Ok(opts)
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771
772 fn labels(items: &[ScatterItem]) -> Vec<String> {
773 items.iter().map(|i| i.label.clone()).collect()
774 }
775
776 fn item(s: &str) -> ScatterItem {
777 ScatterItem::new(serde_json::Value::String(s.to_string()))
778 }
779
780 #[test]
781 fn test_extract_items_structured_json_array() {
782 let data = Value::Json(serde_json::json!(["a", "b", "c"]));
783 let items = extract_items(Some(&data), "").unwrap();
784 assert_eq!(labels(&items), vec!["a", "b", "c"]);
785 }
786
787 #[test]
788 fn test_extract_items_structured_mixed_types_stay_typed() {
789 let data = Value::Json(serde_json::json!([1, "1", true, {"id": 7}]));
792 let items = extract_items(Some(&data), "").unwrap();
793 assert_eq!(items[0].json, serde_json::json!(1));
794 assert_eq!(items[1].json, serde_json::json!("1"));
795 assert_ne!(items[0].json, items[1].json, "1 and \"1\" must not conflate");
796 assert_eq!(items[2].json, serde_json::json!(true));
797 assert_eq!(items[3].json, serde_json::json!({"id": 7}));
798 }
799
800 #[test]
801 fn test_extract_items_null_element_is_loud() {
802 let data = Value::Json(serde_json::json!(["a", null, "c"]));
803 let err = extract_items(Some(&data), "").unwrap_err();
804 assert!(err.contains("null"), "should name the problem: {err}");
805 assert!(err.contains("item 1"), "should name the position: {err}");
806 }
807
808 #[test]
809 fn test_extract_items_single_object_is_loud_with_hint() {
810 let data = Value::Json(serde_json::json!({"jobs": [1, 2]}));
811 let err = extract_items(Some(&data), "").unwrap_err();
812 assert!(err.contains("single object"), "{err}");
813 assert!(err.contains("jq '.jobs'"), "should hint the array key: {err}");
814 }
815
816 #[test]
817 fn test_extract_items_binary_is_loud() {
818 let data = Value::Bytes(vec![0, 1, 2]);
819 let err = extract_items(Some(&data), "").unwrap_err();
820 assert!(err.contains("binary"), "{err}");
821 }
822
823 #[test]
824 fn test_extract_items_structured_string() {
825 let data = Value::String("single".into());
826 let items = extract_items(Some(&data), "").unwrap();
827 assert_eq!(labels(&items), vec!["single"]);
828 }
829
830 #[test]
831 fn test_extract_items_single_line_text() {
832 let items = extract_items(None, "hello").unwrap();
833 assert_eq!(labels(&items), vec!["hello"]);
834 }
835
836 #[test]
837 fn test_extract_items_empty() {
838 let items = extract_items(None, "").unwrap();
839 assert!(items.is_empty());
840 }
841
842 #[test]
843 fn test_extract_items_multiline_fans_out_per_line() {
844 let items = extract_items(None, "one\ntwo\nthree").unwrap();
845 assert_eq!(labels(&items), vec!["one", "two", "three"]);
846 }
847
848 #[test]
849 fn test_extract_items_trailing_newline_no_phantom_item() {
850 let items = extract_items(None, "one\ntwo\n").unwrap();
851 assert_eq!(labels(&items), vec!["one", "two"]);
852 }
853
854 #[test]
855 fn test_extract_items_crlf_per_line() {
856 let items = extract_items(None, "one\r\ntwo\r\n").unwrap();
857 assert_eq!(labels(&items), vec!["one", "two"]);
858 }
859
860 #[test]
861 fn test_extract_items_blank_lines_skipped() {
862 let items = extract_items(None, "a\n\nb").unwrap();
865 assert_eq!(labels(&items), vec!["a", "b"]);
866 }
867
868 #[test]
869 fn test_extract_items_whitespace_within_line_not_split() {
870 let items = extract_items(None, "a b\nc d").unwrap();
871 assert_eq!(labels(&items), vec!["a b", "c d"]);
872 }
873
874 #[test]
875 fn test_extract_items_only_newlines_is_empty() {
876 let items = extract_items(None, "\n\n").unwrap();
877 assert!(items.is_empty());
878 }
879
880 #[test]
881 fn test_extract_items_structured_overrides_text() {
882 let data = Value::Json(serde_json::json!(["x", "y"]));
883 let items = extract_items(Some(&data), "ignored\ntext").unwrap();
884 assert_eq!(labels(&items), vec!["x", "y"]);
885 }
886
887 #[test]
888 fn test_item_label_truncates_on_char_boundary() {
889 let long: String = "é".repeat(100);
891 let it = ScatterItem::new(serde_json::Value::String(long));
892 assert!(it.label.ends_with("..."));
893 assert_eq!(it.label.chars().count(), 67);
894 }
895
896 #[test]
897 fn test_gather_results_jsonl_rows_carry_everything() {
898 let results = vec![
899 ScatterResult {
900 item: item("a"),
901 result: ExecResult::success("result_a\n"),
902 timed_out: false,
903 },
904 ScatterResult {
905 item: item("b"),
906 result: ExecResult::failure(7, "boom\n"),
907 timed_out: false,
908 },
909 ];
910 let out = gather_results(&results, &GatherOptions::default());
911 assert_eq!(out.code, 123, "any failure → 123 (A′)");
912 let rows: Vec<serde_json::Value> = out
913 .text_out()
914 .lines()
915 .map(|l| serde_json::from_str(l).unwrap())
916 .collect();
917 assert_eq!(rows.len(), 2, "every worker gets a row, failures included");
918 assert_eq!(rows[0]["i"], 0);
919 assert_eq!(rows[0]["item"], "a");
920 assert_eq!(rows[0]["ok"], true);
921 assert_eq!(rows[0]["out"], "result_a", "trailing newline stripped");
922 assert_eq!(rows[0]["err"], "", "err always present");
923 assert!(rows[0].get("timed_out").is_none(), "omit-false");
924 assert!(rows[0].get("data").is_none(), "omit-empty");
925 assert_eq!(rows[1]["i"], 1);
926 assert_eq!(rows[1]["ok"], false);
927 assert_eq!(rows[1]["code"], 7);
928 assert_eq!(rows[1]["err"], "boom");
929 assert!(matches!(out.data, Some(Value::Json(serde_json::Value::Array(_)))));
931 }
932
933 #[test]
934 fn test_gather_results_all_ok_is_zero() {
935 let results = vec![ScatterResult {
936 item: item("a"),
937 result: ExecResult::success("x"),
938 timed_out: false,
939 }];
940 let out = gather_results(&results, &GatherOptions::default());
941 assert_eq!(out.code, 0);
942 assert!(out.err.is_empty());
943 }
944
945 #[test]
946 fn test_gather_results_timeout_row_is_124() {
947 let results = vec![ScatterResult {
948 item: item("slow"),
949 result: ExecResult::failure(1, "cancelled"),
950 timed_out: true,
951 }];
952 let out = gather_results(&results, &GatherOptions::default());
953 assert_eq!(out.code, 123);
954 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
955 assert_eq!(row["code"], 124, "timeout reports the timeout(1) code");
956 assert_eq!(row["ok"], false);
957 assert_eq!(row["timed_out"], true);
958 }
959
960 #[test]
961 fn test_gather_results_typed_record_item_in_row() {
962 let results = vec![ScatterResult {
963 item: ScatterItem::new(serde_json::json!({"id": 3, "host": "web1"})),
964 result: ExecResult::success("ok"),
965 timed_out: false,
966 }];
967 let out = gather_results(&results, &GatherOptions::default());
968 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
969 assert_eq!(row["item"]["id"], 3, "row item is the TYPED value, not a string");
970 }
971
972 #[test]
973 fn test_gather_results_worker_data_rides_the_row() {
974 let mut r = ExecResult::success("text");
975 r.data = Some(Value::Json(serde_json::json!({"k": 1})));
976 let results = vec![ScatterResult { item: item("a"), result: r, timed_out: false }];
977 let out = gather_results(&results, &GatherOptions::default());
978 let row: serde_json::Value = serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
979 assert_eq!(row["data"]["k"], 1, "worker .data lands typed in the row");
980 assert_eq!(row["out"], "text", "out stays alongside data");
981 }
982
983 #[test]
993 fn test_gather_results_spilled_worker_counts_as_failed() {
994 let mut spilled = ExecResult::success("truncated preview");
995 spilled.did_spill = true;
996 spilled.original_code = Some(0);
997 spilled.code = 3; let results = vec![
1000 ScatterResult { item: item("a"), result: spilled, timed_out: false },
1001 ScatterResult { item: item("b"), result: ExecResult::success("clean"), timed_out: false },
1002 ];
1003 let out = gather_results(&results, &GatherOptions::default());
1004 assert_eq!(
1005 out.code, 123,
1006 "a spilled worker (code remapped to 3) must count as failed, not silently succeed"
1007 );
1008 let rows: Vec<serde_json::Value> = out
1009 .text_out()
1010 .lines()
1011 .map(|l| serde_json::from_str(l).unwrap())
1012 .collect();
1013 assert_eq!(rows[0]["ok"], false, "spilled row must read ok:false: {:?}", rows[0]);
1014 assert_eq!(rows[0]["code"], 3, "spilled row must carry the remapped exit 3: {:?}", rows[0]);
1015 assert_eq!(rows[1]["ok"], true, "the clean worker's own row is unaffected: {:?}", rows[1]);
1016 }
1017
1018 #[test]
1019 fn test_gather_results_lines_happy_path() {
1020 let results = vec![
1021 ScatterResult { item: item("a"), result: ExecResult::success("result_a\n"), timed_out: false },
1022 ScatterResult { item: item("b"), result: ExecResult::success("result_b"), timed_out: false },
1023 ];
1024 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1025 assert_eq!(out.code, 0);
1026 assert_eq!(&*out.text_out(), "result_a\nresult_b");
1027 }
1028
1029 #[test]
1030 fn test_gather_results_lines_hard_errors_on_any_failure() {
1031 let results = vec![
1033 ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1034 ScatterResult { item: item("b"), result: ExecResult::failure(1, "boom"), timed_out: false },
1035 ];
1036 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1037 assert_eq!(out.code, 123);
1038 assert!(out.text_out().is_empty(), "no partial text on --lines failure");
1039 assert!(out.err.contains("b"), "names the failed item: {}", out.err);
1040 }
1041
1042 #[test]
1043 fn test_parse_scatter_options() {
1044 use crate::tools::ToolArgs;
1045
1046 let mut args = ToolArgs::new();
1047 args.named.insert("as".to_string(), Value::String("URL".to_string()));
1048 args.named.insert("limit".to_string(), Value::Int(4));
1049
1050 let opts = parse_scatter_options(&args).unwrap();
1051 assert_eq!(opts.var_name, "URL");
1052 assert_eq!(opts.limit, 4);
1053 }
1054
1055 #[test]
1056 fn test_parse_gather_options() {
1057 use crate::tools::ToolArgs;
1058
1059 let mut args = ToolArgs::new();
1060 args.flags.insert("lines".to_string());
1061
1062 let opts = parse_gather_options(&args).unwrap();
1063 assert!(opts.lines);
1064 assert!(!parse_gather_options(&ToolArgs::new()).unwrap().lines, "default is JSONL");
1065 }
1066
1067 #[test]
1068 fn scatter_limit_clamps_to_ceiling() {
1069 use crate::tools::ToolArgs;
1070
1071 let mut args = ToolArgs::new();
1072 args.named.insert("limit".to_string(), Value::Int(999_999));
1073 let opts = parse_scatter_options(&args).unwrap();
1074 assert_eq!(opts.limit, SCATTER_LIMIT_MAX);
1075 }
1076
1077 #[test]
1078 fn scatter_limit_raises_zero_to_one() {
1079 use crate::tools::ToolArgs;
1080
1081 let mut args = ToolArgs::new();
1082 args.named.insert("limit".to_string(), Value::Int(0));
1083 let opts = parse_scatter_options(&args).unwrap();
1084 assert_eq!(opts.limit, 1);
1085 }
1086
1087 #[test]
1088 fn scatter_limit_raises_negative_to_one() {
1089 use crate::tools::ToolArgs;
1090
1091 let mut args = ToolArgs::new();
1092 args.named.insert("limit".to_string(), Value::Int(-42));
1093 let opts = parse_scatter_options(&args).unwrap();
1094 assert_eq!(opts.limit, 1);
1095 }
1096
1097 #[test]
1098 fn scatter_limit_preserves_valid_values() {
1099 use crate::tools::ToolArgs;
1100
1101 let mut args = ToolArgs::new();
1102 args.named.insert("limit".to_string(), Value::Int(500));
1103 let opts = parse_scatter_options(&args).unwrap();
1104 assert_eq!(opts.limit, 500);
1105 }
1106
1107 #[test]
1110 fn scatter_limit_wrong_type_is_loud_error() {
1111 use crate::tools::ToolArgs;
1112
1113 let mut args = ToolArgs::new();
1114 args.named.insert("limit".to_string(), Value::String("five".to_string()));
1115 let err = parse_scatter_options(&args).unwrap_err();
1116 assert!(err.contains("--limit"), "{err}");
1117 assert!(err.contains("five"), "{err}");
1118 }
1119
1120 #[test]
1121 fn scatter_limit_bool_is_loud_error() {
1122 use crate::tools::ToolArgs;
1123
1124 let mut args = ToolArgs::new();
1125 args.named.insert("limit".to_string(), Value::Bool(true));
1126 let err = parse_scatter_options(&args).unwrap_err();
1127 assert!(err.contains("--limit"), "{err}");
1128 }
1129
1130 #[test]
1131 fn scatter_limit_numeric_string_coerces() {
1132 use crate::tools::ToolArgs;
1134
1135 let mut args = ToolArgs::new();
1136 args.named.insert("limit".to_string(), Value::String("5".to_string()));
1137 let opts = parse_scatter_options(&args).unwrap();
1138 assert_eq!(opts.limit, 5);
1139 }
1140
1141 #[test]
1142 fn scatter_as_wrong_type_is_loud_error() {
1143 use crate::tools::ToolArgs;
1144
1145 let mut args = ToolArgs::new();
1146 args.named.insert("as".to_string(), Value::Int(42));
1147 let err = parse_scatter_options(&args).unwrap_err();
1148 assert!(err.contains("--as"), "{err}");
1149 assert!(err.contains("42"), "{err}");
1150 }
1151
1152 #[test]
1153 fn scatter_timeout_negative_int_is_loud_error() {
1154 use crate::tools::ToolArgs;
1155
1156 let mut args = ToolArgs::new();
1157 args.named.insert("timeout".to_string(), Value::Int(-5));
1158 let err = parse_scatter_options(&args).unwrap_err();
1159 assert!(err.contains("--timeout"), "{err}");
1160 }
1161
1162 #[test]
1163 fn scatter_timeout_unparseable_string_is_loud_error() {
1164 use crate::tools::ToolArgs;
1165
1166 let mut args = ToolArgs::new();
1167 args.named.insert("timeout".to_string(), Value::String("banana".to_string()));
1168 let err = parse_scatter_options(&args).unwrap_err();
1169 assert!(err.contains("--timeout"), "{err}");
1170 assert!(err.contains("banana"), "{err}");
1171 }
1172
1173 #[test]
1174 fn scatter_timeout_valid_duration_string_parses() {
1175 use crate::tools::ToolArgs;
1176
1177 let mut args = ToolArgs::new();
1178 args.named.insert("timeout".to_string(), Value::String("5s".to_string()));
1179 let opts = parse_scatter_options(&args).unwrap();
1180 assert_eq!(opts.timeout, Some(Duration::from_secs(5)));
1181 }
1182
1183 #[test]
1184 fn scatter_timeout_nonnegative_int_is_seconds() {
1185 use crate::tools::ToolArgs;
1186
1187 let mut args = ToolArgs::new();
1188 args.named.insert("timeout".to_string(), Value::Int(30));
1189 let opts = parse_scatter_options(&args).unwrap();
1190 assert_eq!(opts.timeout, Some(Duration::from_secs(30)));
1191 }
1192
1193 fn binary_result(invalid_utf8: Vec<u8>) -> ExecResult {
1196 ExecResult::success_bytes(invalid_utf8)
1197 }
1198
1199 #[test]
1200 fn gather_row_goes_loud_not_lossy_on_binary_out() {
1201 let results = vec![ScatterResult {
1204 item: item("bin"),
1205 result: binary_result(vec![0xFF, 0xFE, 0x00, 0x01]),
1206 timed_out: false,
1207 }];
1208 let out = gather_results(&results, &GatherOptions::default());
1209 assert_eq!(out.code, 123, "a binary row flips the overall exit code too");
1210 let row: serde_json::Value =
1211 serde_json::from_str(out.text_out().lines().next().unwrap()).unwrap();
1212 assert_eq!(row["ok"], false, "binary output must not be silently ok:true");
1213 assert_ne!(row["code"], 0, "must carry a nonzero code");
1214 assert!(row["out"].as_str().unwrap().is_empty(), "no lossy text in out");
1215 let err_text = row["err"].as_str().unwrap();
1216 assert!(err_text.contains("binary"), "{err_text}");
1217 assert!(!err_text.contains('\u{FFFD}'), "must not carry U+FFFD: {err_text}");
1218 }
1219
1220 #[test]
1221 fn gather_lines_hard_errors_on_binary_out() {
1222 let results = vec![
1225 ScatterResult { item: item("a"), result: ExecResult::success("good"), timed_out: false },
1226 ScatterResult {
1227 item: item("bin"),
1228 result: binary_result(vec![0xFF, 0xFE]),
1229 timed_out: false,
1230 },
1231 ];
1232 let out = gather_results(&results, &GatherOptions { lines: true, ..Default::default() });
1233 assert_eq!(out.code, 123);
1234 assert!(out.text_out().is_empty(), "no partial/lossy text on binary --lines failure");
1235 assert!(!out.err.contains('\u{FFFD}'), "must not carry U+FFFD: {}", out.err);
1236 assert!(out.err.contains("binary") || out.err.contains("bin"), "{}", out.err);
1237 }
1238
1239 fn ctx_with_memory_fs() -> ExecContext {
1242 use crate::vfs::{MemoryFs, VfsRouter};
1243 use std::sync::Arc;
1244 let mut vfs = VfsRouter::new();
1245 vfs.mount("/", MemoryFs::new());
1246 ExecContext::new(Arc::new(vfs))
1247 }
1248
1249 #[test]
1250 fn worker_ctx_inherits_parent_watchdog() {
1251 use crate::watchdog::Watchdog;
1252 use std::sync::Arc;
1253
1254 let mut parent = ctx_with_memory_fs();
1255 parent.watchdog = Some(Arc::new(Watchdog::new(Duration::from_secs(30))));
1256
1257 let worker_ctx = parent.child_for_pipeline();
1261 assert!(
1262 worker_ctx.watchdog.is_some(),
1263 "worker must carry the parent's script watchdog, not None"
1264 );
1265
1266 let from_scratch =
1269 ExecContext::with_backend_and_scope(parent.backend.clone(), parent.scope.clone());
1270 assert!(
1271 from_scratch.watchdog.is_none(),
1272 "the abandoned from-scratch path is exactly why the worker lost its watchdog"
1273 );
1274 }
1275
1276 #[tokio::test]
1279 async fn worker_spills_over_the_shared_output_limit() {
1280 use crate::output_limit::{apply_spill_contract, OutputLimitConfig};
1281
1282 let mut cfg = OutputLimitConfig::agent().in_memory();
1284 cfg.set_limit(Some(64));
1285
1286 let mut parent = ctx_with_memory_fs();
1287 parent.output_limit = cfg;
1288
1289 let worker_ctx = parent.child_for_pipeline();
1294 assert!(worker_ctx.output_limit.is_enabled(), "budget must reach the worker");
1295
1296 let mut result = ExecResult::success("x".repeat(4096));
1301 assert!(worker_ctx.output_limit.is_enabled());
1302 apply_spill_contract(&mut result, &worker_ctx.output_limit).await;
1303
1304 assert!(result.did_spill, "worker output over the limit must spill, not stay resident");
1305 assert_eq!(
1306 result.code, 3,
1307 "a spilled worker must exit 3 so gather's ok()-based aggregation counts it as failed"
1308 );
1309 assert_eq!(result.original_code, Some(0), "the worker's own clean exit is preserved");
1310 assert!(
1311 result.text_out().len() < 4096,
1312 "spilled output must be truncated, not the full payload: {} bytes",
1313 result.text_out().len()
1314 );
1315 }
1316
1317 #[tokio::test(flavor = "current_thread", start_paused = true)]
1345 async fn worker_completing_at_timeout_boundary_is_not_misclassified() {
1346 use crate::ast::{Arg, Expr};
1347 use crate::dispatch::BackendDispatcher;
1348 use crate::tools::register_builtins;
1349 use crate::vfs::{MemoryFs, VfsRouter};
1350
1351 let mut registry = ToolRegistry::new();
1352 register_builtins(&mut registry);
1353 let tools = Arc::new(registry);
1354 let dispatcher: Arc<dyn CommandDispatcher> =
1355 Arc::new(BackendDispatcher::new(tools.clone()));
1356 let runner = ScatterGatherRunner::new(tools.clone(), dispatcher);
1357
1358 let commands = vec![Command {
1360 name: "sleep".to_string(),
1361 args: vec![Arg::Positional(Expr::Literal(Value::String("0.02".to_string())))],
1362 redirects: vec![],
1363 }];
1364 let opts = ScatterOptions {
1365 timeout: Some(Duration::from_millis(20)),
1366 ..ScatterOptions::default()
1367 };
1368
1369 let mut false_positives = 0;
1370 let mut genuine_timeouts = 0;
1371 let mut clean_success = 0;
1372 let iterations = 300;
1373 for _ in 0..iterations {
1374 let mut vfs = VfsRouter::new();
1379 vfs.mount("/", MemoryFs::new());
1380 let ctx = ExecContext::with_vfs_and_tools(Arc::new(vfs), tools.clone());
1381 let items = vec![item("x")];
1382 let results = runner.run_parallel(&items, &opts, &commands, &ctx).await;
1383 assert_eq!(results.len(), 1);
1384 let r = &results[0];
1385 match (r.timed_out, r.result.ok()) {
1386 (true, true) => false_positives += 1,
1387 (true, false) => genuine_timeouts += 1,
1388 (false, _) => clean_success += 1,
1389 }
1390 }
1391
1392 eprintln!(
1393 "worker_completing_at_timeout_boundary: {false_positives} false-positive(s), \
1394 {genuine_timeouts} genuine timeout(s), {clean_success} clean success(es) out of \
1395 {iterations} iterations"
1396 );
1397 assert!(
1403 genuine_timeouts > 0 && clean_success > 0,
1404 "the tie never formed (genuine_timeouts={genuine_timeouts}, \
1405 clean_success={clean_success}) — this test needs the race to actually occur to \
1406 mean anything; check the tied durations still create a real contest"
1407 );
1408 assert_eq!(
1409 false_positives, 0,
1410 "GH #132: a worker whose operation genuinely completed (result.ok()) must never \
1411 be reported timed_out — completion should win the tie"
1412 );
1413 }
1414}