Skip to main content

lean_ctx/server/
background_shell.rs

1//! Explicit, in-process background jobs for `ctx_shell`.
2//!
3//! The MCP request may complete immediately, but the child keeps the exact
4//! timeout, allow-list, path-jail and process-group policy of foreground shell
5//! execution. Jobs intentionally live in the daemon: restarting it invalidates
6//! outstanding jobs rather than silently orphaning subprocesses.
7
8use std::collections::HashMap;
9use std::sync::{
10    Arc, LazyLock, Mutex,
11    atomic::{AtomicBool, Ordering},
12};
13use std::time::{Duration, Instant};
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum JobState {
17    Running { output: String },
18    Completed { output: String, exit_code: i32 },
19    Cancelled { output: String },
20}
21
22const MAX_RETAINED_COMPLETED_JOBS: usize = 64;
23const MAX_RETAINED_COMPLETED_BYTES: usize = 16 * 1024 * 1024;
24const COMPLETED_JOB_TTL: Duration = Duration::from_mins(5);
25
26struct Job {
27    cancel: Arc<AtomicBool>,
28    state: JobState,
29    finished_at: Option<Instant>,
30    // #1217: shared buffer the worker streams captured output into while the
31    // job runs, so `status` can report progress before the job completes.
32    live: Arc<Mutex<String>>,
33    // #1876: identical launches coalesce onto one entry, so several foreground
34    // calls can wait on it at once. Each reads its result from the entry, so it
35    // is removed only once the last waiter has read it, and never while a
36    // background caller (explicit or detached) may still poll it by id.
37    foreground_waiters: usize,
38    background_owned: bool,
39}
40
41static JOBS: LazyLock<Mutex<HashMap<String, Job>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
42
43/// How often a foreground run reports progress to the MCP client (#1173).
44const TICK: Duration = Duration::from_secs(5);
45
46fn prune_finished_jobs(jobs: &mut HashMap<String, Job>, now: Instant) {
47    prune_finished_jobs_with_limits(
48        jobs,
49        now,
50        MAX_RETAINED_COMPLETED_JOBS,
51        MAX_RETAINED_COMPLETED_BYTES,
52    );
53}
54
55fn prune_finished_jobs_with_limits(
56    jobs: &mut HashMap<String, Job>,
57    now: Instant,
58    max_completed_jobs: usize,
59    max_completed_bytes: usize,
60) {
61    jobs.retain(|_, job| {
62        job.foreground_waiters > 0
63            || job
64                .finished_at
65                .is_none_or(|finished_at| now.duration_since(finished_at) < COMPLETED_JOB_TTL)
66    });
67
68    let mut completed: Vec<_> = jobs
69        .iter()
70        .filter(|(_, job)| job.foreground_waiters == 0)
71        .filter_map(|(id, job)| {
72            let finished_at = job.finished_at?;
73            let output_bytes = match &job.state {
74                JobState::Completed { output, .. } | JobState::Cancelled { output } => output.len(),
75                JobState::Running { .. } => 0,
76            };
77            Some((finished_at, id.clone(), output_bytes))
78        })
79        .collect();
80    completed.sort_unstable_by_key(|(finished_at, _, _)| *finished_at);
81
82    let mut retained_bytes = completed.iter().map(|(_, _, bytes)| bytes).sum::<usize>();
83    let mut retained_jobs = completed.len();
84    for (_, id, output_bytes) in completed {
85        if retained_jobs <= max_completed_jobs && retained_bytes <= max_completed_bytes {
86            break;
87        }
88        if retained_jobs == 1 {
89            break;
90        }
91        jobs.remove(&id);
92        retained_jobs -= 1;
93        retained_bytes = retained_bytes.saturating_sub(output_bytes);
94    }
95}
96
97pub fn start(
98    command: String,
99    cwd: String,
100    extra_env: std::collections::HashMap<String, String>,
101    timeout_ms: Option<u64>,
102) -> String {
103    start_inner(command, cwd, extra_env, timeout_ms, false)
104}
105
106fn start_inner(
107    command: String,
108    cwd: String,
109    extra_env: std::collections::HashMap<String, String>,
110    timeout_ms: Option<u64>,
111    foreground: bool,
112) -> String {
113    // IDs are content-addressed so tool responses stay deterministic (#498).
114    // An identical in-flight launch coalesces onto the same job instead of
115    // creating duplicate expensive builds/tests.
116    let mut env_entries: Vec<_> = extra_env.iter().collect();
117    env_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
118    let env_key = env_entries
119        .into_iter()
120        .map(|(key, value)| format!("{key}={value}"))
121        .collect::<Vec<_>>()
122        .join("\0");
123    let material = format!(
124        "{command}\0{cwd}\0{}\0{env_key}",
125        timeout_ms.unwrap_or_default()
126    );
127    let id = format!(
128        "shell_{}",
129        &blake3::hash(material.as_bytes()).to_hex()[..16]
130    );
131    let cancel = Arc::new(AtomicBool::new(false));
132    let worker_cancel = Arc::clone(&cancel);
133    let live = Arc::new(Mutex::new(String::new()));
134    let worker_live = Arc::clone(&live);
135    {
136        let mut jobs = JOBS
137            .lock()
138            .unwrap_or_else(std::sync::PoisonError::into_inner);
139        prune_finished_jobs(&mut jobs, Instant::now());
140        // A finished entry that a foreground waiter has not read yet is joined
141        // too (#1876): replacing it would hand that waiter's release to the new
142        // job, which then disappears under its own waiter.
143        if let Some(job) = jobs.get_mut(&id)
144            && (matches!(job.state, JobState::Running { .. }) || job.foreground_waiters > 0)
145        {
146            if foreground {
147                job.foreground_waiters += 1;
148            } else {
149                job.background_owned = true;
150            }
151            return id;
152        }
153        jobs.insert(
154            id.clone(),
155            Job {
156                cancel,
157                state: JobState::Running {
158                    output: String::new(),
159                },
160                finished_at: None,
161                live,
162                foreground_waiters: usize::from(foreground),
163                background_owned: !foreground,
164            },
165        );
166    }
167
168    let worker_id = id.clone();
169    std::thread::spawn(move || {
170        let (output, exit_code) = crate::server::execute::execute_command_with_env_cancellable(
171            &command,
172            &cwd,
173            &extra_env,
174            timeout_ms,
175            Some(&worker_cancel),
176            // #1113/#1173: bounded by output, not wall clock — a monitor loop
177            // emitting a line every 45s must survive. See `idle_keyed`.
178            true,
179            // #1217: stream captured output into the shared buffer as it arrives.
180            Some(&worker_live),
181        );
182        let mut jobs = JOBS
183            .lock()
184            .unwrap_or_else(std::sync::PoisonError::into_inner);
185        let Some(job) = jobs.get_mut(&worker_id) else {
186            return;
187        };
188        job.state = if worker_cancel.load(Ordering::Acquire) {
189            JobState::Cancelled { output }
190        } else {
191            JobState::Completed { output, exit_code }
192        };
193        job.finished_at = Some(Instant::now());
194        prune_finished_jobs(&mut jobs, Instant::now());
195    });
196    id
197}
198
199/// Outcome of a foreground run that is allowed to detach on a soft cap.
200pub enum ForegroundResult {
201    /// The command finished within the soft cap; output is returned inline and
202    /// the job has been removed from the registry.
203    Finished { output: String, exit_code: i32 },
204    /// The command was still running at the soft cap and was left running as a
205    /// pollable background job (#1106).
206    Detached { job_id: String },
207}
208
209/// Run `command` as a managed background job but block up to `soft_cap` waiting
210/// for it to finish, so fast commands still return their output inline.
211///
212/// The MCP host aborts a tool call that stays in the foreground too long
213/// (~120s) and hands back a task id that `background_action=status` cannot
214/// resolve. By detaching *before* that deadline we always return a real
215/// `shell_*` job id the caller can poll or cancel (#1106).
216///
217/// `on_tick` is called roughly every `TICK` while the command is still
218/// running, so the caller can emit MCP progress notifications and a 3-minute
219/// build stops being indistinguishable from a hang (#1173).
220pub fn run_foreground_or_detach(
221    command: String,
222    cwd: String,
223    extra_env: std::collections::HashMap<String, String>,
224    timeout_ms: Option<u64>,
225    soft_cap: Duration,
226    on_tick: Option<&dyn Fn(Duration)>,
227    cancel: Option<&tokio_util::sync::CancellationToken>,
228) -> ForegroundResult {
229    let id = start_inner(command, cwd, extra_env, timeout_ms, true);
230    let started = Instant::now();
231    let deadline = started + soft_cap;
232    let mut next_tick = started + TICK;
233    loop {
234        match status(&id) {
235            Some(JobState::Completed { output, exit_code }) => {
236                release_foreground(&id, false);
237                return ForegroundResult::Finished { output, exit_code };
238            }
239            // A cancel can only be requested via background_action once the job
240            // is detached, so an inline wait realistically only sees Completed;
241            // handle Cancelled defensively with the timeout exit code.
242            Some(JobState::Cancelled { output }) => {
243                release_foreground(&id, false);
244                return ForegroundResult::Finished {
245                    output,
246                    exit_code: 130,
247                };
248            }
249            _ => {}
250        }
251        // #1781: when the host abandons the call, free this thread immediately.
252        // The foreground wait runs on the blocking pool — dispatch hands the
253        // handler to `spawn_blocking`, and that pool has
254        // `(workers * 4).clamp(8, 32)` slots. Without this check the loop spun
255        // on until `soft_cap` — five minutes for a `timeout_ms: 300_000` call —
256        // so a burst of abandoned commands could occupy every slot, after which
257        // subsequent tool calls queued behind them until the server restarted.
258        // Detaching rather than killing keeps the job alive under its id, which
259        // the caller already knows how to poll and cancel.
260        if cancel.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
261            release_foreground(&id, true);
262            return ForegroundResult::Detached { job_id: id };
263        }
264        let now = Instant::now();
265        if now >= deadline {
266            release_foreground(&id, true);
267            return ForegroundResult::Detached { job_id: id };
268        }
269        if let Some(tick) = on_tick
270            && now >= next_tick
271        {
272            tick(started.elapsed());
273            next_tick = now + TICK;
274        }
275        std::thread::sleep(Duration::from_millis(50));
276    }
277}
278
279/// One foreground waiter is done with `id` (#1876). A detached waiter hands the
280/// id to its caller, so the entry becomes background-owned and stays pollable.
281/// Otherwise the entry is removed once no waiter and no background caller is
282/// left; a waiter that still polls it must not find it gone.
283fn release_foreground(id: &str, detached: bool) {
284    let mut jobs = JOBS
285        .lock()
286        .unwrap_or_else(std::sync::PoisonError::into_inner);
287    let Some(job) = jobs.get_mut(id) else {
288        return;
289    };
290    job.foreground_waiters = job.foreground_waiters.saturating_sub(1);
291    if detached {
292        job.background_owned = true;
293    } else if job.foreground_waiters == 0 && !job.background_owned {
294        jobs.remove(id);
295    }
296}
297
298#[cfg(test)]
299pub(crate) fn remove_for_test(id: &str) {
300    JOBS.lock()
301        .unwrap_or_else(std::sync::PoisonError::into_inner)
302        .remove(id);
303}
304
305pub fn status(id: &str) -> Option<JobState> {
306    let jobs = JOBS
307        .lock()
308        .unwrap_or_else(std::sync::PoisonError::into_inner);
309    let job = jobs.get(id)?;
310    Some(match &job.state {
311        // #1217: a running job's output lives in the shared buffer the worker
312        // streams into; surface the captured-so-far snapshot on each poll.
313        JobState::Running { .. } => JobState::Running {
314            output: job
315                .live
316                .lock()
317                .unwrap_or_else(std::sync::PoisonError::into_inner)
318                .clone(),
319        },
320        other => other.clone(),
321    })
322}
323
324pub fn cancel(id: &str) -> Option<JobState> {
325    let mut jobs = JOBS
326        .lock()
327        .unwrap_or_else(std::sync::PoisonError::into_inner);
328    let job = jobs.get_mut(id)?;
329    if matches!(job.state, JobState::Running { .. }) {
330        job.cancel.store(true, Ordering::Release);
331    }
332    Some(job.state.clone())
333}
334
335#[cfg(test)]
336mod tests {
337    use super::{
338        ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
339    };
340    use std::time::Duration;
341
342    #[test]
343    fn completed_job_retention_is_bounded() {
344        let now = std::time::Instant::now();
345        let mut jobs = std::collections::HashMap::new();
346        for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
347            jobs.insert(
348                format!("job_{index}"),
349                super::Job {
350                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
351                    state: JobState::Completed {
352                        output: "x".repeat(1024),
353                        exit_code: 0,
354                    },
355                    finished_at: Some(
356                        now.checked_sub(Duration::from_secs((index + 1) as u64))
357                            .unwrap(),
358                    ),
359                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
360                    foreground_waiters: 0,
361                    background_owned: true,
362                },
363            );
364        }
365        jobs.insert(
366            "expired".to_string(),
367            super::Job {
368                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
369                state: JobState::Completed {
370                    output: "expired".to_string(),
371                    exit_code: 0,
372                },
373                finished_at: Some(
374                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
375                        .unwrap(),
376                ),
377                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
378                foreground_waiters: 0,
379                background_owned: true,
380            },
381        );
382
383        super::prune_finished_jobs(&mut jobs, now);
384
385        assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
386        assert!(!jobs.contains_key("expired"));
387        assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
388    }
389
390    #[test]
391    fn completed_job_output_bytes_are_bounded() {
392        let now = std::time::Instant::now();
393        let mut jobs = std::collections::HashMap::new();
394        for index in 0..3 {
395            jobs.insert(
396                format!("job_{index}"),
397                super::Job {
398                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
399                    state: JobState::Completed {
400                        output: "x".repeat(8),
401                        exit_code: 0,
402                    },
403                    finished_at: Some(
404                        now.checked_sub(Duration::from_secs((3 - index) as u64))
405                            .unwrap(),
406                    ),
407                    live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
408                    foreground_waiters: 0,
409                    background_owned: true,
410                },
411            );
412        }
413
414        super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
415
416        assert_eq!(jobs.len(), 2);
417        assert!(!jobs.contains_key("job_0"));
418    }
419
420    #[test]
421    #[cfg_attr(windows, ignore)]
422    fn foreground_run_finishing_within_cap_returns_inline() {
423        let result = run_foreground_or_detach(
424            "printf FG_OK".to_string(),
425            ".".to_string(),
426            std::collections::HashMap::default(),
427            Some(10_000),
428            Duration::from_secs(10),
429            None,
430            None,
431        );
432        match result {
433            ForegroundResult::Finished { output, exit_code } => {
434                assert_eq!(exit_code, 0);
435                assert!(output.contains("FG_OK"));
436            }
437            ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
438        }
439    }
440
441    #[test]
442    #[cfg_attr(windows, ignore)]
443    fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
444        let result = run_foreground_or_detach(
445            "sleep 5; printf SLOW_OK".to_string(),
446            ".".to_string(),
447            std::collections::HashMap::default(),
448            Some(10_000),
449            Duration::from_millis(100),
450            None,
451            None,
452        );
453        let ForegroundResult::Detached { job_id } = result else {
454            panic!("slow command should detach");
455        };
456        assert!(job_id.starts_with("shell_"));
457        // The returned id must resolve via status — the core #1106 guarantee.
458        assert!(status(&job_id).is_some());
459        cancel(&job_id);
460    }
461
462    /// #1173: a `timeout_ms` far beyond the soft cap must NOT keep the command
463    /// in the foreground. Raising the cap past the MCP host's ~120s abort is
464    /// what stranded results behind an unresolvable task id; the caller must
465    /// still get a real `shell_*` job id at the cap.
466    #[test]
467    #[cfg_attr(windows, ignore)]
468    fn large_timeout_ms_still_detaches_at_the_soft_cap() {
469        let result = run_foreground_or_detach(
470            "sleep 5; printf NEVER_INLINE".to_string(),
471            ".".to_string(),
472            std::collections::HashMap::default(),
473            Some(600_000),
474            Duration::from_millis(100),
475            None,
476            None,
477        );
478        let ForegroundResult::Detached { job_id } = result else {
479            panic!("timeout_ms must not extend the foreground wait");
480        };
481        assert!(status(&job_id).is_some());
482        cancel(&job_id);
483    }
484
485    /// #1173: a foreground run reports progress while it waits, so a slow
486    /// command is distinguishable from a hang. Deliberately slower than the
487    /// other tests here — it has to outlive one real [`TICK`].
488    #[test]
489    #[cfg_attr(windows, ignore)]
490    fn foreground_run_reports_progress_while_waiting() {
491        let ticks = std::sync::atomic::AtomicUsize::new(0);
492        let tick = |elapsed: Duration| {
493            assert!(elapsed >= TICK, "tick must report real elapsed time");
494            ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
495        };
496        let result = run_foreground_or_detach(
497            "sleep 30".to_string(),
498            ".".to_string(),
499            std::collections::HashMap::default(),
500            Some(60_000),
501            TICK + Duration::from_millis(500),
502            Some(&tick),
503            None,
504        );
505        let ForegroundResult::Detached { job_id } = result else {
506            panic!("slow command should detach");
507        };
508        cancel(&job_id);
509        assert!(
510            ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
511            "no progress reported during a {}s+ foreground wait",
512            TICK.as_secs()
513        );
514    }
515
516    /// #1781: a client-side cancellation must free the waiting thread long
517    /// before the soft cap. The assertion is on *elapsed time*, not just on the
518    /// `Detached` shape — detaching at the cap returns the same variant, so the
519    /// shape alone would pass even with the check removed.
520    #[test]
521    #[cfg_attr(windows, ignore)]
522    fn cancelled_token_detaches_without_waiting_for_the_soft_cap() {
523        let token = tokio_util::sync::CancellationToken::new();
524        token.cancel();
525        let started = std::time::Instant::now();
526        let result = run_foreground_or_detach(
527            // Distinct from the progress test's `sleep 30`: identical commands
528            // coalesce onto one job (#1876), so a shared one would be cancelled
529            // under the other test's feet.
530            "sleep 31".to_string(),
531            ".".to_string(),
532            std::collections::HashMap::default(),
533            Some(60_000),
534            Duration::from_mins(1),
535            None,
536            Some(&token),
537        );
538        let elapsed = started.elapsed();
539        let ForegroundResult::Detached { job_id } = result else {
540            panic!("a cancelled request must detach instead of waiting it out");
541        };
542        cancel(&job_id);
543        assert!(
544            elapsed < Duration::from_secs(5),
545            "cancelled wait took {elapsed:?} against a one-minute cap — token not observed"
546        );
547    }
548
549    #[test]
550    #[cfg_attr(windows, ignore)]
551    fn background_job_runs_past_request_and_can_be_observed() {
552        let id = start(
553            "sleep 0.1; printf BG_JOB_OK".to_string(),
554            ".".to_string(),
555            std::collections::HashMap::default(),
556            Some(10_000),
557        );
558        assert!(matches!(status(&id), Some(JobState::Running { .. })));
559        for _ in 0..40 {
560            if let Some(JobState::Completed { output, exit_code }) = status(&id) {
561                assert_eq!(exit_code, 0);
562                assert!(output.contains("BG_JOB_OK"));
563                return;
564            }
565            std::thread::sleep(Duration::from_millis(25));
566        }
567        panic!("background job did not complete");
568    }
569
570    #[test]
571    #[cfg_attr(windows, ignore)]
572    fn cancelling_background_job_returns_cancelled_state() {
573        let id = start(
574            "sleep 5".to_string(),
575            ".".to_string(),
576            std::collections::HashMap::default(),
577            Some(10_000),
578        );
579        assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
580        for _ in 0..40 {
581            if let Some(JobState::Cancelled { output }) = status(&id) {
582                assert!(output.contains("[cancelled: command stopped on request]"));
583                return;
584            }
585            std::thread::sleep(Duration::from_millis(25));
586        }
587        panic!("background job was not cancelled");
588    }
589
590    /// #1217: a still-running job's `status` must surface the captured-so-far
591    /// output, not a bare "running" with no signal of progress.
592    #[test]
593    #[cfg_attr(windows, ignore)]
594    fn running_background_job_status_streams_partial_output() {
595        let id = start(
596            "printf EARLY_LINE; sleep 5".to_string(),
597            ".".to_string(),
598            std::collections::HashMap::default(),
599            Some(10_000),
600        );
601        let mut saw_partial = false;
602        for _ in 0..80 {
603            if let Some(JobState::Running { output }) = status(&id)
604                && output.contains("EARLY_LINE")
605            {
606                saw_partial = true;
607                break;
608            }
609            std::thread::sleep(Duration::from_millis(25));
610        }
611        cancel(&id);
612        assert!(
613            saw_partial,
614            "status never surfaced the running job's early output"
615        );
616    }
617
618    /// #1876: identical foreground calls coalesce onto one job. The first to
619    /// see it finish used to remove the shared entry, so every other caller
620    /// polled a missing id until the host timed out. Each must get the output.
621    #[test]
622    #[cfg_attr(windows, ignore)]
623    fn identical_concurrent_foreground_calls_all_observe_completion() {
624        const CALLERS: usize = 3;
625        let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
626        let handles: Vec<_> = (0..CALLERS)
627            .map(|_| {
628                let barrier = std::sync::Arc::clone(&barrier);
629                std::thread::spawn(move || {
630                    barrier.wait();
631                    run_foreground_or_detach(
632                        "sleep 0.2; printf GH1876_ALL_OK".to_string(),
633                        ".".to_string(),
634                        std::collections::HashMap::default(),
635                        Some(10_000),
636                        Duration::from_secs(10),
637                        None,
638                        None,
639                    )
640                })
641            })
642            .collect();
643        for handle in handles {
644            match handle.join().expect("foreground caller panicked") {
645                ForegroundResult::Finished { output, exit_code } => {
646                    assert_eq!(exit_code, 0);
647                    assert!(output.contains("GH1876_ALL_OK"), "got: {output}");
648                }
649                ForegroundResult::Detached { job_id } => {
650                    cancel(&job_id);
651                    panic!("a coalesced caller lost the shared job and detached");
652                }
653            }
654        }
655    }
656
657    /// #1876: a foreground call that joins an explicit background job must
658    /// not remove the entry the background caller still polls by id.
659    #[test]
660    #[cfg_attr(windows, ignore)]
661    fn foreground_join_keeps_a_background_job_pollable() {
662        let command = "sleep 0.2; printf GH1876_BG_OK".to_string();
663        let id = start(
664            command.clone(),
665            ".".to_string(),
666            std::collections::HashMap::default(),
667            Some(10_000),
668        );
669        let result = run_foreground_or_detach(
670            command,
671            ".".to_string(),
672            std::collections::HashMap::default(),
673            Some(10_000),
674            Duration::from_secs(10),
675            None,
676            None,
677        );
678        assert!(matches!(result, ForegroundResult::Finished { .. }));
679        match status(&id) {
680            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_BG_OK")),
681            other => panic!("background job vanished after a foreground join: {other:?}"),
682        }
683        super::remove_for_test(&id);
684    }
685
686    /// #1876: a call that arrives after the job finished but before its waiter
687    /// read the result must join that entry. Replacing it let the first
688    /// waiter's release delete the second caller's job.
689    #[test]
690    #[cfg_attr(windows, ignore)]
691    fn a_caller_joins_a_finished_entry_its_waiter_has_not_read() {
692        let launch = || {
693            super::start_inner(
694                "printf GH1876_WINDOW".to_string(),
695                ".".to_string(),
696                std::collections::HashMap::default(),
697                Some(10_000),
698                true,
699            )
700        };
701        let id = launch();
702        let deadline = std::time::Instant::now() + Duration::from_secs(10);
703        while !matches!(status(&id), Some(JobState::Completed { .. })) {
704            assert!(std::time::Instant::now() < deadline, "job never completed");
705            std::thread::sleep(Duration::from_millis(10));
706        }
707
708        assert_eq!(launch(), id);
709        super::release_foreground(&id, false);
710        match status(&id) {
711            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_WINDOW")),
712            other => panic!("the joined caller lost its result: {other:?}"),
713        }
714        super::release_foreground(&id, false);
715        assert!(status(&id).is_none(), "the last waiter removes the entry");
716    }
717
718    /// #1876: fast identical commands finish inside one poll interval, which
719    /// is where callers used to replace an unread entry.
720    #[test]
721    #[cfg_attr(windows, ignore)]
722    fn fast_identical_concurrent_foreground_calls_all_return() {
723        const CALLERS: usize = 8;
724        for _ in 0..5 {
725            let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
726            let handles: Vec<_> = (0..CALLERS)
727                .map(|_| {
728                    let barrier = std::sync::Arc::clone(&barrier);
729                    std::thread::spawn(move || {
730                        barrier.wait();
731                        run_foreground_or_detach(
732                            "printf GH1876_FAST".to_string(),
733                            ".".to_string(),
734                            std::collections::HashMap::default(),
735                            Some(10_000),
736                            Duration::from_secs(5),
737                            None,
738                            None,
739                        )
740                    })
741                })
742                .collect();
743            for handle in handles {
744                match handle.join().expect("foreground caller panicked") {
745                    ForegroundResult::Finished { output, .. } => {
746                        assert!(output.contains("GH1876_FAST"), "got: {output}");
747                    }
748                    ForegroundResult::Detached { job_id } => {
749                        cancel(&job_id);
750                        panic!("a fast identical caller lost its job and detached");
751                    }
752                }
753            }
754        }
755    }
756
757    #[test]
758    fn pruning_keeps_finished_jobs_that_a_waiter_has_not_read() {
759        let now = std::time::Instant::now();
760        let mut jobs = std::collections::HashMap::new();
761        jobs.insert(
762            "waited".to_string(),
763            super::Job {
764                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
765                state: JobState::Completed {
766                    output: "x".repeat(64),
767                    exit_code: 0,
768                },
769                finished_at: Some(
770                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
771                        .unwrap(),
772                ),
773                live: std::sync::Arc::new(std::sync::Mutex::new(String::new())),
774                foreground_waiters: 1,
775                background_owned: false,
776            },
777        );
778
779        super::prune_finished_jobs_with_limits(&mut jobs, now, 0, 0);
780
781        assert!(jobs.contains_key("waited"));
782    }
783}