Skip to main content

lean_ctx_server/server/
background_shell.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Explicit, in-process background jobs for `ctx_shell`.
3//!
4//! The MCP request may complete immediately, but the child keeps the exact
5//! timeout, allow-list, path-jail and process-group policy of foreground shell
6//! execution. Jobs intentionally live in the daemon: restarting it invalidates
7//! outstanding jobs rather than silently orphaning subprocesses.
8
9use std::collections::HashMap;
10use std::path::Path;
11use std::sync::{
12    Arc, LazyLock, Mutex,
13    atomic::{AtomicBool, AtomicU64, Ordering},
14    mpsc,
15};
16use std::time::{Duration, Instant};
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub enum JobState {
20    Running { output: String },
21    Completed { output: String, exit_code: i32 },
22    Cancelled { output: String },
23}
24
25const MAX_RETAINED_COMPLETED_JOBS: usize = 64;
26const MAX_RETAINED_COMPLETED_BYTES: usize = 16 * 1024 * 1024;
27const MAX_FOREGROUND_OUTPUT_RECEIVERS: usize = 64;
28const COMPLETED_JOB_TTL: Duration = Duration::from_mins(5);
29
30struct Job {
31    cancel: Arc<AtomicBool>,
32    state: JobState,
33    finished_at: Option<Instant>,
34    // Terminal text is storage-admitted only. Running jobs keep no output.
35    generation: u64,
36    actual_exit_code: i32,
37    completeness: lean_ctx::core::context_admission::OutputCompleteness,
38    output_withheld: bool,
39    // Q13: the call's fixed, content-free notice. Kept beside the retained
40    // text, never in it: storage admission, scrubbing and replacement do not
41    // touch it, and every delivery puts it in front once.
42    notice: Option<&'static str>,
43    /// The class the command's output is admitted with (pz21 §1.8).
44    class: lean_ctx::core::context_admission::origin::SourceClass,
45    // One-shot raw results go only to foreground receivers that are still alive;
46    // they are never included in JobState or a pollable snapshot.
47    foreground_senders: Vec<mpsc::SyncSender<Arc<crate::server::execute::ShellExecution>>>,
48    // #1876: identical launches coalesce onto one entry, so several foreground
49    // calls can wait on it at once. A detached/background owner keeps it pollable.
50    foreground_waiters: usize,
51    background_owned: bool,
52    telemetry_recorded: bool,
53}
54
55static JOBS: LazyLock<Mutex<HashMap<String, Job>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
56static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
57
58/// How often a foreground run reports progress to the MCP client (#1173).
59const TICK: Duration = Duration::from_secs(5);
60
61fn prune_finished_jobs(jobs: &mut HashMap<String, Job>, now: Instant) {
62    prune_finished_jobs_with_limits(
63        jobs,
64        now,
65        MAX_RETAINED_COMPLETED_JOBS,
66        MAX_RETAINED_COMPLETED_BYTES,
67    );
68}
69
70fn prune_finished_jobs_with_limits(
71    jobs: &mut HashMap<String, Job>,
72    now: Instant,
73    max_completed_jobs: usize,
74    max_completed_bytes: usize,
75) {
76    jobs.retain(|_, job| {
77        job.foreground_waiters > 0
78            || job
79                .finished_at
80                .is_none_or(|finished_at| now.duration_since(finished_at) < COMPLETED_JOB_TTL)
81    });
82
83    let mut completed: Vec<_> = jobs
84        .iter()
85        .filter(|(_, job)| job.foreground_waiters == 0)
86        .filter_map(|(id, job)| {
87            let finished_at = job.finished_at?;
88            let output_bytes = match &job.state {
89                JobState::Completed { output, .. } | JobState::Cancelled { output } => output.len(),
90                JobState::Running { .. } => 0,
91            };
92            Some((finished_at, id.clone(), output_bytes))
93        })
94        .collect();
95    completed.sort_unstable_by_key(|(finished_at, _, _)| *finished_at);
96
97    let mut retained_bytes = completed.iter().map(|(_, _, bytes)| bytes).sum::<usize>();
98    let mut retained_jobs = completed.len();
99    for (_, id, output_bytes) in completed {
100        if retained_jobs <= max_completed_jobs && retained_bytes <= max_completed_bytes {
101            break;
102        }
103        if retained_jobs == 1 {
104            break;
105        }
106        jobs.remove(&id);
107        retained_jobs -= 1;
108        retained_bytes = retained_bytes.saturating_sub(output_bytes);
109    }
110}
111
112pub fn start(
113    command: String,
114    cwd: String,
115    extra_env: std::collections::HashMap<String, String>,
116    timeout_ms: Option<u64>,
117) -> String {
118    start_inner(command, cwd, extra_env, timeout_ms, false)
119}
120
121fn start_inner(
122    command: String,
123    cwd: String,
124    extra_env: std::collections::HashMap<String, String>,
125    timeout_ms: Option<u64>,
126    foreground: bool,
127) -> String {
128    start_inner_with_sender(command, cwd, extra_env, timeout_ms, foreground, None)
129}
130
131fn start_inner_with_sender(
132    command: String,
133    cwd: String,
134    extra_env: std::collections::HashMap<String, String>,
135    timeout_ms: Option<u64>,
136    foreground: bool,
137    output_sender: Option<mpsc::SyncSender<Arc<crate::server::execute::ShellExecution>>>,
138) -> String {
139    // IDs are content-addressed so tool responses stay deterministic (#498).
140    // An identical in-flight launch coalesces onto the same job instead of
141    // creating duplicate expensive builds/tests.
142    let mut env_entries: Vec<_> = extra_env.iter().collect();
143    env_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
144    let env_key = env_entries
145        .into_iter()
146        .map(|(key, value)| format!("{key}={value}"))
147        .collect::<Vec<_>>()
148        .join("\0");
149    let material = format!(
150        "{command}\0{cwd}\0{}\0{env_key}",
151        timeout_ms.unwrap_or_default()
152    );
153    let id = format!(
154        "shell_{}",
155        &blake3::hash(material.as_bytes()).to_hex()[..16]
156    );
157    let cancel = Arc::new(AtomicBool::new(false));
158    let worker_cancel = Arc::clone(&cancel);
159    {
160        let mut jobs = JOBS
161            .lock()
162            .unwrap_or_else(std::sync::PoisonError::into_inner);
163        prune_finished_jobs(&mut jobs, Instant::now());
164        // A finished entry that a foreground waiter has not read yet is joined
165        // too (#1876): replacing it would hand that waiter's release to the new
166        // job, which then disappears under its own waiter.
167        if let Some(job) = jobs.get_mut(&id)
168            && (matches!(job.state, JobState::Running { .. }) || job.foreground_waiters > 0)
169        {
170            if foreground {
171                job.foreground_waiters += 1;
172                if matches!(job.state, JobState::Running { .. })
173                    && job.foreground_senders.len() < MAX_FOREGROUND_OUTPUT_RECEIVERS
174                    && let Some(sender) = output_sender
175                {
176                    job.foreground_senders.push(sender);
177                }
178            } else {
179                job.background_owned = true;
180            }
181            return id;
182        }
183        jobs.insert(
184            id.clone(),
185            Job {
186                cancel,
187                state: JobState::Running {
188                    output: String::new(),
189                },
190                finished_at: None,
191                generation: NEXT_GENERATION.fetch_add(1, Ordering::Relaxed),
192                actual_exit_code: 0,
193                completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
194                output_withheld: false,
195                notice: None,
196                class: lean_ctx::core::patterns::output_class(&command),
197                foreground_senders: output_sender.into_iter().collect(),
198                foreground_waiters: usize::from(foreground),
199                background_owned: !foreground,
200                telemetry_recorded: false,
201            },
202        );
203    }
204
205    let worker_id = id.clone();
206    let project_root = lean_ctx::core::policy::runtime::detached_project_root(Path::new(&cwd)).ok();
207    std::thread::spawn(move || {
208        let execution = crate::server::execute::execute_command_with_env_cancellable_captured(
209            &command,
210            &cwd,
211            &extra_env,
212            timeout_ms,
213            Some(&worker_cancel),
214            // #1113/#1173: bounded by output, not wall clock — a monitor loop
215            // emitting a line every 45s must survive. See `idle_keyed`.
216            true,
217        );
218        let store = lean_ctx::core::context_admission::stores::StoreAdmission::current();
219        let stored_output = project_root.as_deref().and_then(|root| {
220            let root = root.to_str()?;
221            lean_ctx::core::policy::runtime::with_project_source_view(root, || {
222                // Background output is project-policy filtered before it is
223                // retained. Preserve the existing audit of the original text
224                // at this boundary: later tool-pipeline auditing sees only the
225                // admitted text (or a content-free withheld marker).
226                let policy_outcome = lean_ctx::core::policy::runtime::active().map(|policy| {
227                    lean_ctx::core::policy::content::evaluate_text(&execution.output, &policy)
228                });
229                // #2164: a pipe still held by a process the command left
230                // running does not cost the job its output.
231                let stored =
232                    store.admit_background_output(&execution.output, execution.completeness);
233                if let Some(outcome) = policy_outcome
234                    && !outcome.audit.is_empty()
235                    && (outcome.blocked
236                        || outcome.text != execution.output
237                        || stored.as_deref() != Some(execution.output.as_str()))
238                {
239                    crate::server::policy_guard::audit_filter(
240                        "ctx_shell",
241                        &outcome.audit,
242                        outcome.blocked,
243                    );
244                }
245                stored
246            })
247            .ok()
248            .flatten()
249        });
250        let mut jobs = JOBS
251            .lock()
252            .unwrap_or_else(std::sync::PoisonError::into_inner);
253        let Some(job) = jobs.get_mut(&worker_id) else {
254            return;
255        };
256        // Check epoch while the job insertion lock is held, so a policy change
257        // while waiting for JOBS cannot repopulate terminal state.
258        let stored_output = stored_output.filter(|_| store.is_current());
259        let cancelled = worker_cancel.load(Ordering::Acquire);
260        let foreground_result = Arc::new(execution);
261        for sender in job.foreground_senders.drain(..) {
262            let _ = sender.send(Arc::clone(&foreground_result));
263        }
264        let output_withheld = stored_output.is_none();
265        let output = stored_output.unwrap_or_default();
266        let exit_code = foreground_result.exit_code;
267        job.actual_exit_code = exit_code;
268        job.completeness = foreground_result.completeness;
269        job.output_withheld = output_withheld;
270        job.notice = foreground_result.notice;
271        job.state = if cancelled {
272            JobState::Cancelled { output }
273        } else {
274            JobState::Completed { output, exit_code }
275        };
276        job.finished_at = Some(Instant::now());
277        // Only a background-owned job is counted here, so a failure nobody
278        // polls still reaches telemetry. A foreground run is classified once by
279        // the call pipeline, which knows that exit 1 with output (grep, diff,
280        // test) is not an error; counting it here as well filed every failing
281        // inline command twice, the second time as a LeanCTX-internal error.
282        if !cancelled && exit_code != 0 && job.background_owned {
283            let category = if exit_code == 124 {
284                lean_ctx::core::telemetry_v2::ErrorCategory::Timeout
285            } else {
286                lean_ctx::core::telemetry_v2::ErrorCategory::Command
287            };
288            if lean_ctx::core::telemetry_aggregate::record_error_category(category).is_ok() {
289                job.telemetry_recorded = true;
290            }
291        }
292        prune_finished_jobs(&mut jobs, Instant::now());
293    });
294    id
295}
296
297/// Outcome of a foreground run that is allowed to detach on a soft cap.
298pub enum ForegroundResult {
299    /// The command finished within the soft cap; output is returned inline.
300    /// Other coalesced foreground/background callers retain their result.
301    Finished { output: String, exit_code: i32 },
302    /// The command was still running at the soft cap and was left running as a
303    /// pollable background job (#1106).
304    Detached { job_id: String },
305}
306
307/// Legacy tuple-shaped foreground result for existing callers.
308pub fn run_foreground_or_detach(
309    command: String,
310    cwd: String,
311    extra_env: std::collections::HashMap<String, String>,
312    timeout_ms: Option<u64>,
313    soft_cap: Duration,
314    on_tick: Option<&dyn Fn(Duration)>,
315    cancel: Option<&tokio_util::sync::CancellationToken>,
316) -> ForegroundResult {
317    match run_foreground_or_detach_captured(
318        command, cwd, extra_env, timeout_ms, soft_cap, on_tick, cancel,
319    ) {
320        CapturedForegroundResult::Finished {
321            output,
322            exit_code,
323            notice,
324            ..
325        } => ForegroundResult::Finished {
326            // Nothing shortens the text on this path: the notice goes in
327            // front here.
328            output: crate::server::execute::with_notice(notice, output),
329            exit_code,
330        },
331        CapturedForegroundResult::Detached { job_id } => ForegroundResult::Detached { job_id },
332    }
333}
334
335/// Process output returned only while the original foreground call remains alive.
336pub(crate) enum CapturedForegroundResult {
337    Finished {
338        output: String,
339        exit_code: i32,
340        completeness: lean_ctx::core::context_admission::OutputCompleteness,
341        retained_withheld: bool,
342        /// Not part of `output`; see `ShellExecution::notice`.
343        notice: Option<&'static str>,
344    },
345    Detached {
346        job_id: String,
347    },
348}
349
350/// Run a managed job with a one-shot channel for live foreground delivery.
351/// Detached callers drop that receiver; later polls can see only stored text.
352pub(crate) fn run_foreground_or_detach_captured(
353    command: String,
354    cwd: String,
355    extra_env: std::collections::HashMap<String, String>,
356    timeout_ms: Option<u64>,
357    soft_cap: Duration,
358    on_tick: Option<&dyn Fn(Duration)>,
359    cancel: Option<&tokio_util::sync::CancellationToken>,
360) -> CapturedForegroundResult {
361    let (sender, receiver) = mpsc::sync_channel(1);
362    let id = start_inner_with_sender(command, cwd, extra_env, timeout_ms, true, Some(sender));
363    let started = Instant::now();
364    let deadline = started + soft_cap;
365    let mut next_tick = started + TICK;
366    loop {
367        if let Ok(execution) = receiver.try_recv() {
368            release_foreground(&id, false);
369            return CapturedForegroundResult::Finished {
370                output: execution.output.clone(),
371                exit_code: execution.exit_code,
372                completeness: execution.completeness,
373                retained_withheld: false,
374                notice: execution.notice,
375            };
376        }
377        if let Some(snapshot) = snapshot(&id) {
378            match snapshot.state {
379                JobState::Completed { output, exit_code } => {
380                    release_foreground(&id, false);
381                    return CapturedForegroundResult::Finished {
382                        output,
383                        exit_code,
384                        completeness: snapshot.completeness,
385                        retained_withheld: snapshot.output_withheld,
386                        notice: snapshot.notice,
387                    };
388                }
389                JobState::Cancelled { output } => {
390                    release_foreground(&id, false);
391                    return CapturedForegroundResult::Finished {
392                        output,
393                        exit_code: snapshot.actual_exit_code,
394                        completeness: snapshot.completeness,
395                        retained_withheld: snapshot.output_withheld,
396                        notice: snapshot.notice,
397                    };
398                }
399                JobState::Running { .. } => {}
400            }
401        }
402        if cancel.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
403            abandon_foreground(&id);
404            return CapturedForegroundResult::Detached { job_id: id };
405        }
406        let now = Instant::now();
407        if now >= deadline {
408            release_foreground(&id, true);
409            return CapturedForegroundResult::Detached { job_id: id };
410        }
411        if let Some(tick) = on_tick
412            && now >= next_tick
413        {
414            tick(started.elapsed());
415            next_tick = now + TICK;
416        }
417        std::thread::sleep(Duration::from_millis(50));
418    }
419}
420
421/// One foreground waiter is done with `id` (#1876). A detached waiter hands the
422/// id to its caller, so the entry becomes background-owned and stays pollable.
423/// Otherwise the entry is removed once no waiter and no background caller is
424/// left; a waiter that still polls it must not find it gone.
425fn release_foreground(id: &str, detached: bool) {
426    let mut jobs = JOBS
427        .lock()
428        .unwrap_or_else(std::sync::PoisonError::into_inner);
429    let Some(job) = jobs.get_mut(id) else {
430        return;
431    };
432    job.foreground_waiters = job.foreground_waiters.saturating_sub(1);
433    if detached {
434        job.background_owned = true;
435    } else if job.foreground_waiters == 0 && !job.background_owned {
436        jobs.remove(id);
437    }
438}
439
440/// #2279: the request behind a foreground wait was cancelled. Its reply never
441/// reaches the client, so the job id it would carry is unreachable: a job that
442/// nobody else waits on or owns is stopped (its worker kills the process
443/// group) instead of running on unobserved until its lifetime ends. A job
444/// another call joined (#1876) or detached on purpose keeps running for them.
445fn abandon_foreground(id: &str) {
446    let mut jobs = JOBS
447        .lock()
448        .unwrap_or_else(std::sync::PoisonError::into_inner);
449    let Some(job) = jobs.get_mut(id) else {
450        return;
451    };
452    job.foreground_waiters = job.foreground_waiters.saturating_sub(1);
453    if job.foreground_waiters > 0 || job.background_owned {
454        return;
455    }
456    if matches!(job.state, JobState::Running { .. }) {
457        job.cancel.store(true, Ordering::Release);
458        // The worker still records the terminal state; the entry is then
459        // pruned like any finished background job.
460        job.background_owned = true;
461    } else {
462        jobs.remove(id);
463    }
464}
465
466#[cfg(test)]
467pub(crate) fn remove_for_test(id: &str) {
468    JOBS.lock()
469        .unwrap_or_else(std::sync::PoisonError::into_inner)
470        .remove(id);
471}
472
473/// Jobs whose command is still running. An idle MCP server with one of these
474/// is not idle: it holds the child and the output the agent will poll for.
475pub fn running_count() -> usize {
476    JOBS.lock()
477        .unwrap_or_else(std::sync::PoisonError::into_inner)
478        .values()
479        .filter(|job| matches!(job.state, JobState::Running { .. }))
480        .count()
481}
482
483#[derive(Debug, Clone)]
484pub(crate) struct JobSnapshot {
485    pub(crate) state: JobState,
486    pub(crate) generation: u64,
487    pub(crate) completeness: lean_ctx::core::context_admission::OutputCompleteness,
488    pub(crate) output_withheld: bool,
489    pub(crate) actual_exit_code: i32,
490    /// The job's fixed notice, if it has one; not part of the state's text.
491    pub(crate) notice: Option<&'static str>,
492    /// The class the command's output is admitted with (pz21 §1.8).
493    pub(crate) class: lean_ctx::core::context_admission::origin::SourceClass,
494}
495
496/// A running job exposes state only; terminal text was storage-admitted before
497/// it entered the pollable job record.
498pub(crate) fn snapshot(id: &str) -> Option<JobSnapshot> {
499    let jobs = JOBS
500        .lock()
501        .unwrap_or_else(std::sync::PoisonError::into_inner);
502    let job = jobs.get(id)?;
503    Some(JobSnapshot {
504        state: job.state.clone(),
505        generation: job.generation,
506        completeness: job.completeness,
507        output_withheld: job.output_withheld,
508        actual_exit_code: job.actual_exit_code,
509        notice: job.notice,
510        class: job.class.clone(),
511    })
512}
513
514pub fn status(id: &str) -> Option<JobState> {
515    snapshot(id).map(|snapshot| snapshot.state)
516}
517
518/// Replace retained terminal text only if the caller still holds the exact
519/// generation and text it inspected. A policy change can therefore scrub a job
520/// without racing a reused content-addressed id or a newer poll.
521pub(crate) fn replace_retained_output_if_generation(
522    id: &str,
523    generation: u64,
524    expected: &str,
525    expected_epoch: u64,
526    replacement: Option<&str>,
527) -> bool {
528    let mut jobs = JOBS
529        .lock()
530        .unwrap_or_else(std::sync::PoisonError::into_inner);
531    let Some(job) = jobs.get_mut(id) else {
532        return false;
533    };
534    if job.generation != generation
535        || (replacement.is_some()
536            && lean_ctx::core::context_admission::stores::current_epoch() != expected_epoch)
537    {
538        return false;
539    }
540    let current = match &job.state {
541        JobState::Completed { output, .. } | JobState::Cancelled { output } => output,
542        JobState::Running { .. } => return false,
543    };
544    if current != expected {
545        return false;
546    }
547    match &mut job.state {
548        JobState::Completed { output, .. } | JobState::Cancelled { output } => {
549            output.clear();
550            if let Some(replacement) = replacement {
551                output.push_str(replacement);
552            }
553        }
554        JobState::Running { .. } => return false,
555    }
556    job.output_withheld = replacement.is_none();
557    true
558}
559
560/// Persist one aggregate for a terminal failed job, then mark that concrete
561/// retained job instance. A later execution may reuse the content-addressed ID,
562/// but replaces the `Job` and therefore starts with a fresh marker.
563pub fn record_error_telemetry_once(
564    id: &str,
565    category: lean_ctx::core::telemetry_v2::ErrorCategory,
566) -> Result<bool, String> {
567    let mut jobs = JOBS
568        .lock()
569        .unwrap_or_else(std::sync::PoisonError::into_inner);
570    let Some(job) = jobs.get_mut(id) else {
571        return Ok(false);
572    };
573    if job.telemetry_recorded
574        || !matches!(job.state, JobState::Completed { exit_code, .. } if exit_code != 0)
575    {
576        return Ok(false);
577    }
578    lean_ctx::core::telemetry_aggregate::record_error_category(category)?;
579    job.telemetry_recorded = true;
580    Ok(true)
581}
582
583pub(crate) fn cancel_snapshot(id: &str) -> Option<JobSnapshot> {
584    {
585        let mut jobs = JOBS
586            .lock()
587            .unwrap_or_else(std::sync::PoisonError::into_inner);
588        let job = jobs.get_mut(id)?;
589        if matches!(job.state, JobState::Running { .. }) {
590            job.cancel.store(true, Ordering::Release);
591        }
592    }
593    snapshot(id)
594}
595
596pub fn cancel(id: &str) -> Option<JobState> {
597    cancel_snapshot(id).map(|snapshot| snapshot.state)
598}
599
600#[cfg(test)]
601mod tests {
602    use super::{
603        ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
604    };
605    use std::time::Duration;
606
607    /// A finished job's text is storage-admitted, on the job's own thread,
608    /// under the process's gateway configuration and project policy, and is
609    /// dropped when that configuration changes meanwhile. A test that reads
610    /// the retained text holds both still: its own data directory (which
611    /// serializes every test that changes the environment) and no project
612    /// policy — environment first, policy second, as everywhere.
613    fn retained_text_held_still() -> (
614        lean_ctx::core::data_dir::IsolatedDataDir,
615        lean_ctx::core::policy::runtime::TestPolicyOverride,
616    ) {
617        let data = lean_ctx::core::data_dir::isolated_data_dir();
618        let community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
619        (data, community)
620    }
621
622    fn completed_job(exit_code: i32) -> super::Job {
623        super::Job {
624            cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
625            state: JobState::Completed {
626                output: "opaque output".into(),
627                exit_code,
628            },
629            finished_at: Some(std::time::Instant::now()),
630            generation: 0,
631            actual_exit_code: 0,
632            completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
633            output_withheld: false,
634            notice: None,
635            class: lean_ctx::core::context_admission::carrier::INSTANCE,
636            foreground_senders: Vec::new(),
637            foreground_waiters: 0,
638            background_owned: true,
639            telemetry_recorded: false,
640        }
641    }
642
643    #[test]
644    fn retained_output_replacement_checks_epoch_under_the_job_lock() {
645        let id = "shell_epoch_replacement_test";
646        let mut job = completed_job(0);
647        job.generation = 41;
648        super::JOBS
649            .lock()
650            .unwrap_or_else(std::sync::PoisonError::into_inner)
651            .insert(id.into(), job);
652        let epoch = lean_ctx::core::context_admission::stores::current_epoch();
653
654        assert!(
655            !super::replace_retained_output_if_generation(
656                id,
657                41,
658                "opaque output",
659                epoch.wrapping_add(1),
660                Some("stale output"),
661            ),
662            "an old policy snapshot cannot repopulate a terminal job"
663        );
664        assert!(matches!(
665            super::status(id),
666            Some(JobState::Completed { output, .. }) if output == "opaque output"
667        ));
668
669        assert!(
670            super::replace_retained_output_if_generation(
671                id,
672                41,
673                "opaque output",
674                epoch.wrapping_add(1),
675                None,
676            ),
677            "scrubbing remains allowed after an epoch change"
678        );
679        assert!(matches!(
680            super::status(id),
681            Some(JobState::Completed { output, .. }) if output.is_empty()
682        ));
683        super::remove_for_test(id);
684    }
685
686    #[test]
687    #[serial_test::serial]
688    fn failed_job_telemetry_is_once_per_execution_even_when_id_is_reused() {
689        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
690        let id = "shell_same_content";
691        super::JOBS
692            .lock()
693            .unwrap_or_else(std::sync::PoisonError::into_inner)
694            .insert(id.into(), completed_job(2));
695
696        assert!(
697            super::record_error_telemetry_once(
698                id,
699                lean_ctx::core::telemetry_v2::ErrorCategory::Internal
700            )
701            .expect("record first execution")
702        );
703        assert!(
704            !super::record_error_telemetry_once(
705                id,
706                lean_ctx::core::telemetry_v2::ErrorCategory::Internal
707            )
708            .expect("deduplicate repeated poll")
709        );
710
711        super::JOBS
712            .lock()
713            .unwrap_or_else(std::sync::PoisonError::into_inner)
714            .insert(id.into(), completed_job(2));
715        assert!(
716            super::record_error_telemetry_once(
717                id,
718                lean_ctx::core::telemetry_v2::ErrorCategory::Internal
719            )
720            .expect("record replacement execution")
721        );
722
723        let batch = lean_ctx::core::telemetry_aggregate::preview_daily_batch().expect("preview");
724        let count = batch
725            .events
726            .iter()
727            .find_map(|envelope| match &envelope.event {
728                lean_ctx::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
729                    if metrics.category
730                        == lean_ctx::core::telemetry_v2::ErrorCategory::Internal =>
731                {
732                    Some(metrics.count)
733                }
734                _ => None,
735            });
736        assert_eq!(count, Some(2));
737        super::remove_for_test(id);
738    }
739
740    fn queued_error_count(category: lean_ctx::core::telemetry_v2::ErrorCategory) -> Option<u64> {
741        // A preview fails fast while another test's send holds the state lock;
742        // that is transient, so wait it out instead of failing this test.
743        let mut attempt = 0;
744        let batch = loop {
745            match lean_ctx::core::telemetry_aggregate::preview_daily_batch() {
746                Ok(batch) => break batch,
747                Err(_) if attempt < 100 => {
748                    attempt += 1;
749                    std::thread::sleep(Duration::from_millis(20));
750                }
751                Err(error) => panic!("preview: {error}"),
752            }
753        };
754        batch
755            .events
756            .iter()
757            .find_map(|envelope| match &envelope.event {
758                lean_ctx::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
759                    if metrics.category == category =>
760                {
761                    Some(metrics.count)
762                }
763                _ => None,
764            })
765    }
766
767    /// A failing inline command is classified once, by the call pipeline; the
768    /// worker counts only background-owned jobs, and as a failed command, never
769    /// as a LeanCTX-internal error.
770    #[test]
771    #[serial_test::serial]
772    #[cfg_attr(windows, ignore)]
773    fn worker_counts_only_background_failures_and_as_commands() {
774        use lean_ctx::core::telemetry_v2::ErrorCategory;
775        // The daily error counters are process-global: any parallel test whose
776        // failing command or detached job lands while this one holds the
777        // isolated data dir is counted here too (CI saw 2 instead of 1). Run
778        // the exact scenario alone in a fresh test process so the counts are
779        // this worker's own, like the MCP cancellation regression does.
780        if std::env::var_os("LEAN_CTX_BACKGROUND_TELEMETRY_SUBPROCESS").is_none() {
781            let environment = tempfile::tempdir().unwrap();
782            let mut command = std::process::Command::new(std::env::current_exe().unwrap());
783            command
784                .args([
785                    "--exact",
786                    "server::background_shell::tests::worker_counts_only_background_failures_and_as_commands",
787                    "--nocapture",
788                    "--test-threads=1",
789                ])
790                .env("LEAN_CTX_BACKGROUND_TELEMETRY_SUBPROCESS", "1");
791            for name in [
792                "LEAN_CTX_DATA_DIR",
793                "LEAN_CTX_CONFIG_DIR",
794                "LEAN_CTX_STATE_DIR",
795                "LEAN_CTX_CACHE_DIR",
796            ] {
797                command.env(name, environment.path());
798            }
799            let output = command.output().unwrap();
800            let stdout = String::from_utf8_lossy(&output.stdout);
801            assert!(
802                output.status.success() && stdout.contains("1 passed"),
803                "{stdout}\n{}",
804                String::from_utf8_lossy(&output.stderr)
805            );
806            return;
807        }
808        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
809
810        let result = run_foreground_or_detach(
811            "exit 3".to_string(),
812            ".".to_string(),
813            std::collections::HashMap::default(),
814            Some(10_000),
815            Duration::from_secs(10),
816            None,
817            None,
818        );
819        assert!(matches!(
820            result,
821            ForegroundResult::Finished { exit_code: 3, .. }
822        ));
823        assert_eq!(queued_error_count(ErrorCategory::Command), None);
824        assert_eq!(queued_error_count(ErrorCategory::Internal), None);
825
826        let id = start(
827            "exit 4".to_string(),
828            ".".to_string(),
829            std::collections::HashMap::default(),
830            Some(10_000),
831        );
832        for _ in 0..200 {
833            if matches!(status(&id), Some(JobState::Completed { .. })) {
834                break;
835            }
836            std::thread::sleep(Duration::from_millis(25));
837        }
838        assert!(matches!(
839            status(&id),
840            Some(JobState::Completed { exit_code: 4, .. })
841        ));
842        assert_eq!(queued_error_count(ErrorCategory::Command), Some(1));
843        assert_eq!(queued_error_count(ErrorCategory::Internal), None);
844        super::remove_for_test(&id);
845    }
846
847    #[test]
848    fn completed_job_retention_is_bounded() {
849        let now = std::time::Instant::now();
850        let mut jobs = std::collections::HashMap::new();
851        for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
852            jobs.insert(
853                format!("job_{index}"),
854                super::Job {
855                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
856                    state: JobState::Completed {
857                        output: "x".repeat(1024),
858                        exit_code: 0,
859                    },
860                    finished_at: Some(
861                        now.checked_sub(Duration::from_secs((index + 1) as u64))
862                            .unwrap(),
863                    ),
864                    generation: 0,
865                    actual_exit_code: 0,
866                    completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
867                    output_withheld: false,
868                    notice: None,
869                    class: lean_ctx::core::context_admission::carrier::INSTANCE,
870                    foreground_senders: Vec::new(),
871                    foreground_waiters: 0,
872                    background_owned: true,
873                    telemetry_recorded: false,
874                },
875            );
876        }
877        jobs.insert(
878            "expired".to_string(),
879            super::Job {
880                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
881                state: JobState::Completed {
882                    output: "expired".to_string(),
883                    exit_code: 0,
884                },
885                finished_at: Some(
886                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
887                        .unwrap(),
888                ),
889                generation: 0,
890                actual_exit_code: 0,
891                completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
892                output_withheld: false,
893                notice: None,
894                class: lean_ctx::core::context_admission::carrier::INSTANCE,
895                foreground_senders: Vec::new(),
896                foreground_waiters: 0,
897                background_owned: true,
898                telemetry_recorded: false,
899            },
900        );
901
902        super::prune_finished_jobs(&mut jobs, now);
903
904        assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
905        assert!(!jobs.contains_key("expired"));
906        assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
907    }
908
909    #[test]
910    fn completed_job_output_bytes_are_bounded() {
911        let now = std::time::Instant::now();
912        let mut jobs = std::collections::HashMap::new();
913        for index in 0..3 {
914            jobs.insert(
915                format!("job_{index}"),
916                super::Job {
917                    cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
918                    state: JobState::Completed {
919                        output: "x".repeat(8),
920                        exit_code: 0,
921                    },
922                    finished_at: Some(
923                        now.checked_sub(Duration::from_secs((3 - index) as u64))
924                            .unwrap(),
925                    ),
926                    generation: 0,
927                    actual_exit_code: 0,
928                    completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
929                    output_withheld: false,
930                    notice: None,
931                    class: lean_ctx::core::context_admission::carrier::INSTANCE,
932                    foreground_senders: Vec::new(),
933                    foreground_waiters: 0,
934                    background_owned: true,
935                    telemetry_recorded: false,
936                },
937            );
938        }
939
940        super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
941
942        assert_eq!(jobs.len(), 2);
943        assert!(!jobs.contains_key("job_0"));
944    }
945
946    #[test]
947    #[cfg_attr(windows, ignore)]
948    fn foreground_run_finishing_within_cap_returns_inline() {
949        let (_data, _community) = retained_text_held_still();
950        let result = run_foreground_or_detach(
951            "printf FG_OK".to_string(),
952            ".".to_string(),
953            std::collections::HashMap::default(),
954            Some(10_000),
955            Duration::from_secs(10),
956            None,
957            None,
958        );
959        match result {
960            ForegroundResult::Finished { output, exit_code } => {
961                assert_eq!(exit_code, 0);
962                assert!(output.contains("FG_OK"), "got: {output}");
963            }
964            ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
965        }
966    }
967
968    #[test]
969    #[cfg_attr(windows, ignore)]
970    fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
971        let result = run_foreground_or_detach(
972            "sleep 5; printf SLOW_OK".to_string(),
973            ".".to_string(),
974            std::collections::HashMap::default(),
975            Some(10_000),
976            Duration::from_millis(100),
977            None,
978            None,
979        );
980        let ForegroundResult::Detached { job_id } = result else {
981            panic!("slow command should detach");
982        };
983        assert!(job_id.starts_with("shell_"));
984        // The returned id must resolve via status — the core #1106 guarantee.
985        assert!(status(&job_id).is_some());
986        cancel(&job_id);
987    }
988
989    /// #1173: a `timeout_ms` far beyond the soft cap must NOT keep the command
990    /// in the foreground. Raising the cap past the MCP host's call abort (~105–120s) is
991    /// what stranded results behind an unresolvable task id; the caller must
992    /// still get a real `shell_*` job id at the cap.
993    #[test]
994    #[cfg_attr(windows, ignore)]
995    fn large_timeout_ms_still_detaches_at_the_soft_cap() {
996        let result = run_foreground_or_detach(
997            "sleep 5; printf NEVER_INLINE".to_string(),
998            ".".to_string(),
999            std::collections::HashMap::default(),
1000            Some(600_000),
1001            Duration::from_millis(100),
1002            None,
1003            None,
1004        );
1005        let ForegroundResult::Detached { job_id } = result else {
1006            panic!("timeout_ms must not extend the foreground wait");
1007        };
1008        assert!(status(&job_id).is_some());
1009        cancel(&job_id);
1010    }
1011
1012    /// #1173: a foreground run reports progress while it waits, so a slow
1013    /// command is distinguishable from a hang. Deliberately slower than the
1014    /// other tests here — it has to outlive one real [`TICK`].
1015    #[test]
1016    #[cfg_attr(windows, ignore)]
1017    fn foreground_run_reports_progress_while_waiting() {
1018        let ticks = std::sync::atomic::AtomicUsize::new(0);
1019        let tick = |elapsed: Duration| {
1020            assert!(elapsed >= TICK, "tick must report real elapsed time");
1021            ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1022        };
1023        let result = run_foreground_or_detach(
1024            "sleep 30".to_string(),
1025            ".".to_string(),
1026            std::collections::HashMap::default(),
1027            Some(60_000),
1028            TICK + Duration::from_millis(500),
1029            Some(&tick),
1030            None,
1031        );
1032        let ForegroundResult::Detached { job_id } = result else {
1033            panic!("slow command should detach");
1034        };
1035        cancel(&job_id);
1036        assert!(
1037            ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
1038            "no progress reported during a {}s+ foreground wait",
1039            TICK.as_secs()
1040        );
1041    }
1042
1043    /// #1781: a client-side cancellation must free the waiting thread long
1044    /// before the soft cap. The assertion is on *elapsed time*, not just on the
1045    /// `Detached` shape — detaching at the cap returns the same variant, so the
1046    /// shape alone would pass even with the check removed.
1047    #[test]
1048    #[cfg_attr(windows, ignore)]
1049    fn cancelled_token_detaches_without_waiting_for_the_soft_cap() {
1050        let token = tokio_util::sync::CancellationToken::new();
1051        token.cancel();
1052        let started = std::time::Instant::now();
1053        let result = run_foreground_or_detach(
1054            // Distinct from the progress test's `sleep 30`: identical commands
1055            // coalesce onto one job (#1876), so a shared one would be cancelled
1056            // under the other test's feet.
1057            "sleep 31".to_string(),
1058            ".".to_string(),
1059            std::collections::HashMap::default(),
1060            Some(60_000),
1061            Duration::from_mins(1),
1062            None,
1063            Some(&token),
1064        );
1065        let elapsed = started.elapsed();
1066        let ForegroundResult::Detached { job_id } = result else {
1067            panic!("a cancelled request must detach instead of waiting it out");
1068        };
1069        cancel(&job_id);
1070        assert!(
1071            elapsed < Duration::from_secs(5),
1072            "cancelled wait took {elapsed:?} against a one-minute cap — token not observed"
1073        );
1074    }
1075
1076    /// #2279: a cancelled request's reply never reaches the client, so the
1077    /// job it would name is unreachable. A job nobody else waits on is
1078    /// stopped, and with it the whole process group: a grandchild the command
1079    /// put in the background is gone too, not left running until the lifetime.
1080    #[test]
1081    #[cfg(unix)]
1082    fn cancelled_request_stops_its_unshared_job_and_process_group() {
1083        let dir = tempfile::tempdir().unwrap();
1084        let pidfile = dir.path().join("grandchild.pid");
1085        let command = format!("sleep 37 & echo $! > '{}'; wait", pidfile.display());
1086        let token = tokio_util::sync::CancellationToken::new();
1087        let canceller = {
1088            let token = token.clone();
1089            let pidfile = pidfile.clone();
1090            std::thread::spawn(move || {
1091                let deadline = std::time::Instant::now() + Duration::from_secs(20);
1092                while std::time::Instant::now() < deadline {
1093                    if std::fs::read_to_string(&pidfile).is_ok_and(|p| !p.trim().is_empty()) {
1094                        break;
1095                    }
1096                    std::thread::sleep(Duration::from_millis(20));
1097                }
1098                token.cancel();
1099            })
1100        };
1101        let started = std::time::Instant::now();
1102        let result = run_foreground_or_detach(
1103            command,
1104            ".".to_string(),
1105            std::collections::HashMap::default(),
1106            Some(60_000),
1107            Duration::from_mins(1),
1108            None,
1109            Some(&token),
1110        );
1111        canceller.join().unwrap();
1112        let ForegroundResult::Detached { job_id } = result else {
1113            panic!("a cancelled request returns without the command's result");
1114        };
1115        let pid: i32 = std::fs::read_to_string(&pidfile)
1116            .expect("the command started its grandchild")
1117            .trim()
1118            .parse()
1119            .unwrap();
1120        let deadline = std::time::Instant::now() + Duration::from_secs(10);
1121        while matches!(status(&job_id), Some(JobState::Running { .. }))
1122            && std::time::Instant::now() < deadline
1123        {
1124            std::thread::sleep(Duration::from_millis(20));
1125        }
1126        assert!(
1127            matches!(status(&job_id), Some(JobState::Cancelled { .. })),
1128            "the abandoned job must be stopped, not left running: {:?}",
1129            status(&job_id)
1130        );
1131        // The killed grandchild may linger as a zombie until init reaps it;
1132        // either way it no longer runs. Wait for it to vanish.
1133        let alive = |pid: i32| {
1134            // SAFETY: signal 0 only checks that the process exists.
1135            unsafe { libc::kill(pid, 0) == 0 }
1136        };
1137        while alive(pid) && std::time::Instant::now() < deadline {
1138            std::thread::sleep(Duration::from_millis(20));
1139        }
1140        assert!(
1141            !alive(pid),
1142            "the grandchild {pid} outlived its cancelled call"
1143        );
1144        assert!(
1145            started.elapsed() < Duration::from_secs(30),
1146            "cancellation took {:?}",
1147            started.elapsed()
1148        );
1149    }
1150
1151    /// #2279 / #1876: a job another caller owns keeps running when one of its
1152    /// waiters' requests is cancelled.
1153    #[test]
1154    #[cfg_attr(windows, ignore)]
1155    fn cancelled_request_leaves_a_shared_job_running() {
1156        let command = "sleep 38".to_string();
1157        let id = start(
1158            command.clone(),
1159            ".".to_string(),
1160            std::collections::HashMap::default(),
1161            Some(60_000),
1162        );
1163        let token = tokio_util::sync::CancellationToken::new();
1164        token.cancel();
1165        let result = run_foreground_or_detach(
1166            command,
1167            ".".to_string(),
1168            std::collections::HashMap::default(),
1169            Some(60_000),
1170            Duration::from_mins(1),
1171            None,
1172            Some(&token),
1173        );
1174        let ForegroundResult::Detached { job_id } = result else {
1175            panic!("a cancelled request detaches");
1176        };
1177        assert_eq!(job_id, id, "identical launches coalesce onto one job");
1178        std::thread::sleep(Duration::from_millis(300));
1179        let still = status(&id);
1180        cancel(&id);
1181        assert!(
1182            matches!(still, Some(JobState::Running { .. })),
1183            "the background owner's job must keep running: {still:?}"
1184        );
1185    }
1186
1187    #[test]
1188    #[cfg_attr(windows, ignore)]
1189    fn background_job_runs_past_request_and_can_be_observed() {
1190        let (_data, _community) = retained_text_held_still();
1191        let id = start(
1192            "sleep 0.1; printf BG_JOB_OK".to_string(),
1193            ".".to_string(),
1194            std::collections::HashMap::default(),
1195            Some(10_000),
1196        );
1197        assert!(matches!(status(&id), Some(JobState::Running { .. })));
1198        for _ in 0..40 {
1199            if let Some(JobState::Completed { output, exit_code }) = status(&id) {
1200                assert_eq!(exit_code, 0);
1201                assert!(output.contains("BG_JOB_OK"), "got: {output}");
1202                return;
1203            }
1204            std::thread::sleep(Duration::from_millis(25));
1205        }
1206        panic!("background job did not complete");
1207    }
1208
1209    #[test]
1210    #[cfg_attr(windows, ignore)]
1211    fn cancelling_background_job_returns_cancelled_state() {
1212        let id = start(
1213            "sleep 5".to_string(),
1214            ".".to_string(),
1215            std::collections::HashMap::default(),
1216            Some(10_000),
1217        );
1218        assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
1219        for _ in 0..40 {
1220            if let Some(JobState::Cancelled { output }) = status(&id) {
1221                assert!(
1222                    !output.contains("[cancelled: command stopped on request]"),
1223                    "cancellation lifecycle belongs to the structured state, not retained output"
1224                );
1225                return;
1226            }
1227            std::thread::sleep(Duration::from_millis(25));
1228        }
1229        panic!("background job was not cancelled");
1230    }
1231
1232    /// Running jobs must never retain or expose raw output; only terminal
1233    /// StoreAdmission-approved text can appear in a later poll.
1234    #[test]
1235    #[cfg_attr(windows, ignore)]
1236    fn running_background_job_status_never_exposes_live_output() {
1237        let id = start(
1238            "printf EARLY_LINE; sleep 3".to_string(),
1239            ".".to_string(),
1240            std::collections::HashMap::default(),
1241            Some(10_000),
1242        );
1243        let mut saw_running = false;
1244        for _ in 0..20 {
1245            if let Some(JobState::Running { output }) = status(&id) {
1246                saw_running = true;
1247                assert!(output.is_empty(), "running state retained: {output:?}");
1248                break;
1249            }
1250            std::thread::sleep(Duration::from_millis(10));
1251        }
1252        cancel(&id);
1253        assert!(
1254            saw_running,
1255            "job completed before running state was observed"
1256        );
1257    }
1258
1259    /// #1876: identical foreground calls coalesce onto one job. The first to
1260    /// see it finish used to remove the shared entry, so every other caller
1261    /// polled a missing id until the host timed out. Each must get the output.
1262    #[test]
1263    #[cfg_attr(windows, ignore)]
1264    fn identical_concurrent_foreground_calls_all_observe_completion() {
1265        let (_data, _community) = retained_text_held_still();
1266        const CALLERS: usize = 3;
1267        let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
1268        let handles: Vec<_> = (0..CALLERS)
1269            .map(|_| {
1270                let barrier = std::sync::Arc::clone(&barrier);
1271                std::thread::spawn(move || {
1272                    barrier.wait();
1273                    run_foreground_or_detach(
1274                        "sleep 0.2; printf GH1876_ALL_OK".to_string(),
1275                        ".".to_string(),
1276                        std::collections::HashMap::default(),
1277                        Some(10_000),
1278                        Duration::from_secs(10),
1279                        None,
1280                        None,
1281                    )
1282                })
1283            })
1284            .collect();
1285        for handle in handles {
1286            match handle.join().expect("foreground caller panicked") {
1287                ForegroundResult::Finished { output, exit_code } => {
1288                    assert_eq!(exit_code, 0);
1289                    assert!(output.contains("GH1876_ALL_OK"), "got: {output}");
1290                }
1291                ForegroundResult::Detached { job_id } => {
1292                    cancel(&job_id);
1293                    panic!("a coalesced caller lost the shared job and detached");
1294                }
1295            }
1296        }
1297    }
1298
1299    /// #1876: a foreground call that joins an explicit background job must
1300    /// not remove the entry the background caller still polls by id.
1301    #[test]
1302    #[cfg_attr(windows, ignore)]
1303    fn foreground_join_keeps_a_background_job_pollable() {
1304        let (_data, _community) = retained_text_held_still();
1305        let command = "sleep 0.2; printf GH1876_BG_OK".to_string();
1306        let id = start(
1307            command.clone(),
1308            ".".to_string(),
1309            std::collections::HashMap::default(),
1310            Some(10_000),
1311        );
1312        let result = run_foreground_or_detach(
1313            command,
1314            ".".to_string(),
1315            std::collections::HashMap::default(),
1316            Some(10_000),
1317            Duration::from_secs(10),
1318            None,
1319            None,
1320        );
1321        assert!(matches!(result, ForegroundResult::Finished { .. }));
1322        match status(&id) {
1323            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_BG_OK")),
1324            other => panic!("background job vanished after a foreground join: {other:?}"),
1325        }
1326        super::remove_for_test(&id);
1327    }
1328
1329    /// #1876: a call that arrives after the job finished but before its waiter
1330    /// read the result must join that entry. Replacing it let the first
1331    /// waiter's release delete the second caller's job.
1332    #[test]
1333    #[cfg_attr(windows, ignore)]
1334    fn a_caller_joins_a_finished_entry_its_waiter_has_not_read() {
1335        // The retained text is storage-admitted under the process's gateway
1336        // configuration and dropped when that configuration changes while the
1337        // job finishes (`StoreAdmission::is_current`). This test reads the
1338        // retained text, so it holds the configuration still: its own data
1339        // directory (which serializes every test that changes one) and no
1340        // project policy.
1341        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1342        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
1343        let launch = || {
1344            super::start_inner(
1345                "printf GH1876_WINDOW".to_string(),
1346                ".".to_string(),
1347                std::collections::HashMap::default(),
1348                Some(10_000),
1349                true,
1350            )
1351        };
1352        let id = launch();
1353        let deadline = std::time::Instant::now() + Duration::from_secs(10);
1354        while !matches!(status(&id), Some(JobState::Completed { .. })) {
1355            assert!(std::time::Instant::now() < deadline, "job never completed");
1356            std::thread::sleep(Duration::from_millis(10));
1357        }
1358
1359        assert_eq!(launch(), id);
1360        super::release_foreground(&id, false);
1361        match status(&id) {
1362            Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_WINDOW")),
1363            other => panic!("the joined caller lost its result: {other:?}"),
1364        }
1365        super::release_foreground(&id, false);
1366        assert!(status(&id).is_none(), "the last waiter removes the entry");
1367    }
1368
1369    /// #1876: fast identical commands finish inside one poll interval, which
1370    /// is where callers used to replace an unread entry.
1371    #[test]
1372    #[cfg_attr(windows, ignore)]
1373    fn fast_identical_concurrent_foreground_calls_all_return() {
1374        let (_data, _community) = retained_text_held_still();
1375        const CALLERS: usize = 8;
1376        for _ in 0..5 {
1377            let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
1378            let handles: Vec<_> = (0..CALLERS)
1379                .map(|_| {
1380                    let barrier = std::sync::Arc::clone(&barrier);
1381                    std::thread::spawn(move || {
1382                        barrier.wait();
1383                        run_foreground_or_detach(
1384                            "printf GH1876_FAST".to_string(),
1385                            ".".to_string(),
1386                            std::collections::HashMap::default(),
1387                            Some(10_000),
1388                            Duration::from_secs(5),
1389                            None,
1390                            None,
1391                        )
1392                    })
1393                })
1394                .collect();
1395            for handle in handles {
1396                match handle.join().expect("foreground caller panicked") {
1397                    ForegroundResult::Finished { output, .. } => {
1398                        assert!(output.contains("GH1876_FAST"), "got: {output}");
1399                    }
1400                    ForegroundResult::Detached { job_id } => {
1401                        cancel(&job_id);
1402                        panic!("a fast identical caller lost its job and detached");
1403                    }
1404                }
1405            }
1406        }
1407    }
1408
1409    #[test]
1410    fn pruning_keeps_finished_jobs_that_a_waiter_has_not_read() {
1411        let now = std::time::Instant::now();
1412        let mut jobs = std::collections::HashMap::new();
1413        jobs.insert(
1414            "waited".to_string(),
1415            super::Job {
1416                cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1417                state: JobState::Completed {
1418                    output: "x".repeat(64),
1419                    exit_code: 0,
1420                },
1421                finished_at: Some(
1422                    now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
1423                        .unwrap(),
1424                ),
1425                generation: 0,
1426                actual_exit_code: 0,
1427                completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
1428                output_withheld: false,
1429                notice: None,
1430                class: lean_ctx::core::context_admission::carrier::INSTANCE,
1431                foreground_senders: Vec::new(),
1432                foreground_waiters: 1,
1433                background_owned: false,
1434                telemetry_recorded: false,
1435            },
1436        );
1437
1438        super::prune_finished_jobs_with_limits(&mut jobs, now, 0, 0);
1439
1440        assert!(jobs.contains_key("waited"));
1441    }
1442}