agentmux_srv_core/backend/pending_background_pids.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! In-memory holding pen for a declared-background task's OS pid when it
5//! arrives before `db_background_tasks` has a row to attach it to.
6//!
7//! `agentmux-bashwrap` publishes its own pid over MPS essentially at process
8//! start (before the wrapped command even begins running) — see
9//! `bash_wrap.rs`. The `db_background_tasks` row, by contrast, is only
10//! created once the FRONTEND observes the tool call as an accepted
11//! background launch (requires the literal "Command running in background
12//! with ID:" tool-result prefix) and pushes `docknodestatus`, which is a
13//! full extra round-trip through the CLI's own stream-json processing. The
14//! pid publish routinely wins that race.
15//!
16//! `background_task_set_pid` (`background_tasks.rs`) is a bare
17//! `UPDATE ... WHERE id = ?` — it silently no-ops (`Ok(false)`) when the
18//! row doesn't exist yet, and the pid would be lost forever with no retry
19//! that could ever succeed (retrying the same too-early write doesn't
20//! help — the row still won't exist).
21//!
22//! [`set_or_stash`](PendingBackgroundPids::set_or_stash) and
23//! [`observe_and_apply`](PendingBackgroundPids::observe_and_apply) are the
24//! two sides of the fix, called from `websocket.rs`'s
25//! `COMMAND_BACKGROUND_TASK_PID` and `COMMAND_DOCK_NODE_STATUS` handlers
26//! respectively. Both run their DB call (via the `try_set`/`apply` closure)
27//! WHILE HOLDING this module's own lock, not as a separate step after it —
28//! an earlier version of this module exposed plain `stash`/`take` methods
29//! instead, with each handler doing its own DB call first and the
30//! stash/take second, unlocked in between. That let the two handlers'
31//! steps interleave (pid handler's DB call sees no row → before it stashes,
32//! the observe handler's own take() already ran and found nothing →
33//! observe handler's row now exists but nothing will ever re-check it →
34//! pid handler's stash lands after the one take() that would have
35//! consumed it, and sits unclaimed until the TTL drops it). Making the DB
36//! call part of the SAME critical section as the buffer mutation closes
37//! that window: whichever handler's critical section runs second always
38//! observes the first one's effect, DB row or stash, correctly. See
39//! docs/specs/SPEC_BACKGROUND_TASK_PID_CAPTURE_2026_08_20.md and the
40//! Codex/reagentx findings on PR #2681 this was written to address.
41
42use std::collections::HashMap;
43
44use parking_lot::Mutex;
45
46/// How long a stashed pid waits for its row before being dropped. Generous
47/// relative to the observed race window (a network round-trip plus one
48/// SQLite write, normally well under a second) but still bounded — a
49/// declared-background call whose launch is never actually accepted as
50/// background client-side (e.g. the command finished fast enough that
51/// Claude's harness returned synchronously despite `run_in_background:
52/// true` — see issue #2519) would otherwise leak an entry here forever,
53/// since `background_task_observe` would then never fire for that id.
54const PENDING_PID_TTL_MS: i64 = 5 * 60 * 1000;
55
56struct PendingEntry {
57 pid: i64,
58 stashed_at_ms: i64,
59}
60
61#[derive(Default)]
62pub struct PendingBackgroundPids {
63 inner: Mutex<HashMap<String, PendingEntry>>,
64}
65
66impl PendingBackgroundPids {
67 pub fn new() -> Self {
68 Self::default()
69 }
70
71 /// The one pen of this srv. A pid is filed from srv's own broker observer (`background_task_pid`) and a row is
72 /// created from either the pane's `docknodestatus` or the CLI's task feed in the stdout reader, which has no app
73 /// state to hold a pen of its own: all of them meet here.
74 pub fn global() -> &'static PendingBackgroundPids {
75 static PEN: std::sync::LazyLock<PendingBackgroundPids> = std::sync::LazyLock::new(PendingBackgroundPids::new);
76 &PEN
77 }
78
79 fn evict_expired_locked(guard: &mut HashMap<String, PendingEntry>, now_ms: i64) {
80 guard.retain(|_, e| now_ms.saturating_sub(e.stashed_at_ms) < PENDING_PID_TTL_MS);
81 }
82
83 /// Called from the pid-arrival side (`COMMAND_BACKGROUND_TASK_PID`).
84 /// Runs `try_set(pid)` (the `background_task_set_pid` DB call) while
85 /// holding this module's lock; if it reports the row doesn't exist yet
86 /// (`Ok(false)`), stashes the pid instead of losing it. Atomic with
87 /// `observe_and_apply` below for the same `id` — see the module doc
88 /// comment for why that matters.
89 pub fn set_or_stash<E>(
90 &self,
91 id: &str,
92 pid: i64,
93 now_ms: i64,
94 try_set: impl FnOnce(i64) -> Result<bool, E>,
95 ) -> Result<(), E> {
96 let mut guard = self.inner.lock();
97 Self::evict_expired_locked(&mut guard, now_ms);
98 match try_set(pid)? {
99 true => {
100 guard.remove(id);
101 }
102 false => {
103 guard.insert(id.to_string(), PendingEntry { pid, stashed_at_ms: now_ms });
104 }
105 }
106 Ok(())
107 }
108
109 /// Called from the row-creation side (`COMMAND_DOCK_NODE_STATUS`),
110 /// after its own `background_task_observe(...)` call. Checks for a
111 /// pid stashed ahead of the row's existence and, if present and not
112 /// expired, applies it via `apply` (another `background_task_set_pid`
113 /// call) while holding this module's lock. Atomic with `set_or_stash`
114 /// above for the same `id`.
115 pub fn observe_and_apply<E>(
116 &self,
117 id: &str,
118 now_ms: i64,
119 apply: impl FnOnce(i64) -> Result<bool, E>,
120 ) -> Result<(), E> {
121 let mut guard = self.inner.lock();
122 Self::evict_expired_locked(&mut guard, now_ms);
123 if let Some(entry) = guard.remove(id) {
124 apply(entry.pid)?;
125 }
126 Ok(())
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 #[derive(Debug, PartialEq)]
135 struct TestErr;
136
137 #[test]
138 fn set_or_stash_applies_directly_when_the_row_already_exists() {
139 let p = PendingBackgroundPids::new();
140 let mut set_calls = Vec::new();
141 let r: Result<(), TestErr> = p.set_or_stash("t1", 4242, 1000, |pid| {
142 set_calls.push(pid);
143 Ok(true) // row exists, update succeeded
144 });
145 assert!(r.is_ok());
146 assert_eq!(set_calls, vec![4242]);
147 // Nothing stashed — a later observe_and_apply finds nothing to apply.
148 let mut applied = Vec::new();
149 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1001, |pid| {
150 applied.push(pid);
151 Ok(true)
152 });
153 assert!(applied.is_empty());
154 }
155
156 #[test]
157 fn set_or_stash_then_observe_and_apply_delivers_the_pid() {
158 // The exact race this module exists to close: pid arrives before
159 // the row does.
160 let p = PendingBackgroundPids::new();
161 let r: Result<(), TestErr> = p.set_or_stash("t1", 4242, 1000, |_pid| Ok(false)); // no row yet
162 assert!(r.is_ok());
163
164 let mut applied = Vec::new();
165 let r2: Result<(), TestErr> = p.observe_and_apply("t1", 1050, |pid| {
166 applied.push(pid);
167 Ok(true)
168 });
169 assert!(r2.is_ok());
170 assert_eq!(applied, vec![4242]);
171
172 // Consumed — a second observe_and_apply finds nothing.
173 let mut applied2 = Vec::new();
174 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1051, |pid| {
175 applied2.push(pid);
176 Ok(true)
177 });
178 assert!(applied2.is_empty());
179 }
180
181 #[test]
182 fn observe_and_apply_before_any_pid_arrives_is_a_no_op() {
183 let p = PendingBackgroundPids::new();
184 let mut applied = Vec::new();
185 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1000, |pid| {
186 applied.push(pid);
187 Ok(true)
188 });
189 assert!(applied.is_empty());
190 }
191
192 #[test]
193 fn set_or_stash_propagates_the_db_error_without_stashing() {
194 let p = PendingBackgroundPids::new();
195 let r: Result<(), TestErr> = p.set_or_stash("t1", 4242, 1000, |_pid| Err(TestErr));
196 assert_eq!(r, Err(TestErr));
197 // Nothing stashed despite the error.
198 let mut applied = Vec::new();
199 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1001, |pid| {
200 applied.push(pid);
201 Ok(true)
202 });
203 assert!(applied.is_empty());
204 }
205
206 #[test]
207 fn observe_and_apply_propagates_the_db_error_but_still_consumes_the_stash() {
208 // Matches the module's stated semantics: this is a best-effort
209 // relay, not something worth retrying indefinitely — a stashed
210 // pid is consumed on the attempt regardless of outcome.
211 let p = PendingBackgroundPids::new();
212 let _: Result<(), TestErr> = p.set_or_stash("t1", 4242, 1000, |_pid| Ok(false));
213 let r: Result<(), TestErr> = p.observe_and_apply("t1", 1001, |_pid| Err(TestErr));
214 assert_eq!(r, Err(TestErr));
215 let mut applied = Vec::new();
216 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1002, |pid| {
217 applied.push(pid);
218 Ok(true)
219 });
220 assert!(applied.is_empty());
221 }
222
223 #[test]
224 fn a_stash_past_ttl_is_not_applied() {
225 let p = PendingBackgroundPids::new();
226 let _: Result<(), TestErr> = p.set_or_stash("t1", 4242, 1000, |_pid| Ok(false));
227 let mut applied = Vec::new();
228 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1000 + PENDING_PID_TTL_MS, |pid| {
229 applied.push(pid);
230 Ok(true)
231 });
232 assert!(applied.is_empty());
233 }
234
235 #[test]
236 fn set_or_stash_overwrites_a_previous_pending_pid_for_the_same_id() {
237 let p = PendingBackgroundPids::new();
238 let _: Result<(), TestErr> = p.set_or_stash("t1", 111, 1000, |_pid| Ok(false));
239 let _: Result<(), TestErr> = p.set_or_stash("t1", 222, 1001, |_pid| Ok(false));
240 let mut applied = Vec::new();
241 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1002, |pid| {
242 applied.push(pid);
243 Ok(true)
244 });
245 assert_eq!(applied, vec![222]);
246 }
247
248 #[test]
249 fn different_ids_coexist_independently() {
250 let p = PendingBackgroundPids::new();
251 let _: Result<(), TestErr> = p.set_or_stash("t1", 1, 1000, |_pid| Ok(false));
252 let _: Result<(), TestErr> = p.set_or_stash("t2", 2, 1000, |_pid| Ok(false));
253 let mut applied = Vec::new();
254 let _: Result<(), TestErr> = p.observe_and_apply("t1", 1000, |pid| {
255 applied.push(pid);
256 Ok(true)
257 });
258 let _: Result<(), TestErr> = p.observe_and_apply("t2", 1000, |pid| {
259 applied.push(pid);
260 Ok(true)
261 });
262 assert_eq!(applied, vec![1, 2]);
263 }
264}