Skip to main content

agentmux_srv_core/backend/
background_task_container_sweep.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The liveness sweep for a container agent's background tasks (`background_task_sweep` does a host pane's).
5//!
6//! A container pane's `agentmux-bashwrap` reports the process id it runs under in the container's own pid
7//! namespace. It is filed beside the registry row, never in its host `pid` column
8//! (`storage::background_container_calls`), so nothing on the host can signal it. This pass checks each such
9//! row inside its container, through the Docker exec API, and ends it when the process is gone:
10//!
11//! - **The process is gone**, or the pid now belongs to a process that started after the task did (the same
12//!   start-time guard `pid_alive_since` gives a host pid): the row ends as `stopped`.
13//! - **The container is not running** (the exec is refused because it is stopped or gone): every row of the
14//!   panes that ran in it ends at once, each at its last sighting, as when a container is started again
15//!   (`background_task_exit::end_for_restarted_container`).
16//! - Anything else (Docker unreachable, the probe timed out or printed nothing readable) leaves the row as it
17//!   is: it is only ever ended on evidence.
18//!
19//! Only the probe talks to Docker ([`ContainerProbe`]); this pass is plain logic over the store.
20
21use std::collections::BTreeSet;
22use std::sync::Arc;
23
24use futures_util::future::BoxFuture;
25
26use super::storage::background_tasks::BackgroundTaskStatus;
27use super::storage::store::Store;
28
29/// How far after a task's row began a process may have started and still be that task's: the pid is reported
30/// when the command starts, the row is made a moment later, and the container's clock and this host's can
31/// differ a little.
32const START_SLACK_MS: i64 = 60_000;
33
34/// What the container says of one process.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Verdict {
37    /// The process is there and is the task's.
38    Alive,
39    /// No such process, or the pid belongs to a newer one.
40    Gone,
41    /// The container is not running (or no longer exists): nothing in it is.
42    ContainerDown,
43    /// Nothing can be said now.
44    Unknown,
45}
46
47/// Checks a process inside a container. The Docker-backed one is `container_task_probe`.
48pub trait ContainerProbe: Send + Sync {
49    /// The state of process `pid` of `container`, for a task whose row began at `task_started_ms`.
50    fn probe<'a>(&'a self, container: &'a str, pid: u32, task_started_ms: i64) -> BoxFuture<'a, Verdict>;
51}
52
53/// The verdict a probe's printed answer gives: `gone`, `alive`, or `alive <start of the process, unix seconds>`.
54pub fn verdict_of(output: &str, task_started_ms: i64) -> Verdict {
55    let Some(line) = output.lines().map(str::trim).rev().find(|l| *l == "gone" || l.starts_with("alive")) else {
56        return Verdict::Unknown;
57    };
58    if line == "gone" {
59        return Verdict::Gone;
60    }
61    match line["alive".len()..].trim().parse::<i64>() {
62        Ok(started_s) if started_s.saturating_mul(1000) > task_started_ms.saturating_add(START_SLACK_MS) => Verdict::Gone,
63        _ => Verdict::Alive,
64    }
65}
66
67/// One pass: end the container-held rows that are over. Returns the panes whose rows changed.
68pub async fn sweep(store: &Arc<Store>, now_ms: i64, probe: &dyn ContainerProbe) -> BTreeSet<String> {
69    let mut changed = BTreeSet::new();
70    let reader = Arc::clone(store);
71    let rows = match tokio::task::spawn_blocking(move || reader.background_container_running()).await {
72        Ok(Ok(rows)) => rows,
73        Ok(Err(e)) => {
74            tracing::warn!(target: "background_tasks", error = %e, "container liveness sweep: could not list the running tasks");
75            return changed;
76        }
77        Err(_) => return changed,
78    };
79    let mut down: BTreeSet<&str> = BTreeSet::new();
80    for task in &rows {
81        if down.contains(task.container.as_str()) {
82            continue;
83        }
84        let Some(pid) = u32::try_from(task.pid).ok().filter(|p| *p > 0) else { continue };
85        match probe.probe(&task.container, pid, task.started_at_ms).await {
86            Verdict::Alive | Verdict::Unknown => {}
87            Verdict::Gone => {
88                if end(store, &task.id, now_ms).await {
89                    tracing::info!(target: "background_tasks", block_id = %task.block_id, node_id = %task.id,
90                        "container liveness sweep: a background task whose process is gone is stopped");
91                    changed.insert(task.block_id.clone());
92                }
93            }
94            Verdict::ContainerDown => {
95                down.insert(task.container.as_str());
96            }
97        }
98    }
99    for task in rows.iter().filter(|t| down.contains(t.container.as_str())) {
100        let (store, block_id) = (Arc::clone(store), task.block_id.clone());
101        let ended = tokio::task::spawn_blocking(move || store.background_task_end_unchecked_for_block(&block_id)).await;
102        if matches!(ended, Ok(Ok(n)) if n > 0) {
103            tracing::info!(target: "background_tasks", block_id = %task.block_id, container = %task.container,
104                "container liveness sweep: the container is not running, its background tasks are over");
105            changed.insert(task.block_id.clone());
106        }
107    }
108    changed
109}
110
111/// End `id` as stopped if it is still running.
112async fn end(store: &Arc<Store>, id: &str, now_ms: i64) -> bool {
113    let (store, id) = (Arc::clone(store), id.to_string());
114    let ended = tokio::task::spawn_blocking(move || store.background_task_end_if_running(&id, BackgroundTaskStatus::Stopped, now_ms)).await;
115    matches!(ended, Ok(Ok(true)))
116}
117
118#[cfg(test)]
119#[path = "background_task_container_sweep_tests.rs"]
120mod tests;