Skip to content

Commit 02cd9bf

Browse files
authored
fix: suspension and restart wait for background execs (#104172)
* fix: block restart and suspension on background execs * test: cover background exec suspension inspector
1 parent b8502e1 commit 02cd9bf

17 files changed

Lines changed: 675 additions & 44 deletions

‎docs/gateway/background-process.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ Actions:
8181
Notes:
8282

8383
- Only backgrounded sessions are listed/persisted — in memory only, not on disk. Sessions are lost on process restart.
84+
- A live background session blocks cooperative host suspension and safe Gateway restart until the process owner confirms its actual exit.
85+
- `process remove` can hide a running session immediately after requesting termination; suspension and restart remain blocked until exit confirmation.
8486
- Session logs are only saved to chat history if you run `process poll`/`log` and the tool result is recorded.
8587
- `process` is scoped per agent; it only sees sessions started by that agent.
8688
- Use `poll`/`log` for status, logs, or completion confirmation when automatic completion wake is unavailable.

‎docs/gateway/external-apps.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,8 +134,10 @@ transports, or control the hosting platform. The host must fence its ingress
134134
before preparation and remains responsible for wake, snapshot/freeze, and
135135
stop. `activeCount` is the aggregate tracked-work count, while `blockers`
136136
contains the non-zero category counts and bounded task details. This is not a
137-
general process-quiescence barrier. Channel health, maintenance, cache refresh,
138-
established plugin WebSocket sessions, and plugin-owned background work can
137+
general process-quiescence barrier. A `background-exec` blocker is aggregate
138+
only: command text, process IDs, output, and session or scope identifiers never
139+
cross the protocol. Channel health, maintenance, cache refresh, established
140+
plugin WebSocket sessions, and unregistered plugin-owned background work can
139141
remain active.
140142
The hosting platform must freeze or snapshot the full process tree and its
141143
filesystem consistently; unregistered work cannot be proven idle by this first

‎packages/gateway-protocol/src/gateway-suspend.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,36 @@ describe("gateway suspension protocol", () => {
4444
).toBe(true);
4545
});
4646

47+
it("keeps background exec blockers count-only", () => {
48+
const result = {
49+
status: "busy",
50+
reason: "active-work",
51+
retryAfterMs: 20_000,
52+
activeCount: 1,
53+
blockers: [
54+
{
55+
kind: "background-exec",
56+
count: 1,
57+
message: "1 active background exec session(s)",
58+
},
59+
],
60+
};
61+
62+
expect(validateGatewaySuspendPrepareResult(result)).toBe(true);
63+
expect(
64+
validateGatewaySuspendPrepareResult({
65+
...result,
66+
blockers: [{ ...result.blockers[0], sessionIds: ["private-session-id"] }],
67+
}),
68+
).toBe(false);
69+
expect(
70+
validateGatewaySuspendPrepareResult({
71+
...result,
72+
blockers: [{ ...result.blockers[0], command: "private command" }],
73+
}),
74+
).toBe(false);
75+
});
76+
4777
it("validates status and resume results", () => {
4878
expect(validateGatewaySuspendStatusResult({ status: "running" })).toBe(true);
4979
expect(validateGatewaySuspendStatusResult({ status: "ready", expiresAtMs: 123 })).toBe(true);

‎packages/gateway-protocol/src/schema/gateway-suspend.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export const GatewaySuspendBlockerSchema = Type.Object(
2727
Type.Literal("queue"),
2828
Type.Literal("reply"),
2929
Type.Literal("embedded-run"),
30+
Type.Literal("background-exec"),
3031
Type.Literal("cron-run"),
3132
Type.Literal("task"),
3233
Type.Literal("root-request"),

‎src/agents/bash-process-registry.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@ import type { ProcessSession } from "./bash-process-registry.js";
99
import {
1010
addSession,
1111
appendOutput,
12+
createSessionSlug,
13+
deleteSession,
1214
drainSession,
15+
getActiveBackgroundExecSessionCount,
1316
listFinishedSessions,
17+
listRunningSessions,
1418
markBackgrounded,
1519
markExited,
1620
resetProcessRegistryForTests,
@@ -19,6 +23,14 @@ import {
1923
} from "./bash-process-registry.js";
2024
import { createProcessSessionFixture } from "./bash-process-registry.test-helpers.js";
2125

26+
const randomMocks = vi.hoisted(() => ({
27+
generateSecureInt: vi.fn(() => 0),
28+
}));
29+
30+
vi.mock("../infra/secure-random.js", () => ({
31+
generateSecureInt: randomMocks.generateSecureInt,
32+
}));
33+
2234
describe("bash process registry", () => {
2335
function createRegistrySession(params: {
2436
id?: string;
@@ -37,6 +49,8 @@ describe("bash process registry", () => {
3749
}
3850

3951
beforeEach(() => {
52+
randomMocks.generateSecureInt.mockReset();
53+
randomMocks.generateSecureInt.mockReturnValue(0);
4054
resetProcessRegistryForTests();
4155
});
4256

@@ -173,6 +187,79 @@ describe("bash process registry", () => {
173187
]);
174188
});
175189

190+
it("tracks only live backgrounded sessions", () => {
191+
const session = createRegistrySession({
192+
maxOutputChars: 100,
193+
pendingMaxOutputChars: 30_000,
194+
backgrounded: false,
195+
});
196+
197+
addSession(session);
198+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
199+
200+
markBackgrounded(session);
201+
markBackgrounded(session);
202+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
203+
204+
markExited(session, 0, null, "completed");
205+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
206+
207+
markBackgrounded(session);
208+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
209+
});
210+
211+
it("keeps a hidden background session active until its process exits", () => {
212+
const session = createRegistrySession({
213+
id: "hidden-until-exit",
214+
maxOutputChars: 100,
215+
pendingMaxOutputChars: 30_000,
216+
backgrounded: false,
217+
});
218+
219+
addSession(session);
220+
markBackgrounded(session);
221+
deleteSession(session.id);
222+
223+
expect(listRunningSessions()).toHaveLength(0);
224+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
225+
226+
markExited(session, null, "SIGTERM", "killed");
227+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
228+
});
229+
230+
it("keeps a hidden active session id reserved until exit", () => {
231+
const session = createRegistrySession({
232+
id: "amber-atlas",
233+
maxOutputChars: 100,
234+
pendingMaxOutputChars: 30_000,
235+
backgrounded: false,
236+
});
237+
238+
addSession(session);
239+
markBackgrounded(session);
240+
deleteSession(session.id);
241+
expect(createSessionSlug()).toBe("amber-atlas-2");
242+
243+
session.backgrounded = false;
244+
markExited(session, 0, null, "completed");
245+
expect(createSessionSlug()).toBe("amber-atlas");
246+
});
247+
248+
it("clears background activity in the test reset", () => {
249+
const session = createRegistrySession({
250+
maxOutputChars: 100,
251+
pendingMaxOutputChars: 30_000,
252+
backgrounded: false,
253+
});
254+
255+
addSession(session);
256+
markBackgrounded(session);
257+
expect(getActiveBackgroundExecSessionCount()).toBe(1);
258+
259+
resetProcessRegistryForTests();
260+
expect(getActiveBackgroundExecSessionCount()).toBe(0);
261+
});
262+
176263
it("clamps a zero retention TTL to one minute", () => {
177264
vi.useFakeTimers();
178265
try {

‎src/agents/bash-process-registry.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,14 @@ interface FinishedSession {
109109

110110
const runningSessions = new Map<string, ProcessSession>();
111111
const finishedSessions = new Map<string, FinishedSession>();
112+
const activeBackgroundExecSessionIds = new Set<string>();
112113

113114
let sweeper: NodeJS.Timeout | null = null;
114115

115116
function isSessionIdTaken(id: string) {
116-
return runningSessions.has(id) || finishedSessions.has(id);
117+
return (
118+
runningSessions.has(id) || finishedSessions.has(id) || activeBackgroundExecSessionIds.has(id)
119+
);
117120
}
118121

119122
/** Creates a unique short session id that avoids running and retained sessions. */
@@ -137,7 +140,7 @@ export function getFinishedSession(id: string) {
137140
return finishedSessions.get(id);
138141
}
139142

140-
/** Removes a session from both running and finished registries. */
143+
/** Removes visible session records without changing live-process activity. */
141144
export function deleteSession(id: string) {
142145
runningSessions.delete(id);
143146
finishedSessions.delete(id);
@@ -194,6 +197,9 @@ export function markExited(
194197
exitReason?: TerminationReason,
195198
noOutputTimedOut?: boolean,
196199
) {
200+
// Visibility can be cleared before process termination. Keep suspension
201+
// blocked until the process owner reports the actual terminal transition.
202+
activeBackgroundExecSessionIds.delete(session.id);
197203
session.exited = true;
198204
session.exitCode = exitCode;
199205
session.exitSignal = exitSignal;
@@ -206,6 +212,14 @@ export function markExited(
206212
/** Marks a running session as reconnectable after the exec call returns. */
207213
export function markBackgrounded(session: ProcessSession) {
208214
session.backgrounded = true;
215+
if (!session.exited) {
216+
activeBackgroundExecSessionIds.add(session.id);
217+
}
218+
}
219+
220+
/** Returns the number of live background exec sessions without exposing process details. */
221+
export function getActiveBackgroundExecSessionCount(): number {
222+
return activeBackgroundExecSessionIds.size;
209223
}
210224

211225
function moveToFinished(session: ProcessSession, status: ProcessStatus) {
@@ -334,6 +348,7 @@ export function listFinishedSessions() {
334348
export function resetProcessRegistryForTests() {
335349
runningSessions.clear();
336350
finishedSessions.clear();
351+
activeBackgroundExecSessionIds.clear();
337352
stopSweeper();
338353
}
339354

0 commit comments

Comments
 (0)