Skip to content

Commit 064b0dd

Browse files
authored
refactor(agents): retain one process record through completion (#130572)
1 parent f1bef4b commit 064b0dd

12 files changed

Lines changed: 303 additions & 246 deletions

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

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,9 @@ import {
1010
addSession,
1111
appendOutput,
1212
deleteSession,
13-
drainFinishedSession,
1413
drainSession,
1514
getActiveBackgroundExecSessionCount,
1615
getFinishedSession,
17-
getFinishedSessionForProcess,
1816
isProcessSessionIdTaken,
1917
listFinishedSessions,
2018
listRunningSessions,
@@ -208,34 +206,21 @@ describe("bash process registry", () => {
208206
addSession(session);
209207
markExited(session, 0, null, "completed");
210208
expect(listFinishedSessions()).toHaveLength(0);
209+
expect(session.endedAt).toBeUndefined();
211210

212211
markBackgrounded(session);
213212
markExited(session, 0, null, "completed");
214213
const finishedSessions = listFinishedSessions();
215214
const endedAt = finishedSessions[0]?.endedAt;
216215
expect(endedAt).toEqual(expect.any(Number));
217-
expect(finishedSessions).toStrictEqual([
218-
{
219-
id: "sess",
220-
command: "echo test",
221-
scopeKey: undefined,
222-
startedAt: session.startedAt,
223-
endedAt,
224-
cwd: "/tmp",
225-
status: "completed",
226-
exitCode: 0,
227-
exitSignal: null,
228-
exitReason: undefined,
229-
aggregated: "",
230-
tail: "",
231-
truncated: false,
232-
totalOutputChars: 0,
233-
unreadOutput: { output: "", outputDropped: false },
234-
},
235-
]);
216+
expect(finishedSessions).toEqual([session]);
217+
expect(session.terminalStatus).toBe("completed");
218+
deleteSession(session.id);
219+
expect(session.endedAt).toBe(endedAt);
220+
expect(listFinishedSessions()).toHaveLength(0);
236221
});
237222

238-
it("moves unread output into the exact finished snapshot and consumes it once", () => {
223+
it("retains unread output on its exact process and consumes it once", () => {
239224
const session = createRegistrySession({
240225
id: "exact-finished-output",
241226
maxOutputChars: 100,
@@ -246,10 +231,9 @@ describe("bash process registry", () => {
246231
appendOutput(session, "stdout", "terminal output\n");
247232
markExited(session, 0, null, "completed");
248233

249-
const finished = getFinishedSessionForProcess(session);
250-
expect(finished).toBe(getFinishedSession(session.id));
251-
expect(finished && drainFinishedSession(finished).output).toBe("terminal output\n");
252-
expect(finished && drainFinishedSession(finished).output).toBe("");
234+
const finished = getFinishedSession(session.id);
235+
expect(finished).toBe(session);
236+
expect(finished && drainSession(finished).output).toBe("terminal output\n");
253237
expect(drainSession(session).output).toBe("");
254238
});
255239

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

Lines changed: 24 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ type PendingOutputChunk = {
4949
text: string;
5050
};
5151

52-
/** Mutable session state for a running bash exec process. */
52+
/** One process record from execution through completed retention. */
5353
export interface ProcessSession {
5454
id: string;
5555
command: string;
@@ -84,11 +84,14 @@ export interface ProcessSession {
8484
stdin?: SessionStdin;
8585
pid?: number;
8686
startedAt: number;
87+
/** Set only on admission to completed retention; survives index removal. */
88+
endedAt?: number;
8789
cwd?: string;
8890
maxOutputChars: number;
8991
pendingMaxOutputChars?: number;
9092
totalOutputChars: number;
91-
pendingOutput: PendingOutputChunk[];
93+
/** Live chunks become frozen text at completion, releasing the chunk graph. */
94+
pendingOutput: PendingOutputChunk[] | string;
9295
pendingStdoutChars: number;
9396
pendingStderrChars: number;
9497
/** Output was dropped from the pending poll buffers since their last drain. */
@@ -110,32 +113,9 @@ export interface ProcessSession {
110113
cursorKeyMode: "unknown" | "normal" | "application";
111114
}
112115

113-
/** Retained summary for a completed background session. */
114-
interface FinishedSession {
115-
id: string;
116-
command: string;
117-
scopeKey?: string;
118-
startedAt: number;
119-
endedAt: number;
120-
cwd?: string;
121-
status: ProcessStatus;
122-
exitCode?: number | null;
123-
exitSignal?: NodeJS.Signals | number | null;
124-
exitReason?: TerminationReason;
125-
noOutputTimedOut?: boolean;
126-
aggregated: string;
127-
tail: string;
128-
truncated: boolean;
129-
totalOutputChars: number;
130-
unreadOutput?: ReturnType<typeof drainSession>;
131-
terminalPollObserved?: boolean;
132-
notifyOnExitRemoval?: NotifyOnExitRemoval;
133-
}
134-
135116
const runningSessions = new Map<string, ProcessSession>();
136-
const finishedSessions = new Map<string, FinishedSession>();
137-
let finishedSessionsByProcess = new WeakMap<ProcessSession, FinishedSession>();
138-
// Keep start chronology private while snapshots retain their completion-order eviction contract.
117+
const finishedSessions = new Map<string, ProcessSession & { endedAt: number }>();
118+
// Display uses start chronology; retained records are evicted in completion order.
139119
let processSessionStartOrders = new WeakMap<object, number>();
140120
let nextProcessSessionStartOrder = 0;
141121
const activeBackgroundExecSessionIds = new Set<string>();
@@ -178,11 +158,6 @@ export function getFinishedSession(id: string) {
178158
return finishedSessions.get(id);
179159
}
180160

181-
/** Returns the terminal snapshot owned by this exact process incarnation. */
182-
export function getFinishedSessionForProcess(session: ProcessSession) {
183-
return finishedSessionsByProcess.get(session);
184-
}
185-
186161
function deleteFinishedSession(id: string): boolean {
187162
const session = finishedSessions.get(id);
188163
if (!session) {
@@ -220,6 +195,9 @@ export function clearFinishedSessionsForScopes(scopeKeys: Iterable<string>): voi
220195

221196
/** Appends process output while enforcing aggregate and pending-output caps. */
222197
export function appendOutput(session: ProcessSession, stream: "stdout" | "stderr", chunk: string) {
198+
if (typeof session.pendingOutput === "string") {
199+
return;
200+
}
223201
const streamChars = stream === "stdout" ? session.pendingStdoutChars : session.pendingStderrChars;
224202
const pendingCap = Math.min(
225203
session.pendingMaxOutputChars ?? DEFAULT_PENDING_OUTPUT_CHARS,
@@ -247,22 +225,18 @@ export function appendOutput(session: ProcessSession, stream: "stdout" | "stderr
247225

248226
/** Drains pending chunks in producer callback order for a process poll. */
249227
export function drainSession(session: ProcessSession) {
250-
const output = session.pendingOutput.map((chunk) => chunk.text).join("");
228+
const pending = session.pendingOutput;
229+
const output =
230+
typeof pending === "string" ? pending : pending.map((chunk) => chunk.text).join("");
251231
const outputDropped = session.pendingOutputDropped;
252-
session.pendingOutput = [];
232+
// Draining a terminal record must not reopen it to late producer callbacks.
233+
session.pendingOutput = typeof pending === "string" ? "" : [];
253234
session.pendingStdoutChars = 0;
254235
session.pendingStderrChars = 0;
255236
session.pendingOutputDropped = false;
256237
return { output, outputDropped };
257238
}
258239

259-
/** Consumes the output transferred to one exact terminal snapshot. */
260-
export function drainFinishedSession(session: FinishedSession) {
261-
const output = session.unreadOutput;
262-
session.unreadOutput = undefined;
263-
return output ?? { output: "", outputDropped: false };
264-
}
265-
266240
/** Moves a session to finished state and records exit metadata. */
267241
export function markExited(
268242
session: ProcessSession,
@@ -282,7 +256,12 @@ export function markExited(
282256
session.exitReason = exitReason;
283257
session.noOutputTimedOut = noOutputTimedOut;
284258
session.tail = tail(session.aggregated, 2000);
285-
moveToFinished(session, status);
259+
// Finalizer diagnostics are already appended. Freeze output before retention
260+
// accounts for its size, and release the live per-callback chunk objects.
261+
const pending = drainSession(session);
262+
session.pendingOutput = pending.output;
263+
session.pendingOutputDropped = pending.outputDropped;
264+
moveToFinished(session);
286265
}
287266

288267
/** Marks a running session as reconnectable after the exec call returns. */
@@ -296,13 +275,9 @@ export function markBackgrounded(session: ProcessSession) {
296275
/** Records that a terminal process poll consumed the process result. */
297276
export function markTerminalPollObserved(session: ProcessSession): void {
298277
session.terminalPollObserved = true;
299-
const finished = finishedSessionsByProcess.get(session);
300-
if (finished) {
301-
finished.terminalPollObserved = true;
302-
}
303278
}
304279

305-
/** Retains the precise event removal handle across the finished-session move. */
280+
/** Retains the precise completion-event removal handle on its process owner. */
306281
export function recordNotifyOnExitRemoval(
307282
session: ProcessSession,
308283
remove: NotifyOnExitRemoval,
@@ -312,10 +287,6 @@ export function recordNotifyOnExitRemoval(
312287
return;
313288
}
314289
session.notifyOnExitRemoval = remove;
315-
const finished = finishedSessionsByProcess.get(session);
316-
if (finished) {
317-
finished.notifyOnExitRemoval = remove;
318-
}
319290
}
320291

321292
/** Acknowledges one completion event without touching unrelated queue entries. */
@@ -340,7 +311,7 @@ export function getActiveBackgroundExecSessionCount(): number {
340311
return activeBackgroundExecSessionIds.size;
341312
}
342313

343-
function moveToFinished(session: ProcessSession, status: ProcessStatus) {
314+
function moveToFinished(session: ProcessSession) {
344315
runningSessions.delete(session.id);
345316

346317
// The supervisor owns the raw process. The registry releases only the
@@ -361,31 +332,7 @@ function moveToFinished(session: ProcessSession, status: ProcessStatus) {
361332
// Keep full completed logs; evict older records rather than silently
362333
// truncating the process poll/log contract or dropping the newest result.
363334
deleteFinishedSession(session.id);
364-
const finished: FinishedSession = {
365-
id: session.id,
366-
command: session.command,
367-
scopeKey: session.scopeKey,
368-
startedAt: session.startedAt,
369-
endedAt: Date.now(),
370-
cwd: session.cwd,
371-
status,
372-
exitCode: session.exitCode,
373-
exitSignal: session.exitSignal,
374-
exitReason: session.exitReason,
375-
...(session.noOutputTimedOut !== undefined
376-
? { noOutputTimedOut: session.noOutputTimedOut }
377-
: {}),
378-
aggregated: session.aggregated,
379-
tail: session.tail,
380-
truncated: session.truncated,
381-
totalOutputChars: session.totalOutputChars,
382-
unreadOutput: drainSession(session),
383-
...(session.terminalPollObserved ? { terminalPollObserved: true } : {}),
384-
...(session.notifyOnExitRemoval ? { notifyOnExitRemoval: session.notifyOnExitRemoval } : {}),
385-
};
386-
processSessionStartOrders.set(finished, processSessionStartOrders.get(session)!);
387-
finishedSessionsByProcess.set(session, finished);
388-
finishedSessions.set(session.id, finished);
335+
finishedSessions.set(session.id, Object.assign(session, { endedAt: Date.now() }));
389336
finishedSessionOutputChars += session.aggregated.length;
390337
while (
391338
finishedSessions.size > MAX_FINISHED_SESSION_COUNT ||
@@ -455,7 +402,6 @@ export function listFinishedSessions() {
455402
function resetProcessRegistryForTests() {
456403
runningSessions.clear();
457404
finishedSessions.clear();
458-
finishedSessionsByProcess = new WeakMap();
459405
processSessionStartOrders = new WeakMap();
460406
nextProcessSessionStartOrder = 0;
461407
finishedSessionOutputChars = 0;

0 commit comments

Comments
 (0)