Skip to main content

blyte_cli/
wait.rs

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