Skip to main content

agentmux_srv_core/backend/
background_task_sweep.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Ends the `db_background_tasks` rows that nothing is left to end
5//! (`docs/specs/SPEC_BACKGROUND_TASK_STRUCTURED_FEED_AND_SWARM_OWNERSHIP_2026_09_27.md` §5, the liveness sweep;
6//! `docs/retro/retro-agent-pane-progress-flicker-and-orphaned-background-tasks-2026-09-30.md` §5, fixes 4 and 5).
7//!
8//! A row ends from the CLI's own task feed (`background_task_feed`) or from the renderer's `<task-notification>`.
9//! Neither speaks when the CLI dies mid-task, or drops a task without ending it from a feed that no longer holds a
10//! record of it (a row older than this srv). Two cases remain, and a pass over the still-`running` rows settles both:
11//!
12//! - A row with a pid whose process is gone. The pid is checked against the row's start, so a pid the OS has since
13//!   given to another program does not keep it alive (`pid_alive_since`). A task that really still runs keeps its pid,
14//!   so a long `task dev` stays.
15//! - A row with no pid that nothing has seen for [`ORPHAN_AFTER_MS`]. It can't be checked; it only has the CLI's word,
16//!   and the word stopped. The dock reads such a row as unknown after two hours; this ends it after a day.
17//!
18//! Both end as `stopped` and only while still `running` (`background_task_end_if_running`), so a real outcome that
19//! arrives during the pass stands. Pids here are the host's: a container pane's pid, from its own pid namespace, is
20//! filed apart (`container_tool_chunk`) and checked inside its container (`background_task_container_sweep`).
21
22use std::collections::BTreeSet;
23use std::sync::Arc;
24use std::time::Duration;
25
26use super::background_task_container_sweep::{sweep as container_sweep, ContainerProbe};
27use super::background_task_feed::publish_background_task_updated;
28use super::mps::Broker;
29use super::reactive::registry::pid_alive_since;
30use super::storage::background_tasks::{BackgroundTask, BackgroundTaskStatus};
31use super::storage::store::Store;
32
33/// How long after srv starts the first pass runs: rows left by the last run are cleared early, with the rest of the
34/// start-up work out of the way.
35const FIRST_AFTER: Duration = Duration::from_secs(30);
36/// Between passes. A dead task's row reading running for a few more minutes costs nothing.
37const EVERY: Duration = Duration::from_secs(5 * 60);
38/// A `running` row with no pid is ended when it was last seen this long ago.
39pub const ORPHAN_AFTER_MS: i64 = 24 * 60 * 60 * 1000;
40
41/// When `task`, still `running`, ended as far as anyone can tell, or `None` if it may still be running.
42/// `alive(pid, started_at_ms)` is whether that process, started before the row, is still there.
43fn ended_at(task: &BackgroundTask, now_ms: i64, alive: &impl Fn(u32, u64) -> bool) -> Option<i64> {
44    match task.pid {
45        Some(pid) => {
46            // A pid that doesn't fit, or is not one, can't be looked up: leave the row to the other paths.
47            let pid = u32::try_from(pid).ok().filter(|p| *p > 0)?;
48            (!alive(pid, u64::try_from(task.started_at_ms).unwrap_or(0))).then_some(now_ms)
49        }
50        None => (now_ms.saturating_sub(task.last_seen_ms) > ORPHAN_AFTER_MS).then_some(task.last_seen_ms),
51    }
52}
53
54/// One pass: end every `running` row that [`ended_at`] says is over. Returns the blocks whose rows changed.
55fn sweep(store: &Store, now_ms: i64, alive: &impl Fn(u32, u64) -> bool) -> BTreeSet<String> {
56    let mut changed = BTreeSet::new();
57    let running = match store.background_task_list_running() {
58        Ok(rows) => rows,
59        Err(e) => {
60            tracing::warn!(target: "background_tasks", error = %e, "liveness sweep: could not list the running tasks");
61            return changed;
62        }
63    };
64    for task in running {
65        let Some(at) = ended_at(&task, now_ms, alive) else { continue };
66        match store.background_task_end_if_running(&task.id, BackgroundTaskStatus::Stopped, at) {
67            Ok(true) => {
68                tracing::info!(target: "background_tasks", block_id = %task.block_id, node_id = %task.id, pid = ?task.pid,
69                    "liveness sweep: a background task nothing reports on any more is stopped");
70                changed.insert(task.block_id);
71            }
72            Ok(false) => {}
73            Err(e) => tracing::warn!(target: "background_tasks", node_id = %task.id, error = %e, "liveness sweep: could not end a task"),
74        }
75    }
76    changed
77}
78
79/// How long a container's report of a call's process id and description is kept: far longer than a task that
80/// is still worth checking, short enough that the table does not grow with every Bash call.
81const CONTAINER_REPORT_KEPT_MS: i64 = 7 * 24 * 60 * 60 * 1000;
82
83/// Starts the sweep: a first pass soon after srv starts, then every [`EVERY`]. `containers` checks a container
84/// pane's rows inside its container (`background_task_container_sweep`); with none, they are left to the
85/// restart path and the day's wait.
86pub fn start(store: Arc<Store>, broker: Arc<Broker>, containers: Option<Arc<dyn ContainerProbe>>) {
87    tokio::spawn(async move {
88        tokio::time::sleep(FIRST_AFTER).await;
89        let mut tick = tokio::time::interval(EVERY);
90        loop {
91            tick.tick().await;
92            let host = Arc::clone(&store);
93            // The store and the process table are blocking reads.
94            let mut changed = tokio::task::spawn_blocking(move || sweep(&host, agentmux_common::time::now_ms(), &pid_alive_since)).await.unwrap_or_default();
95            if let Some(probe) = &containers {
96                changed.extend(sweep_containers(&store, probe.as_ref()).await);
97            }
98            for block_id in changed {
99                publish_background_task_updated(&broker, &block_id);
100            }
101        }
102    });
103}
104
105/// One container pass, then forget what containers reported long ago.
106async fn sweep_containers(store: &Arc<Store>, probe: &dyn ContainerProbe) -> BTreeSet<String> {
107    let now_ms = agentmux_common::time::now_ms();
108    let changed = container_sweep(store, now_ms, probe).await;
109    let store = Arc::clone(store);
110    let _ = tokio::task::spawn_blocking(move || store.background_container_calls_prune(now_ms - CONTAINER_REPORT_KEPT_MS)).await;
111    changed
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    const NOW: i64 = 10 * ORPHAN_AFTER_MS;
119
120    fn store() -> Store {
121        Store::open(std::path::Path::new(":memory:")).unwrap()
122    }
123
124    fn row(store: &Store, id: &str, block: &str, started: i64, seen: i64, pid: Option<i64>) {
125        store.background_task_observe(id, block, "task dev", started, seen).unwrap();
126        if let Some(pid) = pid {
127            store.background_task_set_pid(id, pid).unwrap();
128        }
129    }
130
131    fn status(store: &Store, id: &str) -> (BackgroundTaskStatus, Option<i64>) {
132        let t = store.background_task_get(id).unwrap().unwrap();
133        (t.status, t.ended_at_ms)
134    }
135
136    #[test]
137    fn a_task_whose_process_is_gone_is_stopped_and_one_still_there_stays() {
138        let s = store();
139        row(&s, "dead", "b1", NOW - 5000, NOW - 1000, Some(111));
140        row(&s, "live", "b2", NOW - 5000, NOW - 1000, Some(222));
141        let changed = sweep(&s, NOW, &|pid, _| pid == 222);
142        assert_eq!(changed.into_iter().collect::<Vec<_>>(), vec!["b1".to_string()]);
143        assert_eq!(status(&s, "dead"), (BackgroundTaskStatus::Stopped, Some(NOW)));
144        assert_eq!(status(&s, "live"), (BackgroundTaskStatus::Running, None));
145    }
146
147    #[test]
148    fn the_pid_is_checked_against_when_the_row_started() {
149        let s = store();
150        row(&s, "t", "b1", NOW - 5000, NOW - 1000, Some(111));
151        let seen = std::cell::Cell::new(None);
152        sweep(&s, NOW, &|pid, started| {
153            seen.set(Some((pid, started)));
154            true
155        });
156        assert_eq!(seen.get(), Some((111, (NOW - 5000) as u64)));
157    }
158
159    #[test]
160    fn a_row_with_no_pid_is_left_for_a_day_and_then_ended_at_its_last_sighting() {
161        let s = store();
162        row(&s, "recent", "b1", NOW - 3 * 60 * 60 * 1000, NOW - ORPHAN_AFTER_MS, None);
163        row(&s, "orphan", "b2", NOW - 3 * ORPHAN_AFTER_MS, NOW - ORPHAN_AFTER_MS - 1, None);
164        let changed = sweep(&s, NOW, &|_, _| panic!("no pid to look up"));
165        assert_eq!(changed.into_iter().collect::<Vec<_>>(), vec!["b2".to_string()]);
166        assert_eq!(status(&s, "recent").0, BackgroundTaskStatus::Running);
167        assert_eq!(status(&s, "orphan"), (BackgroundTaskStatus::Stopped, Some(NOW - ORPHAN_AFTER_MS - 1)));
168    }
169
170    #[test]
171    fn a_row_that_already_ended_is_not_touched() {
172        let s = store();
173        row(&s, "done", "b1", NOW - 5000, NOW - 1000, Some(111));
174        s.background_task_complete("done", BackgroundTaskStatus::Done, NOW - 500).unwrap();
175        assert!(sweep(&s, NOW, &|_, _| false).is_empty());
176        assert_eq!(status(&s, "done"), (BackgroundTaskStatus::Done, Some(NOW - 500)));
177    }
178
179    #[test]
180    fn a_pid_that_cannot_be_looked_up_leaves_the_row_alone() {
181        let s = store();
182        row(&s, "zero", "b1", NOW - 5000, NOW - 1000, Some(0));
183        row(&s, "huge", "b1", NOW - 5000, NOW - 1000, Some(i64::from(u32::MAX) + 1));
184        assert!(sweep(&s, NOW, &|_, _| false).is_empty());
185    }
186
187    #[test]
188    fn a_block_with_several_ended_rows_is_reported_once() {
189        let s = store();
190        row(&s, "a", "b1", NOW - 5000, NOW - 1000, Some(1));
191        row(&s, "b", "b1", NOW - 5000, NOW - 1000, Some(2));
192        assert_eq!(sweep(&s, NOW, &|_, _| false).len(), 1);
193    }
194}