1use std::collections::HashMap;
9use std::path::Path;
10use std::sync::{
11 Arc, LazyLock, Mutex,
12 atomic::{AtomicBool, AtomicU64, Ordering},
13 mpsc,
14};
15use std::time::{Duration, Instant};
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum JobState {
19 Running { output: String },
20 Completed { output: String, exit_code: i32 },
21 Cancelled { output: String },
22}
23
24const MAX_RETAINED_COMPLETED_JOBS: usize = 64;
25const MAX_RETAINED_COMPLETED_BYTES: usize = 16 * 1024 * 1024;
26const MAX_FOREGROUND_OUTPUT_RECEIVERS: usize = 64;
27const COMPLETED_JOB_TTL: Duration = Duration::from_mins(5);
28
29struct Job {
30 cancel: Arc<AtomicBool>,
31 state: JobState,
32 finished_at: Option<Instant>,
33 generation: u64,
35 actual_exit_code: i32,
36 completeness: crate::core::context_admission::OutputCompleteness,
37 output_withheld: bool,
38 notice: Option<&'static str>,
42 foreground_senders: Vec<mpsc::SyncSender<Arc<crate::server::execute::ShellExecution>>>,
45 foreground_waiters: usize,
48 background_owned: bool,
49 telemetry_recorded: bool,
50}
51
52static JOBS: LazyLock<Mutex<HashMap<String, Job>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
53static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
54
55const TICK: Duration = Duration::from_secs(5);
57
58fn prune_finished_jobs(jobs: &mut HashMap<String, Job>, now: Instant) {
59 prune_finished_jobs_with_limits(
60 jobs,
61 now,
62 MAX_RETAINED_COMPLETED_JOBS,
63 MAX_RETAINED_COMPLETED_BYTES,
64 );
65}
66
67fn prune_finished_jobs_with_limits(
68 jobs: &mut HashMap<String, Job>,
69 now: Instant,
70 max_completed_jobs: usize,
71 max_completed_bytes: usize,
72) {
73 jobs.retain(|_, job| {
74 job.foreground_waiters > 0
75 || job
76 .finished_at
77 .is_none_or(|finished_at| now.duration_since(finished_at) < COMPLETED_JOB_TTL)
78 });
79
80 let mut completed: Vec<_> = jobs
81 .iter()
82 .filter(|(_, job)| job.foreground_waiters == 0)
83 .filter_map(|(id, job)| {
84 let finished_at = job.finished_at?;
85 let output_bytes = match &job.state {
86 JobState::Completed { output, .. } | JobState::Cancelled { output } => output.len(),
87 JobState::Running { .. } => 0,
88 };
89 Some((finished_at, id.clone(), output_bytes))
90 })
91 .collect();
92 completed.sort_unstable_by_key(|(finished_at, _, _)| *finished_at);
93
94 let mut retained_bytes = completed.iter().map(|(_, _, bytes)| bytes).sum::<usize>();
95 let mut retained_jobs = completed.len();
96 for (_, id, output_bytes) in completed {
97 if retained_jobs <= max_completed_jobs && retained_bytes <= max_completed_bytes {
98 break;
99 }
100 if retained_jobs == 1 {
101 break;
102 }
103 jobs.remove(&id);
104 retained_jobs -= 1;
105 retained_bytes = retained_bytes.saturating_sub(output_bytes);
106 }
107}
108
109pub fn start(
110 command: String,
111 cwd: String,
112 extra_env: std::collections::HashMap<String, String>,
113 timeout_ms: Option<u64>,
114) -> String {
115 start_inner(command, cwd, extra_env, timeout_ms, false)
116}
117
118fn start_inner(
119 command: String,
120 cwd: String,
121 extra_env: std::collections::HashMap<String, String>,
122 timeout_ms: Option<u64>,
123 foreground: bool,
124) -> String {
125 start_inner_with_sender(command, cwd, extra_env, timeout_ms, foreground, None)
126}
127
128fn start_inner_with_sender(
129 command: String,
130 cwd: String,
131 extra_env: std::collections::HashMap<String, String>,
132 timeout_ms: Option<u64>,
133 foreground: bool,
134 output_sender: Option<mpsc::SyncSender<Arc<crate::server::execute::ShellExecution>>>,
135) -> String {
136 let mut env_entries: Vec<_> = extra_env.iter().collect();
140 env_entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
141 let env_key = env_entries
142 .into_iter()
143 .map(|(key, value)| format!("{key}={value}"))
144 .collect::<Vec<_>>()
145 .join("\0");
146 let material = format!(
147 "{command}\0{cwd}\0{}\0{env_key}",
148 timeout_ms.unwrap_or_default()
149 );
150 let id = format!(
151 "shell_{}",
152 &blake3::hash(material.as_bytes()).to_hex()[..16]
153 );
154 let cancel = Arc::new(AtomicBool::new(false));
155 let worker_cancel = Arc::clone(&cancel);
156 {
157 let mut jobs = JOBS
158 .lock()
159 .unwrap_or_else(std::sync::PoisonError::into_inner);
160 prune_finished_jobs(&mut jobs, Instant::now());
161 if let Some(job) = jobs.get_mut(&id)
165 && (matches!(job.state, JobState::Running { .. }) || job.foreground_waiters > 0)
166 {
167 if foreground {
168 job.foreground_waiters += 1;
169 if matches!(job.state, JobState::Running { .. })
170 && job.foreground_senders.len() < MAX_FOREGROUND_OUTPUT_RECEIVERS
171 && let Some(sender) = output_sender
172 {
173 job.foreground_senders.push(sender);
174 }
175 } else {
176 job.background_owned = true;
177 }
178 return id;
179 }
180 jobs.insert(
181 id.clone(),
182 Job {
183 cancel,
184 state: JobState::Running {
185 output: String::new(),
186 },
187 finished_at: None,
188 generation: NEXT_GENERATION.fetch_add(1, Ordering::Relaxed),
189 actual_exit_code: 0,
190 completeness: crate::core::context_admission::OutputCompleteness::complete(),
191 output_withheld: false,
192 notice: None,
193 foreground_senders: output_sender.into_iter().collect(),
194 foreground_waiters: usize::from(foreground),
195 background_owned: !foreground,
196 telemetry_recorded: false,
197 },
198 );
199 }
200
201 let worker_id = id.clone();
202 let project_root = crate::core::policy::runtime::detached_project_root(Path::new(&cwd)).ok();
203 std::thread::spawn(move || {
204 let execution = crate::server::execute::execute_command_with_env_cancellable_captured(
205 &command,
206 &cwd,
207 &extra_env,
208 timeout_ms,
209 Some(&worker_cancel),
210 true,
213 );
214 let store = crate::core::context_admission::stores::StoreAdmission::current();
215 let stored_output = project_root.as_deref().and_then(|root| {
216 let root = root.to_str()?;
217 crate::core::policy::runtime::with_project_source_view(root, || {
218 let policy_outcome = crate::core::policy::runtime::active().map(|policy| {
223 crate::core::policy::content::evaluate_text(&execution.output, &policy)
224 });
225 let stored = store.admit_shell_output(&execution.output, execution.completeness);
226 if let Some(outcome) = policy_outcome
227 && !outcome.audit.is_empty()
228 && (outcome.blocked
229 || outcome.text != execution.output
230 || stored.as_deref() != Some(execution.output.as_str()))
231 {
232 crate::server::policy_guard::audit_filter(
233 "ctx_shell",
234 &outcome.audit,
235 outcome.blocked,
236 );
237 }
238 stored
239 })
240 .ok()
241 .flatten()
242 });
243 let mut jobs = JOBS
244 .lock()
245 .unwrap_or_else(std::sync::PoisonError::into_inner);
246 let Some(job) = jobs.get_mut(&worker_id) else {
247 return;
248 };
249 let stored_output = stored_output.filter(|_| store.is_current());
252 let cancelled = worker_cancel.load(Ordering::Acquire);
253 let foreground_result = Arc::new(execution);
254 for sender in job.foreground_senders.drain(..) {
255 let _ = sender.send(Arc::clone(&foreground_result));
256 }
257 let output_withheld = stored_output.is_none();
258 let output = stored_output.unwrap_or_default();
259 let exit_code = foreground_result.exit_code;
260 job.actual_exit_code = exit_code;
261 job.completeness = foreground_result.completeness;
262 job.output_withheld = output_withheld;
263 job.notice = foreground_result.notice;
264 job.state = if cancelled {
265 JobState::Cancelled { output }
266 } else {
267 JobState::Completed { output, exit_code }
268 };
269 job.finished_at = Some(Instant::now());
270 if !cancelled && exit_code != 0 && job.background_owned {
276 let category = if exit_code == 124 {
277 crate::core::telemetry_v2::ErrorCategory::Timeout
278 } else {
279 crate::core::telemetry_v2::ErrorCategory::Command
280 };
281 if crate::core::telemetry_aggregate::record_error_category(category).is_ok() {
282 job.telemetry_recorded = true;
283 }
284 }
285 prune_finished_jobs(&mut jobs, Instant::now());
286 });
287 id
288}
289
290pub enum ForegroundResult {
292 Finished { output: String, exit_code: i32 },
295 Detached { job_id: String },
298}
299
300pub fn run_foreground_or_detach(
302 command: String,
303 cwd: String,
304 extra_env: std::collections::HashMap<String, String>,
305 timeout_ms: Option<u64>,
306 soft_cap: Duration,
307 on_tick: Option<&dyn Fn(Duration)>,
308 cancel: Option<&tokio_util::sync::CancellationToken>,
309) -> ForegroundResult {
310 match run_foreground_or_detach_captured(
311 command, cwd, extra_env, timeout_ms, soft_cap, on_tick, cancel,
312 ) {
313 CapturedForegroundResult::Finished {
314 output,
315 exit_code,
316 notice,
317 ..
318 } => ForegroundResult::Finished {
319 output: crate::server::execute::with_notice(notice, output),
322 exit_code,
323 },
324 CapturedForegroundResult::Detached { job_id } => ForegroundResult::Detached { job_id },
325 }
326}
327
328pub(crate) enum CapturedForegroundResult {
330 Finished {
331 output: String,
332 exit_code: i32,
333 completeness: crate::core::context_admission::OutputCompleteness,
334 retained_withheld: bool,
335 notice: Option<&'static str>,
337 },
338 Detached {
339 job_id: String,
340 },
341}
342
343pub(crate) fn run_foreground_or_detach_captured(
346 command: String,
347 cwd: String,
348 extra_env: std::collections::HashMap<String, String>,
349 timeout_ms: Option<u64>,
350 soft_cap: Duration,
351 on_tick: Option<&dyn Fn(Duration)>,
352 cancel: Option<&tokio_util::sync::CancellationToken>,
353) -> CapturedForegroundResult {
354 let (sender, receiver) = mpsc::sync_channel(1);
355 let id = start_inner_with_sender(command, cwd, extra_env, timeout_ms, true, Some(sender));
356 let started = Instant::now();
357 let deadline = started + soft_cap;
358 let mut next_tick = started + TICK;
359 loop {
360 if let Ok(execution) = receiver.try_recv() {
361 release_foreground(&id, false);
362 return CapturedForegroundResult::Finished {
363 output: execution.output.clone(),
364 exit_code: execution.exit_code,
365 completeness: execution.completeness,
366 retained_withheld: false,
367 notice: execution.notice,
368 };
369 }
370 if let Some(snapshot) = snapshot(&id) {
371 match snapshot.state {
372 JobState::Completed { output, exit_code } => {
373 release_foreground(&id, false);
374 return CapturedForegroundResult::Finished {
375 output,
376 exit_code,
377 completeness: snapshot.completeness,
378 retained_withheld: snapshot.output_withheld,
379 notice: snapshot.notice,
380 };
381 }
382 JobState::Cancelled { output } => {
383 release_foreground(&id, false);
384 return CapturedForegroundResult::Finished {
385 output,
386 exit_code: snapshot.actual_exit_code,
387 completeness: snapshot.completeness,
388 retained_withheld: snapshot.output_withheld,
389 notice: snapshot.notice,
390 };
391 }
392 JobState::Running { .. } => {}
393 }
394 }
395 if cancel.is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
396 release_foreground(&id, true);
397 return CapturedForegroundResult::Detached { job_id: id };
398 }
399 let now = Instant::now();
400 if now >= deadline {
401 release_foreground(&id, true);
402 return CapturedForegroundResult::Detached { job_id: id };
403 }
404 if let Some(tick) = on_tick
405 && now >= next_tick
406 {
407 tick(started.elapsed());
408 next_tick = now + TICK;
409 }
410 std::thread::sleep(Duration::from_millis(50));
411 }
412}
413
414fn release_foreground(id: &str, detached: bool) {
419 let mut jobs = JOBS
420 .lock()
421 .unwrap_or_else(std::sync::PoisonError::into_inner);
422 let Some(job) = jobs.get_mut(id) else {
423 return;
424 };
425 job.foreground_waiters = job.foreground_waiters.saturating_sub(1);
426 if detached {
427 job.background_owned = true;
428 } else if job.foreground_waiters == 0 && !job.background_owned {
429 jobs.remove(id);
430 }
431}
432
433#[cfg(test)]
434pub(crate) fn remove_for_test(id: &str) {
435 JOBS.lock()
436 .unwrap_or_else(std::sync::PoisonError::into_inner)
437 .remove(id);
438}
439
440pub fn running_count() -> usize {
443 JOBS.lock()
444 .unwrap_or_else(std::sync::PoisonError::into_inner)
445 .values()
446 .filter(|job| matches!(job.state, JobState::Running { .. }))
447 .count()
448}
449
450#[derive(Debug, Clone)]
451pub(crate) struct JobSnapshot {
452 pub(crate) state: JobState,
453 pub(crate) generation: u64,
454 pub(crate) completeness: crate::core::context_admission::OutputCompleteness,
455 pub(crate) output_withheld: bool,
456 pub(crate) actual_exit_code: i32,
457 pub(crate) notice: Option<&'static str>,
459}
460
461pub(crate) fn snapshot(id: &str) -> Option<JobSnapshot> {
464 let jobs = JOBS
465 .lock()
466 .unwrap_or_else(std::sync::PoisonError::into_inner);
467 let job = jobs.get(id)?;
468 Some(JobSnapshot {
469 state: job.state.clone(),
470 generation: job.generation,
471 completeness: job.completeness,
472 output_withheld: job.output_withheld,
473 actual_exit_code: job.actual_exit_code,
474 notice: job.notice,
475 })
476}
477
478pub fn status(id: &str) -> Option<JobState> {
479 snapshot(id).map(|snapshot| snapshot.state)
480}
481
482pub(crate) fn replace_retained_output_if_generation(
486 id: &str,
487 generation: u64,
488 expected: &str,
489 expected_epoch: u64,
490 replacement: Option<&str>,
491) -> bool {
492 let mut jobs = JOBS
493 .lock()
494 .unwrap_or_else(std::sync::PoisonError::into_inner);
495 let Some(job) = jobs.get_mut(id) else {
496 return false;
497 };
498 if job.generation != generation
499 || (replacement.is_some()
500 && crate::core::context_admission::stores::current_epoch() != expected_epoch)
501 {
502 return false;
503 }
504 let current = match &job.state {
505 JobState::Completed { output, .. } | JobState::Cancelled { output } => output,
506 JobState::Running { .. } => return false,
507 };
508 if current != expected {
509 return false;
510 }
511 match &mut job.state {
512 JobState::Completed { output, .. } | JobState::Cancelled { output } => {
513 output.clear();
514 if let Some(replacement) = replacement {
515 output.push_str(replacement);
516 }
517 }
518 JobState::Running { .. } => return false,
519 }
520 job.output_withheld = replacement.is_none();
521 true
522}
523
524pub fn record_error_telemetry_once(
528 id: &str,
529 category: crate::core::telemetry_v2::ErrorCategory,
530) -> Result<bool, String> {
531 let mut jobs = JOBS
532 .lock()
533 .unwrap_or_else(std::sync::PoisonError::into_inner);
534 let Some(job) = jobs.get_mut(id) else {
535 return Ok(false);
536 };
537 if job.telemetry_recorded
538 || !matches!(job.state, JobState::Completed { exit_code, .. } if exit_code != 0)
539 {
540 return Ok(false);
541 }
542 crate::core::telemetry_aggregate::record_error_category(category)?;
543 job.telemetry_recorded = true;
544 Ok(true)
545}
546
547pub(crate) fn cancel_snapshot(id: &str) -> Option<JobSnapshot> {
548 {
549 let mut jobs = JOBS
550 .lock()
551 .unwrap_or_else(std::sync::PoisonError::into_inner);
552 let job = jobs.get_mut(id)?;
553 if matches!(job.state, JobState::Running { .. }) {
554 job.cancel.store(true, Ordering::Release);
555 }
556 }
557 snapshot(id)
558}
559
560pub fn cancel(id: &str) -> Option<JobState> {
561 cancel_snapshot(id).map(|snapshot| snapshot.state)
562}
563
564#[cfg(test)]
565mod tests {
566 use super::{
567 ForegroundResult, JobState, TICK, cancel, run_foreground_or_detach, start, status,
568 };
569 use std::time::Duration;
570
571 fn retained_text_held_still() -> (
578 crate::core::data_dir::IsolatedDataDir,
579 crate::core::policy::runtime::TestPolicyOverride,
580 ) {
581 let data = crate::core::data_dir::isolated_data_dir();
582 let community = crate::core::policy::runtime::TestPolicyOverride::set(None);
583 (data, community)
584 }
585
586 fn completed_job(exit_code: i32) -> super::Job {
587 super::Job {
588 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
589 state: JobState::Completed {
590 output: "opaque output".into(),
591 exit_code,
592 },
593 finished_at: Some(std::time::Instant::now()),
594 generation: 0,
595 actual_exit_code: 0,
596 completeness: crate::core::context_admission::OutputCompleteness::complete(),
597 output_withheld: false,
598 notice: None,
599 foreground_senders: Vec::new(),
600 foreground_waiters: 0,
601 background_owned: true,
602 telemetry_recorded: false,
603 }
604 }
605
606 #[test]
607 fn retained_output_replacement_checks_epoch_under_the_job_lock() {
608 let id = "shell_epoch_replacement_test";
609 let mut job = completed_job(0);
610 job.generation = 41;
611 super::JOBS
612 .lock()
613 .unwrap_or_else(std::sync::PoisonError::into_inner)
614 .insert(id.into(), job);
615 let epoch = crate::core::context_admission::stores::current_epoch();
616
617 assert!(
618 !super::replace_retained_output_if_generation(
619 id,
620 41,
621 "opaque output",
622 epoch.wrapping_add(1),
623 Some("stale output"),
624 ),
625 "an old policy snapshot cannot repopulate a terminal job"
626 );
627 assert!(matches!(
628 super::status(id),
629 Some(JobState::Completed { output, .. }) if output == "opaque output"
630 ));
631
632 assert!(
633 super::replace_retained_output_if_generation(
634 id,
635 41,
636 "opaque output",
637 epoch.wrapping_add(1),
638 None,
639 ),
640 "scrubbing remains allowed after an epoch change"
641 );
642 assert!(matches!(
643 super::status(id),
644 Some(JobState::Completed { output, .. }) if output.is_empty()
645 ));
646 super::remove_for_test(id);
647 }
648
649 #[test]
650 #[serial_test::serial]
651 fn failed_job_telemetry_is_once_per_execution_even_when_id_is_reused() {
652 let _iso = crate::core::data_dir::isolated_data_dir();
653 let id = "shell_same_content";
654 super::JOBS
655 .lock()
656 .unwrap_or_else(std::sync::PoisonError::into_inner)
657 .insert(id.into(), completed_job(2));
658
659 assert!(
660 super::record_error_telemetry_once(
661 id,
662 crate::core::telemetry_v2::ErrorCategory::Internal
663 )
664 .expect("record first execution")
665 );
666 assert!(
667 !super::record_error_telemetry_once(
668 id,
669 crate::core::telemetry_v2::ErrorCategory::Internal
670 )
671 .expect("deduplicate repeated poll")
672 );
673
674 super::JOBS
675 .lock()
676 .unwrap_or_else(std::sync::PoisonError::into_inner)
677 .insert(id.into(), completed_job(2));
678 assert!(
679 super::record_error_telemetry_once(
680 id,
681 crate::core::telemetry_v2::ErrorCategory::Internal
682 )
683 .expect("record replacement execution")
684 );
685
686 let batch = crate::core::telemetry_aggregate::preview_daily_batch().expect("preview");
687 let count = batch
688 .events
689 .iter()
690 .find_map(|envelope| match &envelope.event {
691 crate::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
692 if metrics.category == crate::core::telemetry_v2::ErrorCategory::Internal =>
693 {
694 Some(metrics.count)
695 }
696 _ => None,
697 });
698 assert_eq!(count, Some(2));
699 super::remove_for_test(id);
700 }
701
702 fn queued_error_count(category: crate::core::telemetry_v2::ErrorCategory) -> Option<u64> {
703 let mut attempt = 0;
706 let batch = loop {
707 match crate::core::telemetry_aggregate::preview_daily_batch() {
708 Ok(batch) => break batch,
709 Err(_) if attempt < 100 => {
710 attempt += 1;
711 std::thread::sleep(Duration::from_millis(20));
712 }
713 Err(error) => panic!("preview: {error}"),
714 }
715 };
716 batch
717 .events
718 .iter()
719 .find_map(|envelope| match &envelope.event {
720 crate::core::telemetry_v2::TelemetryEventV2::ErrorCategoryAggregate(metrics)
721 if metrics.category == category =>
722 {
723 Some(metrics.count)
724 }
725 _ => None,
726 })
727 }
728
729 #[test]
733 #[serial_test::serial]
734 #[cfg_attr(windows, ignore)]
735 fn worker_counts_only_background_failures_and_as_commands() {
736 use crate::core::telemetry_v2::ErrorCategory;
737 if std::env::var_os("LEAN_CTX_BACKGROUND_TELEMETRY_SUBPROCESS").is_none() {
743 let environment = tempfile::tempdir().unwrap();
744 let mut command = std::process::Command::new(std::env::current_exe().unwrap());
745 command
746 .args([
747 "--exact",
748 "server::background_shell::tests::worker_counts_only_background_failures_and_as_commands",
749 "--nocapture",
750 "--test-threads=1",
751 ])
752 .env("LEAN_CTX_BACKGROUND_TELEMETRY_SUBPROCESS", "1");
753 for name in [
754 "LEAN_CTX_DATA_DIR",
755 "LEAN_CTX_CONFIG_DIR",
756 "LEAN_CTX_STATE_DIR",
757 "LEAN_CTX_CACHE_DIR",
758 ] {
759 command.env(name, environment.path());
760 }
761 let output = command.output().unwrap();
762 let stdout = String::from_utf8_lossy(&output.stdout);
763 assert!(
764 output.status.success() && stdout.contains("1 passed"),
765 "{stdout}\n{}",
766 String::from_utf8_lossy(&output.stderr)
767 );
768 return;
769 }
770 let _iso = crate::core::data_dir::isolated_data_dir();
771
772 let result = run_foreground_or_detach(
773 "exit 3".to_string(),
774 ".".to_string(),
775 std::collections::HashMap::default(),
776 Some(10_000),
777 Duration::from_secs(10),
778 None,
779 None,
780 );
781 assert!(matches!(
782 result,
783 ForegroundResult::Finished { exit_code: 3, .. }
784 ));
785 assert_eq!(queued_error_count(ErrorCategory::Command), None);
786 assert_eq!(queued_error_count(ErrorCategory::Internal), None);
787
788 let id = start(
789 "exit 4".to_string(),
790 ".".to_string(),
791 std::collections::HashMap::default(),
792 Some(10_000),
793 );
794 for _ in 0..200 {
795 if matches!(status(&id), Some(JobState::Completed { .. })) {
796 break;
797 }
798 std::thread::sleep(Duration::from_millis(25));
799 }
800 assert!(matches!(
801 status(&id),
802 Some(JobState::Completed { exit_code: 4, .. })
803 ));
804 assert_eq!(queued_error_count(ErrorCategory::Command), Some(1));
805 assert_eq!(queued_error_count(ErrorCategory::Internal), None);
806 super::remove_for_test(&id);
807 }
808
809 #[test]
810 fn completed_job_retention_is_bounded() {
811 let now = std::time::Instant::now();
812 let mut jobs = std::collections::HashMap::new();
813 for index in 0..=super::MAX_RETAINED_COMPLETED_JOBS {
814 jobs.insert(
815 format!("job_{index}"),
816 super::Job {
817 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
818 state: JobState::Completed {
819 output: "x".repeat(1024),
820 exit_code: 0,
821 },
822 finished_at: Some(
823 now.checked_sub(Duration::from_secs((index + 1) as u64))
824 .unwrap(),
825 ),
826 generation: 0,
827 actual_exit_code: 0,
828 completeness: crate::core::context_admission::OutputCompleteness::complete(),
829 output_withheld: false,
830 notice: None,
831 foreground_senders: Vec::new(),
832 foreground_waiters: 0,
833 background_owned: true,
834 telemetry_recorded: false,
835 },
836 );
837 }
838 jobs.insert(
839 "expired".to_string(),
840 super::Job {
841 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
842 state: JobState::Completed {
843 output: "expired".to_string(),
844 exit_code: 0,
845 },
846 finished_at: Some(
847 now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
848 .unwrap(),
849 ),
850 generation: 0,
851 actual_exit_code: 0,
852 completeness: crate::core::context_admission::OutputCompleteness::complete(),
853 output_withheld: false,
854 notice: None,
855 foreground_senders: Vec::new(),
856 foreground_waiters: 0,
857 background_owned: true,
858 telemetry_recorded: false,
859 },
860 );
861
862 super::prune_finished_jobs(&mut jobs, now);
863
864 assert_eq!(jobs.len(), super::MAX_RETAINED_COMPLETED_JOBS);
865 assert!(!jobs.contains_key("expired"));
866 assert!(!jobs.contains_key(&format!("job_{}", super::MAX_RETAINED_COMPLETED_JOBS)));
867 }
868
869 #[test]
870 fn completed_job_output_bytes_are_bounded() {
871 let now = std::time::Instant::now();
872 let mut jobs = std::collections::HashMap::new();
873 for index in 0..3 {
874 jobs.insert(
875 format!("job_{index}"),
876 super::Job {
877 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
878 state: JobState::Completed {
879 output: "x".repeat(8),
880 exit_code: 0,
881 },
882 finished_at: Some(
883 now.checked_sub(Duration::from_secs((3 - index) as u64))
884 .unwrap(),
885 ),
886 generation: 0,
887 actual_exit_code: 0,
888 completeness: crate::core::context_admission::OutputCompleteness::complete(),
889 output_withheld: false,
890 notice: None,
891 foreground_senders: Vec::new(),
892 foreground_waiters: 0,
893 background_owned: true,
894 telemetry_recorded: false,
895 },
896 );
897 }
898
899 super::prune_finished_jobs_with_limits(&mut jobs, now, 10, 16);
900
901 assert_eq!(jobs.len(), 2);
902 assert!(!jobs.contains_key("job_0"));
903 }
904
905 #[test]
906 #[cfg_attr(windows, ignore)]
907 fn foreground_run_finishing_within_cap_returns_inline() {
908 let (_data, _community) = retained_text_held_still();
909 let result = run_foreground_or_detach(
910 "printf FG_OK".to_string(),
911 ".".to_string(),
912 std::collections::HashMap::default(),
913 Some(10_000),
914 Duration::from_secs(10),
915 None,
916 None,
917 );
918 match result {
919 ForegroundResult::Finished { output, exit_code } => {
920 assert_eq!(exit_code, 0);
921 assert!(output.contains("FG_OK"), "got: {output}");
922 }
923 ForegroundResult::Detached { .. } => panic!("fast command should not detach"),
924 }
925 }
926
927 #[test]
928 #[cfg_attr(windows, ignore)]
929 fn foreground_run_exceeding_cap_detaches_to_pollable_job() {
930 let result = run_foreground_or_detach(
931 "sleep 5; printf SLOW_OK".to_string(),
932 ".".to_string(),
933 std::collections::HashMap::default(),
934 Some(10_000),
935 Duration::from_millis(100),
936 None,
937 None,
938 );
939 let ForegroundResult::Detached { job_id } = result else {
940 panic!("slow command should detach");
941 };
942 assert!(job_id.starts_with("shell_"));
943 assert!(status(&job_id).is_some());
945 cancel(&job_id);
946 }
947
948 #[test]
953 #[cfg_attr(windows, ignore)]
954 fn large_timeout_ms_still_detaches_at_the_soft_cap() {
955 let result = run_foreground_or_detach(
956 "sleep 5; printf NEVER_INLINE".to_string(),
957 ".".to_string(),
958 std::collections::HashMap::default(),
959 Some(600_000),
960 Duration::from_millis(100),
961 None,
962 None,
963 );
964 let ForegroundResult::Detached { job_id } = result else {
965 panic!("timeout_ms must not extend the foreground wait");
966 };
967 assert!(status(&job_id).is_some());
968 cancel(&job_id);
969 }
970
971 #[test]
975 #[cfg_attr(windows, ignore)]
976 fn foreground_run_reports_progress_while_waiting() {
977 let ticks = std::sync::atomic::AtomicUsize::new(0);
978 let tick = |elapsed: Duration| {
979 assert!(elapsed >= TICK, "tick must report real elapsed time");
980 ticks.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
981 };
982 let result = run_foreground_or_detach(
983 "sleep 30".to_string(),
984 ".".to_string(),
985 std::collections::HashMap::default(),
986 Some(60_000),
987 TICK + Duration::from_millis(500),
988 Some(&tick),
989 None,
990 );
991 let ForegroundResult::Detached { job_id } = result else {
992 panic!("slow command should detach");
993 };
994 cancel(&job_id);
995 assert!(
996 ticks.load(std::sync::atomic::Ordering::Relaxed) >= 1,
997 "no progress reported during a {}s+ foreground wait",
998 TICK.as_secs()
999 );
1000 }
1001
1002 #[test]
1007 #[cfg_attr(windows, ignore)]
1008 fn cancelled_token_detaches_without_waiting_for_the_soft_cap() {
1009 let token = tokio_util::sync::CancellationToken::new();
1010 token.cancel();
1011 let started = std::time::Instant::now();
1012 let result = run_foreground_or_detach(
1013 "sleep 31".to_string(),
1017 ".".to_string(),
1018 std::collections::HashMap::default(),
1019 Some(60_000),
1020 Duration::from_mins(1),
1021 None,
1022 Some(&token),
1023 );
1024 let elapsed = started.elapsed();
1025 let ForegroundResult::Detached { job_id } = result else {
1026 panic!("a cancelled request must detach instead of waiting it out");
1027 };
1028 cancel(&job_id);
1029 assert!(
1030 elapsed < Duration::from_secs(5),
1031 "cancelled wait took {elapsed:?} against a one-minute cap — token not observed"
1032 );
1033 }
1034
1035 #[test]
1036 #[cfg_attr(windows, ignore)]
1037 fn background_job_runs_past_request_and_can_be_observed() {
1038 let (_data, _community) = retained_text_held_still();
1039 let id = start(
1040 "sleep 0.1; printf BG_JOB_OK".to_string(),
1041 ".".to_string(),
1042 std::collections::HashMap::default(),
1043 Some(10_000),
1044 );
1045 assert!(matches!(status(&id), Some(JobState::Running { .. })));
1046 for _ in 0..40 {
1047 if let Some(JobState::Completed { output, exit_code }) = status(&id) {
1048 assert_eq!(exit_code, 0);
1049 assert!(output.contains("BG_JOB_OK"), "got: {output}");
1050 return;
1051 }
1052 std::thread::sleep(Duration::from_millis(25));
1053 }
1054 panic!("background job did not complete");
1055 }
1056
1057 #[test]
1058 #[cfg_attr(windows, ignore)]
1059 fn cancelling_background_job_returns_cancelled_state() {
1060 let id = start(
1061 "sleep 5".to_string(),
1062 ".".to_string(),
1063 std::collections::HashMap::default(),
1064 Some(10_000),
1065 );
1066 assert!(matches!(cancel(&id), Some(JobState::Running { .. })));
1067 for _ in 0..40 {
1068 if let Some(JobState::Cancelled { output }) = status(&id) {
1069 assert!(
1070 !output.contains("[cancelled: command stopped on request]"),
1071 "cancellation lifecycle belongs to the structured state, not retained output"
1072 );
1073 return;
1074 }
1075 std::thread::sleep(Duration::from_millis(25));
1076 }
1077 panic!("background job was not cancelled");
1078 }
1079
1080 #[test]
1083 #[cfg_attr(windows, ignore)]
1084 fn running_background_job_status_never_exposes_live_output() {
1085 let id = start(
1086 "printf EARLY_LINE; sleep 3".to_string(),
1087 ".".to_string(),
1088 std::collections::HashMap::default(),
1089 Some(10_000),
1090 );
1091 let mut saw_running = false;
1092 for _ in 0..20 {
1093 if let Some(JobState::Running { output }) = status(&id) {
1094 saw_running = true;
1095 assert!(output.is_empty(), "running state retained: {output:?}");
1096 break;
1097 }
1098 std::thread::sleep(Duration::from_millis(10));
1099 }
1100 cancel(&id);
1101 assert!(
1102 saw_running,
1103 "job completed before running state was observed"
1104 );
1105 }
1106
1107 #[test]
1111 #[cfg_attr(windows, ignore)]
1112 fn identical_concurrent_foreground_calls_all_observe_completion() {
1113 let (_data, _community) = retained_text_held_still();
1114 const CALLERS: usize = 3;
1115 let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
1116 let handles: Vec<_> = (0..CALLERS)
1117 .map(|_| {
1118 let barrier = std::sync::Arc::clone(&barrier);
1119 std::thread::spawn(move || {
1120 barrier.wait();
1121 run_foreground_or_detach(
1122 "sleep 0.2; printf GH1876_ALL_OK".to_string(),
1123 ".".to_string(),
1124 std::collections::HashMap::default(),
1125 Some(10_000),
1126 Duration::from_secs(10),
1127 None,
1128 None,
1129 )
1130 })
1131 })
1132 .collect();
1133 for handle in handles {
1134 match handle.join().expect("foreground caller panicked") {
1135 ForegroundResult::Finished { output, exit_code } => {
1136 assert_eq!(exit_code, 0);
1137 assert!(output.contains("GH1876_ALL_OK"), "got: {output}");
1138 }
1139 ForegroundResult::Detached { job_id } => {
1140 cancel(&job_id);
1141 panic!("a coalesced caller lost the shared job and detached");
1142 }
1143 }
1144 }
1145 }
1146
1147 #[test]
1150 #[cfg_attr(windows, ignore)]
1151 fn foreground_join_keeps_a_background_job_pollable() {
1152 let (_data, _community) = retained_text_held_still();
1153 let command = "sleep 0.2; printf GH1876_BG_OK".to_string();
1154 let id = start(
1155 command.clone(),
1156 ".".to_string(),
1157 std::collections::HashMap::default(),
1158 Some(10_000),
1159 );
1160 let result = run_foreground_or_detach(
1161 command,
1162 ".".to_string(),
1163 std::collections::HashMap::default(),
1164 Some(10_000),
1165 Duration::from_secs(10),
1166 None,
1167 None,
1168 );
1169 assert!(matches!(result, ForegroundResult::Finished { .. }));
1170 match status(&id) {
1171 Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_BG_OK")),
1172 other => panic!("background job vanished after a foreground join: {other:?}"),
1173 }
1174 super::remove_for_test(&id);
1175 }
1176
1177 #[test]
1181 #[cfg_attr(windows, ignore)]
1182 fn a_caller_joins_a_finished_entry_its_waiter_has_not_read() {
1183 let _data = crate::core::data_dir::isolated_data_dir();
1190 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
1191 let launch = || {
1192 super::start_inner(
1193 "printf GH1876_WINDOW".to_string(),
1194 ".".to_string(),
1195 std::collections::HashMap::default(),
1196 Some(10_000),
1197 true,
1198 )
1199 };
1200 let id = launch();
1201 let deadline = std::time::Instant::now() + Duration::from_secs(10);
1202 while !matches!(status(&id), Some(JobState::Completed { .. })) {
1203 assert!(std::time::Instant::now() < deadline, "job never completed");
1204 std::thread::sleep(Duration::from_millis(10));
1205 }
1206
1207 assert_eq!(launch(), id);
1208 super::release_foreground(&id, false);
1209 match status(&id) {
1210 Some(JobState::Completed { output, .. }) => assert!(output.contains("GH1876_WINDOW")),
1211 other => panic!("the joined caller lost its result: {other:?}"),
1212 }
1213 super::release_foreground(&id, false);
1214 assert!(status(&id).is_none(), "the last waiter removes the entry");
1215 }
1216
1217 #[test]
1220 #[cfg_attr(windows, ignore)]
1221 fn fast_identical_concurrent_foreground_calls_all_return() {
1222 let (_data, _community) = retained_text_held_still();
1223 const CALLERS: usize = 8;
1224 for _ in 0..5 {
1225 let barrier = std::sync::Arc::new(std::sync::Barrier::new(CALLERS));
1226 let handles: Vec<_> = (0..CALLERS)
1227 .map(|_| {
1228 let barrier = std::sync::Arc::clone(&barrier);
1229 std::thread::spawn(move || {
1230 barrier.wait();
1231 run_foreground_or_detach(
1232 "printf GH1876_FAST".to_string(),
1233 ".".to_string(),
1234 std::collections::HashMap::default(),
1235 Some(10_000),
1236 Duration::from_secs(5),
1237 None,
1238 None,
1239 )
1240 })
1241 })
1242 .collect();
1243 for handle in handles {
1244 match handle.join().expect("foreground caller panicked") {
1245 ForegroundResult::Finished { output, .. } => {
1246 assert!(output.contains("GH1876_FAST"), "got: {output}");
1247 }
1248 ForegroundResult::Detached { job_id } => {
1249 cancel(&job_id);
1250 panic!("a fast identical caller lost its job and detached");
1251 }
1252 }
1253 }
1254 }
1255 }
1256
1257 #[test]
1258 fn pruning_keeps_finished_jobs_that_a_waiter_has_not_read() {
1259 let now = std::time::Instant::now();
1260 let mut jobs = std::collections::HashMap::new();
1261 jobs.insert(
1262 "waited".to_string(),
1263 super::Job {
1264 cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
1265 state: JobState::Completed {
1266 output: "x".repeat(64),
1267 exit_code: 0,
1268 },
1269 finished_at: Some(
1270 now.checked_sub(super::COMPLETED_JOB_TTL + Duration::from_secs(1))
1271 .unwrap(),
1272 ),
1273 generation: 0,
1274 actual_exit_code: 0,
1275 completeness: crate::core::context_admission::OutputCompleteness::complete(),
1276 output_withheld: false,
1277 notice: None,
1278 foreground_senders: Vec::new(),
1279 foreground_waiters: 1,
1280 background_owned: false,
1281 telemetry_recorded: false,
1282 },
1283 );
1284
1285 super::prune_finished_jobs_with_limits(&mut jobs, now, 0, 0);
1286
1287 assert!(jobs.contains_key("waited"));
1288 }
1289}