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