Skip to content

Commit 107e116

Browse files
steipetePeter Steinberger
andauthored
fix(gateway): preserve accepted suggestions until capacity demands eviction (#117623)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent d03a43a commit 107e116

2 files changed

Lines changed: 190 additions & 31 deletions

File tree

‎src/gateway/server-methods/task-suggestions.test.ts‎

Lines changed: 154 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { managedWorktrees } from "../../agents/worktrees/service.js";
33
import {
44
abandonTaskSuggestionAcceptance,
55
beginTaskSuggestionAcceptance,
6+
completeTaskSuggestionAcceptance,
67
} from "../task-suggestion-registry.js";
78
import { sessionsHandlers } from "./sessions.js";
89
import { taskSuggestionsHandlers } from "./task-suggestions.js";
@@ -92,7 +93,7 @@ describe("task suggestion gateway methods", () => {
9293
expect(empty.response?.[1]).toEqual({ suggestions: [] });
9394
});
9495

95-
it("accepts a suggestion once and replays the created session key", async () => {
96+
it("preserves accepted-session replay when successful admission expires a pending suggestion", async () => {
9697
const created = await call("taskSuggestions.create", {
9798
title: "Remove stale adapter",
9899
prompt: "Delete src/example.ts and update its tests.",
@@ -120,6 +121,38 @@ describe("task suggestion gateway methods", () => {
120121
});
121122

122123
const first = await call("taskSuggestions.accept", { taskId });
124+
for (let index = 0; index < 100; index += 1) {
125+
requirePayload(
126+
await call("taskSuggestions.create", {
127+
title: `Pending follow up ${index}`,
128+
prompt: `Complete pending follow-up task ${index}.`,
129+
tldr: "The operator has not accepted this follow-up.",
130+
cwd: "/repo",
131+
sessionKey: "agent:main:main",
132+
}),
133+
);
134+
}
135+
136+
const previous = await call("taskSuggestions.list", {});
137+
const pending = (requirePayload(previous) as { suggestions: Array<{ id: string }> })
138+
.suggestions;
139+
const oldestPending = pending.at(-1);
140+
expect(oldestPending).toBeDefined();
141+
const admitted = await call("taskSuggestions.create", {
142+
title: "Latest follow up",
143+
prompt: "Preserve the accepted task while admitting new work.",
144+
tldr: "Evict only the oldest pending follow-up.",
145+
cwd: "/repo",
146+
sessionKey: "agent:main:main",
147+
});
148+
expect(admitted.response?.[0]).toBe(true);
149+
expect(admitted.broadcast).toHaveBeenNthCalledWith(
150+
1,
151+
"task.suggestion",
152+
{ action: "resolved", taskId: oldestPending?.id, resolution: "expired" },
153+
{ dropIfSlow: true },
154+
);
155+
123156
const retry = await call("taskSuggestions.accept", { taskId });
124157

125158
expect(first.response?.[1]).toEqual({ taskId, key: sessionKey });
@@ -132,6 +165,49 @@ describe("task suggestion gateway methods", () => {
132165
);
133166
});
134167

168+
it("admits new work when every bounded registry entry has already been accepted", async () => {
169+
const acceptedTaskIds: string[] = [];
170+
const createSession = vi
171+
.spyOn(sessionsHandlers, "sessions.create")
172+
.mockImplementation(async ({ params, respond }) => {
173+
respond(true, { key: (params as { key: string }).key, runStarted: true }, undefined);
174+
});
175+
176+
for (let index = 0; index < 100; index += 1) {
177+
const created = await call("taskSuggestions.create", {
178+
title: `Accepted follow up ${index}`,
179+
prompt: `Complete accepted follow-up task ${index}.`,
180+
tldr: "This follow-up already created its managed task session.",
181+
cwd: "/repo",
182+
sessionKey: "agent:main:main",
183+
});
184+
const taskId = (requirePayload(created) as { taskId: string }).taskId;
185+
const accepted = await call("taskSuggestions.accept", { taskId });
186+
expect(accepted.response?.[1]).toMatchObject({ taskId });
187+
acceptedTaskIds.push(taskId);
188+
}
189+
190+
const replacement = await call("taskSuggestions.create", {
191+
title: "Latest follow up",
192+
prompt: "Keep accepting new suggestions after earlier tasks completed.",
193+
tldr: "Accepted-session replay is bounded best-effort state.",
194+
cwd: "/repo",
195+
sessionKey: "agent:main:main",
196+
});
197+
198+
expect(replacement.response?.[0]).toBe(true);
199+
expect(replacement.broadcast).toHaveBeenCalledTimes(1);
200+
expect(replacement.broadcast).toHaveBeenCalledWith(
201+
"task.suggestion",
202+
expect.objectContaining({ action: "created" }),
203+
{ dropIfSlow: true },
204+
);
205+
const oldestRetry = await call("taskSuggestions.accept", { taskId: acceptedTaskIds[0] });
206+
expect(oldestRetry.response?.[0]).toBe(false);
207+
expect(oldestRetry.response?.[2]).toMatchObject({ code: "INVALID_REQUEST" });
208+
expect(createSession).toHaveBeenCalledTimes(100);
209+
});
210+
135211
it("coalesces concurrent acceptance requests", async () => {
136212
const created = await call("taskSuggestions.create", {
137213
title: "Add coverage",
@@ -348,7 +424,6 @@ describe("task suggestion gateway methods", () => {
348424
});
349425

350426
it("broadcasts when the bounded registry expires a pending suggestion", async () => {
351-
const taskIds: string[] = [];
352427
for (let index = 0; index < 100; index += 1) {
353428
const created = await call("taskSuggestions.create", {
354429
title: `Follow up ${index}`,
@@ -357,9 +432,14 @@ describe("task suggestion gateway methods", () => {
357432
cwd: "/repo",
358433
sessionKey: "agent:main:main",
359434
});
360-
taskIds.push((requirePayload(created) as { taskId: string }).taskId);
435+
requirePayload(created);
361436
}
362437

438+
const previous = await call("taskSuggestions.list", {});
439+
const pending = (requirePayload(previous) as { suggestions: Array<{ id: string }> })
440+
.suggestions;
441+
const oldestPending = pending.at(-1);
442+
expect(oldestPending).toBeDefined();
363443
const replacement = await call("taskSuggestions.create", {
364444
title: "Latest follow up",
365445
prompt: "Complete the latest follow-up task.",
@@ -372,11 +452,80 @@ describe("task suggestion gateway methods", () => {
372452
expect(replacement.broadcast).toHaveBeenNthCalledWith(
373453
1,
374454
"task.suggestion",
375-
{ action: "resolved", taskId: taskIds[0], resolution: "expired" },
455+
{ action: "resolved", taskId: oldestPending?.id, resolution: "expired" },
376456
{ dropIfSlow: true },
377457
);
378458
const listed = await call("taskSuggestions.list", {});
379-
expect((requirePayload(listed) as { suggestions: unknown[] }).suggestions).toHaveLength(100);
459+
expect((requirePayload(listed) as { suggestions: unknown[] }).suggestions).toHaveLength(
460+
pending.length,
461+
);
462+
});
463+
464+
it("rejects impossible byte admission without evicting accepted or pending suggestions", async () => {
465+
const acceptingTaskIds: string[] = [];
466+
const largePrompt = "🦀".repeat(16_000);
467+
468+
try {
469+
for (let index = 0; index < 32; index += 1) {
470+
const created = await call("taskSuggestions.create", {
471+
title: `Running follow up ${index}`,
472+
prompt: largePrompt,
473+
tldr: "This accepted task is still starting.",
474+
cwd: "/repo",
475+
sessionKey: "agent:main:main",
476+
});
477+
const taskId = (requirePayload(created) as { taskId: string }).taskId;
478+
expect(beginTaskSuggestionAcceptance(taskId).status).toBe("claimed");
479+
acceptingTaskIds.push(taskId);
480+
}
481+
482+
const accepted = await call("taskSuggestions.create", {
483+
title: "Preserve accepted task",
484+
prompt: "Keep its accepted result available for retries.",
485+
tldr: "A rejected admission must not discard completed results.",
486+
cwd: "/repo",
487+
sessionKey: "agent:main:main",
488+
});
489+
const acceptedTaskId = (requirePayload(accepted) as { taskId: string }).taskId;
490+
expect(beginTaskSuggestionAcceptance(acceptedTaskId).status).toBe("claimed");
491+
completeTaskSuggestionAcceptance(acceptedTaskId, "agent:main:dashboard:accepted");
492+
493+
const pending = await call("taskSuggestions.create", {
494+
title: "Keep this follow up",
495+
prompt: "Do not discard this pending task.",
496+
tldr: "The operator has not accepted it yet.",
497+
cwd: "/repo",
498+
sessionKey: "agent:main:main",
499+
});
500+
const pendingTaskId = (requirePayload(pending) as { taskId: string }).taskId;
501+
const rejected = await call("taskSuggestions.create", {
502+
title: "One oversized follow up",
503+
prompt: largePrompt,
504+
tldr: "This valid task cannot fit beside protected tasks.",
505+
cwd: "/repo",
506+
sessionKey: "agent:main:main",
507+
});
508+
509+
expect(rejected.response?.[0]).toBe(false);
510+
expect(rejected.response?.[2]).toMatchObject({
511+
code: "UNAVAILABLE",
512+
message: "task suggestion registry is busy",
513+
retryable: true,
514+
});
515+
expect(rejected.broadcast).not.toHaveBeenCalled();
516+
expect(beginTaskSuggestionAcceptance(acceptedTaskId)).toEqual({
517+
status: "accepted",
518+
sessionKey: "agent:main:dashboard:accepted",
519+
});
520+
const listed = await call("taskSuggestions.list", {});
521+
expect(
522+
(requirePayload(listed) as { suggestions: Array<{ id: string }> }).suggestions,
523+
).toEqual([expect.objectContaining({ id: pendingTaskId })]);
524+
} finally {
525+
for (const taskId of acceptingTaskIds) {
526+
expect(abandonTaskSuggestionAcceptance(taskId)).toBe(true);
527+
}
528+
}
380529
});
381530

382531
it("rejects a new suggestion when every bounded registry entry is accepting", async () => {

‎src/gateway/task-suggestion-registry.ts‎

Lines changed: 36 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,34 @@ type CreateTaskSuggestionResult =
2525
| { status: "created"; suggestion: TaskSuggestion; evictedPendingTaskIds: string[] }
2626
| { status: "full" };
2727

28-
function evictTaskSuggestion(): string | null | undefined {
29-
for (const [taskId, record] of suggestions) {
30-
if (record.status === "accepted" || record.status === "dismissed") {
31-
retainedSuggestionBytes -= retainedBytesForSuggestion(record.suggestion);
32-
suggestions.delete(taskId);
33-
return null;
28+
function planTaskSuggestionEvictions(
29+
suggestionBytes: number,
30+
): Array<[string, TaskSuggestionRecord]> | null {
31+
let projectedCount = suggestions.size + 1;
32+
let projectedBytes = retainedSuggestionBytes + suggestionBytes + 1;
33+
const planned: Array<[string, TaskSuggestionRecord]> = [];
34+
// Accepted replay is best effort: protect it behind pending work, but never
35+
// let completed entries permanently prevent new suggestions from starting.
36+
for (const status of ["dismissed", "pending", "accepted"] as const) {
37+
for (const [taskId, record] of suggestions) {
38+
if (
39+
projectedCount <= MAX_TASK_SUGGESTIONS &&
40+
projectedBytes <= MAX_TASK_SUGGESTION_RETAINED_BYTES
41+
) {
42+
return planned;
43+
}
44+
if (record.status !== status) {
45+
continue;
46+
}
47+
planned.push([taskId, record]);
48+
projectedCount -= 1;
49+
projectedBytes -= retainedBytesForSuggestion(record.suggestion);
3450
}
3551
}
36-
for (const [taskId, record] of suggestions) {
37-
if (record.status === "pending") {
38-
retainedSuggestionBytes -= retainedBytesForSuggestion(record.suggestion);
39-
suggestions.delete(taskId);
40-
return taskId;
41-
}
42-
}
43-
return undefined;
52+
return projectedCount <= MAX_TASK_SUGGESTIONS &&
53+
projectedBytes <= MAX_TASK_SUGGESTION_RETAINED_BYTES
54+
? planned
55+
: null;
4456
}
4557

4658
/** Records one suggestion without starting work. IDs intentionally vanish on restart. */
@@ -58,19 +70,17 @@ export function createTaskSuggestion(
5870
createdAt: Date.now(),
5971
};
6072
const suggestionBytes = retainedBytesForSuggestion(suggestion);
73+
const plannedEvictions = planTaskSuggestionEvictions(suggestionBytes);
74+
if (!plannedEvictions) {
75+
return { status: "full" };
76+
}
6177
const evictedPendingTaskIds: string[] = [];
62-
while (
63-
suggestions.size >= MAX_TASK_SUGGESTIONS ||
64-
retainedSuggestionBytes + suggestionBytes + 1 > MAX_TASK_SUGGESTION_RETAINED_BYTES
65-
) {
66-
const evictedTaskId = evictTaskSuggestion();
67-
if (evictedTaskId === undefined) {
68-
// All retained tasks are in-flight acceptances. Reject new work instead
69-
// of losing either its UI card or an acceptance's idempotency result.
70-
return { status: "full" };
71-
}
72-
if (evictedTaskId) {
73-
evictedPendingTaskIds.push(evictedTaskId);
78+
// Commit only a complete plan; failed admissions must not discard state.
79+
for (const [taskId, record] of plannedEvictions) {
80+
retainedSuggestionBytes -= retainedBytesForSuggestion(record.suggestion);
81+
suggestions.delete(taskId);
82+
if (record.status === "pending") {
83+
evictedPendingTaskIds.push(taskId);
7484
}
7585
}
7686
suggestions.set(suggestion.id, { status: "pending", suggestion });

0 commit comments

Comments
 (0)