1use std::collections::HashSet;
2use std::io::Write;
3use std::path::Path;
4use std::time::{Duration, Instant, SystemTime};
5
6const PARTIAL_WRITE_WINDOW: Duration = Duration::from_secs(2);
7
8pub fn run(ids: &[String], any: bool, timeout_secs: u64) -> i32 {
9 let cwd = match std::env::current_dir() {
10 Ok(d) => d,
11 Err(e) => {
12 eprintln!("error: {e}");
13 return 2;
14 }
15 };
16 let records_dir = match crate::dispatch_in_place::records_dir_for(&cwd) {
17 Ok(d) => d,
18 Err(e) => {
19 eprintln!("error: {e}");
20 return 2;
21 }
22 };
23 wait_in(
24 &records_dir,
25 ids,
26 any,
27 Duration::from_secs(timeout_secs),
28 Duration::from_secs(2),
29 Duration::from_secs(15),
30 &mut std::io::stdout(),
31 &mut std::io::stderr(),
32 )
33}
34
35enum SummaryState {
36 Absent,
37 InProgress,
38 Ready(serde_json::Value),
39 Corrupt(String),
40}
41
42fn is_recently_modified(path: &Path, window: Duration) -> bool {
43 let Ok(meta) = std::fs::metadata(path) else {
44 return false;
45 };
46 let Ok(mtime) = meta.modified() else {
47 return false;
48 };
49 match SystemTime::now().duration_since(mtime) {
50 Ok(age) => age < window,
51 Err(_) => true,
52 }
53}
54
55fn read_summary(path: &Path) -> SummaryState {
56 let raw = match std::fs::read_to_string(path) {
57 Ok(s) => s,
58 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return SummaryState::Absent,
59 Err(e) => return SummaryState::Corrupt(format!("cannot read {}: {e}", path.display())),
60 };
61 match serde_json::from_str::<serde_json::Value>(&raw) {
62 Ok(val) => SummaryState::Ready(val),
63 Err(e) => {
64 if is_recently_modified(path, PARTIAL_WRITE_WINDOW) {
65 SummaryState::InProgress
66 } else {
67 SummaryState::Corrupt(format!("cannot parse {}: {e}", path.display()))
68 }
69 }
70 }
71}
72
73fn check_start_alive(path: &Path) -> Result<Option<bool>, String> {
74 let raw = match std::fs::read_to_string(path) {
75 Ok(s) => s,
76 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
77 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
78 };
79 let val: serde_json::Value =
80 serde_json::from_str(&raw).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
81 crate::clean::run_process_alive(&val)
82 .map(Some)
83 .map_err(|e| format!("{}: {e}", path.display()))
84}
85
86fn format_summary_line(
87 path: &Path,
88 id: &str,
89 summary: &serde_json::Value,
90) -> Result<String, String> {
91 if !summary.is_object() {
92 return Err(format!("{} is not a JSON object", path.display()));
93 }
94 let outcome = summary
95 .get("outcome")
96 .and_then(|v| v.as_str())
97 .ok_or_else(|| format!("{} is missing string field \"outcome\"", path.display()))?;
98 let turns = summary
99 .get("turns")
100 .and_then(|v| {
101 v.as_i64()
102 .map(|t| t.to_string())
103 .or_else(|| v.as_u64().map(|t| t.to_string()))
104 })
105 .ok_or_else(|| format!("{} is missing integer field \"turns\"", path.display()))?;
106 let cost = match summary.get("cost_usd").and_then(|v| v.as_f64()) {
107 Some(c) => format!("${:.2}", c),
108 None => "-".to_string(),
109 };
110 Ok(format!("{id} {outcome} {turns} {cost}"))
111}
112
113enum IdStatus {
114 Finished(String),
115 Running,
116 LooksDead,
117 Unknown,
118 Corrupt(String),
119}
120
121fn check_id_status(wt: &Path, id: &str) -> IdStatus {
122 let summary_path = wt.join(format!("{id}.json"));
123 match read_summary(&summary_path) {
124 SummaryState::Ready(summary) => match format_summary_line(&summary_path, id, &summary) {
125 Ok(line) => return IdStatus::Finished(line),
126 Err(e) => return IdStatus::Corrupt(e),
127 },
128 SummaryState::Corrupt(e) => return IdStatus::Corrupt(e),
129 SummaryState::InProgress => return IdStatus::Running,
130 SummaryState::Absent => {}
131 }
132
133 let start_path = wt.join(format!("{id}.start.json"));
134 match check_start_alive(&start_path) {
135 Ok(Some(true)) => IdStatus::Running,
136 Ok(Some(false)) => match read_summary(&summary_path) {
137 SummaryState::Ready(summary) => {
138 match format_summary_line(&summary_path, id, &summary) {
139 Ok(line) => IdStatus::Finished(line),
140 Err(e) => IdStatus::Corrupt(e),
141 }
142 }
143 SummaryState::Corrupt(e) => IdStatus::Corrupt(e),
144 SummaryState::InProgress => IdStatus::Running,
145 SummaryState::Absent => IdStatus::LooksDead,
146 },
147 Ok(None) => IdStatus::Unknown,
148 Err(e) => IdStatus::Corrupt(e),
149 }
150}
151
152fn is_known(wt: &Path, id: &str) -> bool {
153 wt.join(format!("{id}.json")).exists() || wt.join(format!("{id}.start.json")).exists()
154}
155
156#[allow(clippy::too_many_arguments)]
157pub fn wait_in(
158 wt: &Path,
159 ids: &[String],
160 any: bool,
161 timeout: Duration,
162 poll: Duration,
163 grace: Duration,
164 out: &mut impl Write,
165 err: &mut impl Write,
166) -> i32 {
167 let mut unique_ids: Vec<&str> = Vec::new();
168 let mut seen = HashSet::new();
169 for id in ids {
170 if seen.insert(id.as_str()) {
171 unique_ids.push(id.as_str());
172 }
173 }
174
175 if unique_ids.is_empty() {
176 return 0;
177 }
178
179 let start_time = Instant::now();
180 let mut printed = vec![false; unique_ids.len()];
181 let mut first_dead = vec![None; unique_ids.len()];
182 let mut printed_count = 0;
183
184 loop {
185 let mut printed_this_poll = false;
186 for (i, id) in unique_ids.iter().enumerate() {
187 if printed[i] {
188 continue;
189 }
190 match check_id_status(wt, id) {
191 IdStatus::Finished(line) => {
192 let _ = writeln!(out, "{line}");
193 let _ = out.flush();
194 printed[i] = true;
195 first_dead[i] = None;
196 printed_count += 1;
197 printed_this_poll = true;
198 }
199 IdStatus::Running => {
200 first_dead[i] = None;
201 }
202 IdStatus::LooksDead => {
203 let first_seen = *first_dead[i].get_or_insert_with(Instant::now);
204 if grace.is_zero() || first_seen.elapsed() >= grace {
205 let _ = writeln!(out, "{id} dead - -");
206 let _ = out.flush();
207 printed[i] = true;
208 first_dead[i] = None;
209 printed_count += 1;
210 printed_this_poll = true;
211 }
212 }
213 IdStatus::Unknown => {
214 first_dead[i] = None;
215 }
216 IdStatus::Corrupt(msg) => {
217 let _ = writeln!(err, "error: {msg}");
218 let _ = err.flush();
219 return 1;
220 }
221 }
222 }
223
224 if printed_count == unique_ids.len() {
225 return 0;
226 }
227
228 if any && printed_this_poll {
229 return 0;
230 }
231
232 let elapsed = start_time.elapsed();
233
234 if elapsed >= timeout && timeout < grace {
235 let unprinted: Vec<&str> = unique_ids
236 .iter()
237 .enumerate()
238 .filter(|(i, _)| !printed[*i])
239 .map(|(_, id)| *id)
240 .collect();
241 let _ = writeln!(err, "still running: {}", unprinted.join(" "));
242 let _ = err.flush();
243 return 2;
244 }
245
246 if elapsed >= grace {
247 let unknown_ids: Vec<&str> = unique_ids
248 .iter()
249 .enumerate()
250 .filter(|(i, id)| !printed[*i] && !is_known(wt, id))
251 .map(|(_, id)| *id)
252 .collect();
253 if !unknown_ids.is_empty() {
254 for id in unknown_ids {
255 let _ = writeln!(err, "no dispatch {id} here");
256 }
257 let _ = err.flush();
258 return 1;
259 }
260 }
261
262 if elapsed >= timeout {
263 let unprinted: Vec<&str> = unique_ids
264 .iter()
265 .enumerate()
266 .filter(|(i, _)| !printed[*i])
267 .map(|(_, id)| *id)
268 .collect();
269 let _ = writeln!(err, "still running: {}", unprinted.join(" "));
270 let _ = err.flush();
271 return 2;
272 }
273
274 let remaining = timeout.saturating_sub(start_time.elapsed());
275 let sleep_dur = poll.min(remaining);
276 std::thread::sleep(sleep_dur);
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
285 fn finished_run_prints_summary_line() {
286 let dir = tempfile::tempdir().unwrap();
287 let wt = dir.path();
288 std::fs::write(
289 wt.join("T1.json"),
290 r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
291 )
292 .unwrap();
293 let mut out = Vec::new();
294 let mut err = Vec::new();
295 let code = wait_in(
296 wt,
297 &["T1".to_string()],
298 false,
299 Duration::from_secs(5),
300 Duration::from_millis(10),
301 Duration::ZERO,
302 &mut out,
303 &mut err,
304 );
305 assert_eq!(code, 0);
306 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
307 assert!(err.is_empty());
308 }
309
310 #[test]
311 fn missing_cost_prints_dash() {
312 let dir = tempfile::tempdir().unwrap();
313 let wt = dir.path();
314 std::fs::write(
315 wt.join("T1.json"),
316 r#"{"outcome":"gate_failed","turns":7,"cost_usd":null}"#,
317 )
318 .unwrap();
319 let mut out = Vec::new();
320 let mut err = Vec::new();
321 let code = wait_in(
322 wt,
323 &["T1".to_string()],
324 false,
325 Duration::from_secs(5),
326 Duration::from_millis(10),
327 Duration::ZERO,
328 &mut out,
329 &mut err,
330 );
331 assert_eq!(code, 0);
332 assert_eq!(String::from_utf8(out).unwrap(), "T1 gate_failed 7 -\n");
333 assert!(err.is_empty());
334 }
335
336 #[test]
337 fn dead_run() {
338 let dir = tempfile::tempdir().unwrap();
339 let wt = dir.path();
340 let mut child = std::process::Command::new("true").spawn().unwrap();
341 let pid = child.id();
342 child.wait().unwrap();
343 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
344 let mut out = Vec::new();
345 let mut err = Vec::new();
346 let code = wait_in(
347 wt,
348 &["T1".to_string()],
349 false,
350 Duration::from_secs(5),
351 Duration::from_millis(10),
352 Duration::ZERO,
353 &mut out,
354 &mut err,
355 );
356 assert_eq!(code, 0);
357 assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
358 assert!(err.is_empty());
359 }
360
361 #[test]
362 fn zero_pid_is_dead() {
363 let dir = tempfile::tempdir().unwrap();
364 let wt = dir.path();
365 std::fs::write(wt.join("T1.start.json"), r#"{"pid": 0}"#).unwrap();
366 let mut out = Vec::new();
367 let mut err = Vec::new();
368 let code = wait_in(
369 wt,
370 &["T1".to_string()],
371 false,
372 Duration::from_secs(5),
373 Duration::from_millis(10),
374 Duration::ZERO,
375 &mut out,
376 &mut err,
377 );
378 assert_eq!(code, 0);
379 assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
380 assert!(err.is_empty());
381 }
382
383 #[test]
384 fn unknown_id_errors_without_waiting() {
385 let dir = tempfile::tempdir().unwrap();
386 let wt = dir.path();
387 let mut out = Vec::new();
388 let mut err = Vec::new();
389 let start = Instant::now();
390 let code = wait_in(
391 wt,
392 &["T9".to_string()],
393 false,
394 Duration::from_secs(5),
395 Duration::from_millis(10),
396 Duration::from_millis(50),
397 &mut out,
398 &mut err,
399 );
400 let elapsed = start.elapsed();
401 assert_eq!(code, 1);
402 let err_str = String::from_utf8(err).unwrap();
403 assert!(err_str.contains("no dispatch T9 here"));
404 assert!(out.is_empty());
405 assert!(elapsed < Duration::from_secs(1));
406 }
407
408 #[test]
409 fn timeout_with_running_run() {
410 let dir = tempfile::tempdir().unwrap();
411 let wt = dir.path();
412 let pid = std::process::id();
413 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
414 let mut out = Vec::new();
415 let mut err = Vec::new();
416 let code = wait_in(
417 wt,
418 &["T1".to_string()],
419 false,
420 Duration::from_millis(50),
421 Duration::from_millis(10),
422 Duration::ZERO,
423 &mut out,
424 &mut err,
425 );
426 assert_eq!(code, 2);
427 assert!(out.is_empty());
428 let err_str = String::from_utf8(err).unwrap();
429 assert!(err_str.contains("still running: T1"));
430 }
431
432 #[test]
433 fn all_mode_waits_for_every_run() {
434 let dir = tempfile::tempdir().unwrap();
435 let wt = dir.path();
436 std::fs::write(
437 wt.join("T1.json"),
438 r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
439 )
440 .unwrap();
441 let pid = std::process::id();
442 std::fs::write(wt.join("T2.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
443 let wt_clone = wt.to_path_buf();
444 std::thread::spawn(move || {
445 std::thread::sleep(Duration::from_millis(100));
446 std::fs::write(
447 wt_clone.join("T2.json"),
448 r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
449 )
450 .unwrap();
451 });
452 let mut out = Vec::new();
453 let mut err = Vec::new();
454 let code = wait_in(
455 wt,
456 &["T1".to_string(), "T2".to_string()],
457 false,
458 Duration::from_secs(5),
459 Duration::from_millis(10),
460 Duration::ZERO,
461 &mut out,
462 &mut err,
463 );
464 assert_eq!(code, 0);
465 let out_str = String::from_utf8(out).unwrap();
466 assert_eq!(out_str, "T1 verified 41 $0.37\nT2 verified 10 $0.10\n");
467 assert!(err.is_empty());
468 }
469
470 #[test]
471 fn any_mode_returns_after_first() {
472 let dir = tempfile::tempdir().unwrap();
473 let wt = dir.path();
474 let pid = std::process::id();
475 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
476 std::fs::write(
477 wt.join("T2.json"),
478 r#"{"outcome":"verified","turns":12,"cost_usd":0.20}"#,
479 )
480 .unwrap();
481 let mut out = Vec::new();
482 let mut err = Vec::new();
483 let code = wait_in(
484 wt,
485 &["T1".to_string(), "T2".to_string()],
486 true,
487 Duration::from_secs(5),
488 Duration::from_millis(10),
489 Duration::ZERO,
490 &mut out,
491 &mut err,
492 );
493 assert_eq!(code, 0);
494 assert_eq!(String::from_utf8(out).unwrap(), "T2 verified 12 $0.20\n");
495 assert!(err.is_empty());
496 }
497
498 #[test]
499 fn any_mode_prints_all_already_finished() {
500 let dir = tempfile::tempdir().unwrap();
501 let wt = dir.path();
502 std::fs::write(
503 wt.join("T1.json"),
504 r#"{"outcome":"verified","turns":1,"cost_usd":0.01}"#,
505 )
506 .unwrap();
507 std::fs::write(
508 wt.join("T2.json"),
509 r#"{"outcome":"gate_failed","turns":2,"cost_usd":0.02}"#,
510 )
511 .unwrap();
512 let mut out = Vec::new();
513 let mut err = Vec::new();
514 let code = wait_in(
515 wt,
516 &["T1".to_string(), "T2".to_string()],
517 true,
518 Duration::from_secs(5),
519 Duration::from_millis(10),
520 Duration::ZERO,
521 &mut out,
522 &mut err,
523 );
524 assert_eq!(code, 0);
525 let out_str = String::from_utf8(out).unwrap();
526 let lines: Vec<&str> = out_str.lines().collect();
527 assert_eq!(lines, vec!["T1 verified 1 $0.01", "T2 gate_failed 2 $0.02"]);
528 assert!(err.is_empty());
529 }
530
531 #[test]
532 fn any_mode_timeout() {
533 let dir = tempfile::tempdir().unwrap();
534 let wt = dir.path();
535 let pid = std::process::id();
536 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
537 let mut out = Vec::new();
538 let mut err = Vec::new();
539 let code = wait_in(
540 wt,
541 &["T1".to_string()],
542 true,
543 Duration::from_millis(50),
544 Duration::from_millis(10),
545 Duration::ZERO,
546 &mut out,
547 &mut err,
548 );
549 assert_eq!(code, 2);
550 assert!(out.is_empty());
551 let err_str = String::from_utf8(err).unwrap();
552 assert!(err_str.contains("still running: T1"));
553 }
554
555 #[test]
556 fn summary_written_after_start_counts_as_finished() {
557 let dir = tempfile::tempdir().unwrap();
558 let wt = dir.path();
559 let mut child = std::process::Command::new("true").spawn().unwrap();
560 let pid = child.id();
561 child.wait().unwrap();
562 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
563 std::fs::write(
564 wt.join("T1.json"),
565 r#"{"outcome":"verified","turns":5,"cost_usd":0.05}"#,
566 )
567 .unwrap();
568 let mut out = Vec::new();
569 let mut err = Vec::new();
570 let code = wait_in(
571 wt,
572 &["T1".to_string()],
573 false,
574 Duration::from_secs(5),
575 Duration::from_millis(10),
576 Duration::ZERO,
577 &mut out,
578 &mut err,
579 );
580 assert_eq!(code, 0);
581 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 5 $0.05\n");
582 assert!(err.is_empty());
583 }
584
585 #[test]
586 fn unparseable_summary_is_not_finished() {
587 let dir = tempfile::tempdir().unwrap();
588 let wt = dir.path();
589 std::fs::write(wt.join("T1.json"), r#"{"outc"#).unwrap();
590 let pid = std::process::id();
591 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
592 let mut out = Vec::new();
593 let mut err = Vec::new();
594 let code = wait_in(
595 wt,
596 &["T1".to_string()],
597 false,
598 Duration::from_millis(50),
599 Duration::from_millis(10),
600 Duration::ZERO,
601 &mut out,
602 &mut err,
603 );
604 assert_eq!(code, 2);
605 assert!(out.is_empty());
606 let err_str = String::from_utf8(err).unwrap();
607 assert!(err_str.contains("still running: T1"));
608 }
609
610 #[test]
611 fn duplicate_ids_reported_once() {
612 let dir = tempfile::tempdir().unwrap();
613 let wt = dir.path();
614 std::fs::write(
615 wt.join("T1.json"),
616 r#"{"outcome":"verified","turns":41,"cost_usd":0.374}"#,
617 )
618 .unwrap();
619 let mut out = Vec::new();
620 let mut err = Vec::new();
621 let code = wait_in(
622 wt,
623 &["T1".to_string(), "T1".to_string()],
624 false,
625 Duration::from_secs(5),
626 Duration::from_millis(10),
627 Duration::ZERO,
628 &mut out,
629 &mut err,
630 );
631 assert_eq!(code, 0);
632 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 41 $0.37\n");
633 assert!(err.is_empty());
634 }
635
636 #[test]
637 fn finishing_run_within_grace_reports_summary() {
638 let dir = tempfile::tempdir().unwrap();
639 let wt = dir.path();
640 let mut child = std::process::Command::new("true").spawn().unwrap();
641 let pid = child.id();
642 child.wait().unwrap();
643 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
644 let wt_clone = wt.to_path_buf();
645 std::thread::spawn(move || {
646 std::thread::sleep(Duration::from_millis(100));
647 std::fs::write(
648 wt_clone.join("T1.json"),
649 r#"{"outcome":"verified","turns":3,"cost_usd":0.1}"#,
650 )
651 .unwrap();
652 });
653 let mut out = Vec::new();
654 let mut err = Vec::new();
655 let code = wait_in(
656 wt,
657 &["T1".to_string()],
658 false,
659 Duration::from_secs(5),
660 Duration::from_millis(10),
661 Duration::from_secs(2),
662 &mut out,
663 &mut err,
664 );
665 assert_eq!(code, 0);
666 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 3 $0.10\n");
667 assert!(err.is_empty());
668 }
669
670 #[test]
671 fn dead_run_reported_after_grace() {
672 let dir = tempfile::tempdir().unwrap();
673 let wt = dir.path();
674 let mut child = std::process::Command::new("true").spawn().unwrap();
675 let pid = child.id();
676 child.wait().unwrap();
677 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
678 let mut out = Vec::new();
679 let mut err = Vec::new();
680 let start = Instant::now();
681 let code = wait_in(
682 wt,
683 &["T1".to_string()],
684 false,
685 Duration::from_secs(5),
686 Duration::from_millis(10),
687 Duration::from_millis(150),
688 &mut out,
689 &mut err,
690 );
691 let elapsed = start.elapsed();
692 assert_eq!(code, 0);
693 assert_eq!(String::from_utf8(out).unwrap(), "T1 dead - -\n");
694 assert!(elapsed >= Duration::from_millis(150));
695 assert!(err.is_empty());
696 }
697
698 #[test]
699 fn timeout_inside_grace_is_still_running() {
700 let dir = tempfile::tempdir().unwrap();
701 let wt = dir.path();
702 let mut child = std::process::Command::new("true").spawn().unwrap();
703 let pid = child.id();
704 child.wait().unwrap();
705 std::fs::write(wt.join("T1.start.json"), format!(r#"{{"pid": {pid}}}"#)).unwrap();
706 let mut out = Vec::new();
707 let mut err = Vec::new();
708 let code = wait_in(
709 wt,
710 &["T1".to_string()],
711 false,
712 Duration::from_millis(100),
713 Duration::from_millis(10),
714 Duration::from_secs(5),
715 &mut out,
716 &mut err,
717 );
718 assert_eq!(code, 2);
719 assert!(out.is_empty());
720 let err_str = String::from_utf8(err).unwrap();
721 assert!(err_str.contains("still running: T1"));
722 }
723
724 #[test]
725 fn summary_without_start_file_written_after_start() {
726 let dir = tempfile::tempdir().unwrap();
727 let wt = dir.path();
728 let wt_clone = wt.to_path_buf();
729 std::thread::spawn(move || {
730 std::thread::sleep(Duration::from_millis(100));
731 std::fs::write(
732 wt_clone.join("T1.json"),
733 r#"{"outcome":"verified","turns":15,"cost_usd":0.25}"#,
734 )
735 .unwrap();
736 });
737 let mut out = Vec::new();
738 let mut err = Vec::new();
739 let code = wait_in(
740 wt,
741 &["T1".to_string()],
742 false,
743 Duration::from_secs(5),
744 Duration::from_millis(10),
745 Duration::from_secs(2),
746 &mut out,
747 &mut err,
748 );
749 assert_eq!(code, 0);
750 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 15 $0.25\n");
751 assert!(err.is_empty());
752 }
753
754 #[test]
755 fn one_summary_one_never_appearing() {
756 let dir = tempfile::tempdir().unwrap();
757 let wt = dir.path();
758 std::fs::write(
759 wt.join("T1.json"),
760 r#"{"outcome":"verified","turns":10,"cost_usd":0.10}"#,
761 )
762 .unwrap();
763 let mut out = Vec::new();
764 let mut err = Vec::new();
765 let code = wait_in(
766 wt,
767 &["T1".to_string(), "T2".to_string()],
768 false,
769 Duration::from_secs(5),
770 Duration::from_millis(10),
771 Duration::from_millis(50),
772 &mut out,
773 &mut err,
774 );
775 assert_eq!(code, 1);
776 let err_str = String::from_utf8(err).unwrap();
777 assert!(err_str.contains("no dispatch T2 here"));
778 assert!(!err_str.contains("no dispatch T1 here"));
779 assert_eq!(String::from_utf8(out).unwrap(), "T1 verified 10 $0.10\n");
780 }
781
782 #[test]
783 fn timeout_before_grace_with_unknown_id() {
784 let dir = tempfile::tempdir().unwrap();
785 let wt = dir.path();
786 let mut out = Vec::new();
787 let mut err = Vec::new();
788 let code = wait_in(
789 wt,
790 &["T9".to_string()],
791 false,
792 Duration::from_millis(50),
793 Duration::from_millis(10),
794 Duration::from_secs(5),
795 &mut out,
796 &mut err,
797 );
798 assert_eq!(code, 2);
799 assert!(out.is_empty());
800 let err_str = String::from_utf8(err).unwrap();
801 assert!(err_str.contains("still running: T9"));
802 }
803
804 #[test]
805 fn multiple_unknown_ids_reported_in_argument_order() {
806 let dir = tempfile::tempdir().unwrap();
807 let wt = dir.path();
808 let mut out = Vec::new();
809 let mut err = Vec::new();
810 let code = wait_in(
811 wt,
812 &["B".to_string(), "A".to_string()],
813 false,
814 Duration::from_secs(5),
815 Duration::from_millis(10),
816 Duration::from_millis(50),
817 &mut out,
818 &mut err,
819 );
820 assert_eq!(code, 1);
821 assert!(out.is_empty());
822 let err_str = String::from_utf8(err).unwrap();
823 assert_eq!(err_str, "no dispatch B here\nno dispatch A here\n");
824 }
825
826 #[test]
827 fn cli_parses_wait() {
828 use crate::cli::{Cli, Command};
829 use clap::Parser;
830
831 let cli =
832 Cli::try_parse_from(["blyte", "wait", "A", "B", "--any", "--timeout", "10"]).unwrap();
833 assert_eq!(
834 cli.command,
835 Some(Command::Wait {
836 ids: vec!["A".to_string(), "B".to_string()],
837 any: true,
838 timeout: 10,
839 })
840 );
841
842 let cli = Cli::try_parse_from(["blyte", "wait", "A"]).unwrap();
843 assert_eq!(
844 cli.command,
845 Some(Command::Wait {
846 ids: vec!["A".to_string()],
847 any: false,
848 timeout: 280,
849 })
850 );
851
852 assert!(Cli::try_parse_from(["blyte", "wait"]).is_err());
853 }
854
855 fn set_older_than_window(path: &Path) {
856 let old_time = SystemTime::now() - Duration::from_secs(10);
857 let file = std::fs::OpenOptions::new().write(true).open(path).unwrap();
858 file.set_modified(old_time).unwrap();
859 }
860
861 #[test]
862 fn missing_outcome_in_summary_exits_1_and_names_file_and_field() {
863 let dir = tempfile::tempdir().unwrap();
864 let wt = dir.path();
865 let path = wt.join("X.json");
866 std::fs::write(&path, r#"{"id":"X"}"#).unwrap();
867 set_older_than_window(&path);
868
869 let mut out = Vec::new();
870 let mut err = Vec::new();
871 let code = wait_in(
872 wt,
873 &["X".to_string()],
874 false,
875 Duration::from_secs(5),
876 Duration::from_millis(10),
877 Duration::ZERO,
878 &mut out,
879 &mut err,
880 );
881 let out_str = String::from_utf8(out).unwrap();
882 let err_str = String::from_utf8(err).unwrap();
883 assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
884 assert!(!out_str.contains('?'), "stdout={out_str:?}");
885 assert!(!err_str.contains('?'), "stderr={err_str:?}");
886 assert!(
887 err_str.contains(&path.display().to_string()),
888 "stderr={err_str:?}"
889 );
890 assert!(err_str.contains("outcome"), "stderr={err_str:?}");
891 }
892
893 #[test]
894 fn missing_turns_in_summary_exits_1_and_names_file_and_field() {
895 let dir = tempfile::tempdir().unwrap();
896 let wt = dir.path();
897 let path = wt.join("X.json");
898 std::fs::write(&path, r#"{"id":"X","outcome":"verified"}"#).unwrap();
899 set_older_than_window(&path);
900
901 let mut out = Vec::new();
902 let mut err = Vec::new();
903 let code = wait_in(
904 wt,
905 &["X".to_string()],
906 false,
907 Duration::from_secs(5),
908 Duration::from_millis(10),
909 Duration::ZERO,
910 &mut out,
911 &mut err,
912 );
913 let out_str = String::from_utf8(out).unwrap();
914 let err_str = String::from_utf8(err).unwrap();
915 assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
916 assert!(!out_str.contains('?'), "stdout={out_str:?}");
917 assert!(!err_str.contains('?'), "stderr={err_str:?}");
918 assert!(
919 err_str.contains(&path.display().to_string()),
920 "stderr={err_str:?}"
921 );
922 assert!(err_str.contains("turns"), "stderr={err_str:?}");
923 }
924
925 #[test]
926 fn old_corrupt_summary_json_exits_1_and_names_file() {
927 let dir = tempfile::tempdir().unwrap();
928 let wt = dir.path();
929 let path = wt.join("X.json");
930 std::fs::write(&path, r#"{"outc"#).unwrap();
931 set_older_than_window(&path);
932
933 let mut out = Vec::new();
934 let mut err = Vec::new();
935 let code = wait_in(
936 wt,
937 &["X".to_string()],
938 false,
939 Duration::from_secs(5),
940 Duration::from_millis(10),
941 Duration::ZERO,
942 &mut out,
943 &mut err,
944 );
945 let out_str = String::from_utf8(out).unwrap();
946 let err_str = String::from_utf8(err).unwrap();
947 assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
948 assert!(out_str.is_empty(), "stdout={out_str:?}");
949 assert!(
950 err_str.contains(&path.display().to_string()),
951 "stderr={err_str:?}"
952 );
953 }
954
955 #[test]
956 fn corrupt_start_json_exits_1_and_names_file() {
957 let dir = tempfile::tempdir().unwrap();
958 let wt = dir.path();
959 let start_path = wt.join("X.start.json");
960 std::fs::write(&start_path, "{broken").unwrap();
961
962 let mut out = Vec::new();
963 let mut err = Vec::new();
964 let code = wait_in(
965 wt,
966 &["X".to_string()],
967 false,
968 Duration::from_secs(5),
969 Duration::from_millis(10),
970 Duration::ZERO,
971 &mut out,
972 &mut err,
973 );
974 let out_str = String::from_utf8(out).unwrap();
975 let err_str = String::from_utf8(err).unwrap();
976 assert_eq!(code, 1, "stdout={out_str:?} stderr={err_str:?}");
977 assert!(out_str.is_empty(), "stdout={out_str:?}");
978 assert!(
979 err_str.contains(&start_path.display().to_string()),
980 "stderr={err_str:?}"
981 );
982 }
983}