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