Skip to content

Commit dd972b8

Browse files
steipeteJerry-Xin
andauthored
fix: replies fail when memory flush is exhausted (#100618)
* fix(reply): recover from memory flush exhaustion Co-authored-by: 忻役 <[email protected]> Co-authored-by: Jerry-Xin <[email protected]> * test(reply): remove unused memory flush result --------- Co-authored-by: Jerry-Xin <[email protected]>
1 parent e183d66 commit dd972b8

16 files changed

Lines changed: 421 additions & 159 deletions

‎docs/concepts/compaction.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ and are pruned by normal session cleanup.
123123

124124
### Compaction notices
125125

126-
By default, compaction runs silently. Set `notifyUser` to show brief status messages when compaction starts and completes:
126+
By default, compaction runs silently. Set `notifyUser` to show brief status messages when compaction starts and completes, and to surface a degraded notice when a pre-compaction memory flush is exhausted but the reply still continues:
127127

128128
```json5
129129
{

‎docs/gateway/config-agents.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,7 @@ Periodic heartbeat runs.
631631
model: "openrouter/anthropic/claude-sonnet-4-6", // optional compaction-only model override
632632
truncateAfterCompaction: true, // rotate to a smaller successor JSONL after compaction
633633
maxActiveTranscriptBytes: "20mb", // optional preflight local compaction trigger
634-
notifyUser: true, // send brief notices when compaction starts and completes (default: false)
634+
notifyUser: true, // notices when compaction starts/completes and on memory-flush degradation (default: false)
635635
memoryFlush: {
636636
enabled: true,
637637
model: "ollama/qwen3:8b", // optional memory-flush-only model override
@@ -661,7 +661,7 @@ Periodic heartbeat runs.
661661
- `model`: optional `provider/model-id` or bare alias from `agents.defaults.models` for compaction summarization only. Bare aliases resolve before dispatch; configured literal model IDs retain precedence on collisions. Use this when the main session should keep one model but compaction summaries should run on another; when unset, compaction uses the session's primary model.
662662
- `truncateAfterCompaction`: rotates the active session JSONL after compaction so future turns load only the summary and unsummarized tail, while the previous full transcript remains archived. Prevents unbounded active transcript growth in long-running sessions. Default: `false`.
663663
- `maxActiveTranscriptBytes`: optional byte threshold (`number` or strings like `"20mb"`) that triggers normal local compaction before a run when the active JSONL grows past the threshold. Requires `truncateAfterCompaction` so successful compaction can rotate to a smaller successor transcript. Disabled when unset or `0`.
664-
- `notifyUser`: when `true`, sends brief notices to the user when compaction starts and when it completes (for example, "Compacting context..." and "Compaction complete"). Disabled by default to keep compaction silent.
664+
- `notifyUser`: when `true`, sends brief context-maintenance notices to the user: when compaction starts and completes (for example, "Compacting context..." and "Compaction complete"), and when a pre-compaction memory flush is exhausted so the reply continues in a degraded state (for example, "Memory maintenance temporarily failed; continuing your reply."). Disabled by default to keep these notices silent.
665665
- `memoryFlush`: silent agentic turn before auto-compaction to store durable memories. Set `model` to an exact provider/model such as `ollama/qwen3:8b` when this housekeeping turn should stay on a local model; the override does not inherit the active session fallback chain. `forceFlushTranscriptBytes` forces the flush when transcript file size reaches the threshold even if token counters are stale. Skipped when workspace is read-only.
666666

667667
### `agents.defaults.runRetries`

‎src/auto-reply/reply/agent-runner-direct-runtime-config.test.ts‎

Lines changed: 164 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { TemplateContext } from "../templating.js";
55
import { SILENT_REPLY_TOKEN } from "../tokens.js";
66
import { createTestFollowupRun } from "./agent-runner.test-fixtures.js";
77
import type { QueueSettings } from "./queue.js";
8+
import type { ReplyOperation } from "./reply-run-registry.js";
89
import { createMockTypingController } from "./test-helpers.js";
910

1011
const freshCfg = { runtimeFresh: true };
@@ -27,6 +28,8 @@ const createReplyMediaContextMock = vi.fn();
2728
const createReplyMediaPathNormalizerMock = vi.fn();
2829
const runPreflightCompactionIfNeededMock = vi.fn();
2930
const runMemoryFlushIfNeededMock = vi.fn();
31+
const runAgentTurnWithFallbackMock = vi.fn();
32+
const resetReplyRunSessionMock = vi.fn();
3033
const enqueueFollowupRunMock = vi.fn();
3134

3235
vi.mock("./agent-runner-utils.js", async () => {
@@ -67,6 +70,26 @@ vi.mock("./agent-runner-memory.js", () => ({
6770
runMemoryFlushIfNeeded: (...args: unknown[]) => runMemoryFlushIfNeededMock(...args),
6871
}));
6972

73+
vi.mock("./agent-runner-execution.js", async () => {
74+
const actual = await vi.importActual<typeof import("./agent-runner-execution.js")>(
75+
"./agent-runner-execution.js",
76+
);
77+
return {
78+
...actual,
79+
runAgentTurnWithFallback: (...args: unknown[]) => runAgentTurnWithFallbackMock(...args),
80+
};
81+
});
82+
83+
vi.mock("./agent-runner-session-reset.js", async () => {
84+
const actual = await vi.importActual<typeof import("./agent-runner-session-reset.js")>(
85+
"./agent-runner-session-reset.js",
86+
);
87+
return {
88+
...actual,
89+
resetReplyRunSession: (...args: unknown[]) => resetReplyRunSessionMock(...args),
90+
};
91+
});
92+
7093
vi.mock("./queue.js", async () => {
7194
const actual = await vi.importActual<typeof import("./queue.js")>("./queue.js");
7295
return {
@@ -88,6 +111,34 @@ function createTelegramSessionCtx(): TemplateContext {
88111
} as unknown as TemplateContext;
89112
}
90113

114+
function createReplyOperation(): ReplyOperation {
115+
return {
116+
key: "test",
117+
sessionId: "session-1",
118+
abortSignal: new AbortController().signal,
119+
resetTriggered: false,
120+
phase: "queued",
121+
result: null,
122+
setPhase: vi.fn(),
123+
updateSessionId: vi.fn(),
124+
hasOwnedSessionId: vi.fn(() => false),
125+
attachBackend: vi.fn(),
126+
detachBackend: vi.fn(),
127+
retainFailureUntilComplete: vi.fn(),
128+
complete: vi.fn(),
129+
completeThen: vi.fn((afterClear: () => void) => {
130+
afterClear();
131+
}),
132+
completeWithAfterClearBarrier: vi.fn(),
133+
fail: vi.fn(),
134+
freezeAbort: vi.fn(),
135+
abortByUser: vi.fn(),
136+
abortForRestart: vi.fn(),
137+
terminalRecovery: false,
138+
markTerminalRecovery: vi.fn(),
139+
};
140+
}
141+
91142
function createDirectRuntimeReplyParams({
92143
shouldFollowup,
93144
isActive,
@@ -173,14 +224,21 @@ describe("runReplyAgent runtime config", () => {
173224
createReplyMediaPathNormalizerMock.mockReset();
174225
runPreflightCompactionIfNeededMock.mockReset();
175226
runMemoryFlushIfNeededMock.mockReset();
227+
runAgentTurnWithFallbackMock.mockReset();
228+
resetReplyRunSessionMock.mockReset();
176229
enqueueFollowupRunMock.mockReset();
177230

178231
resolveQueuedReplyExecutionConfigMock.mockResolvedValue(freshCfg);
179232
resolveReplyToModeMock.mockReturnValue("all");
180233
createReplyToModeFilterForChannelMock.mockReturnValue((payload: unknown) => payload);
181234
createReplyMediaPathNormalizerMock.mockReturnValue((payload: unknown) => payload);
182235
runPreflightCompactionIfNeededMock.mockRejectedValue(sentinelError);
183-
runMemoryFlushIfNeededMock.mockResolvedValue(undefined);
236+
runMemoryFlushIfNeededMock.mockResolvedValue({ sessionEntry: undefined, outcome: "skipped" });
237+
runAgentTurnWithFallbackMock.mockResolvedValue({
238+
kind: "final",
239+
payload: { text: "main reply" },
240+
});
241+
resetReplyRunSessionMock.mockResolvedValue(false);
184242
});
185243

186244
it("resolves direct reply runs before early helpers read config", async () => {
@@ -247,62 +305,132 @@ describe("runReplyAgent runtime config", () => {
247305
expect(memoryCall.runtimePolicySessionKey).toBe(runtimePolicySessionKey);
248306
});
249307

250-
it("returns source-suppression-safe memory-flush error payloads before the main reply run", async () => {
308+
it("continues the main reply when memory flush reports visible maintenance errors", async () => {
251309
const { replyParams } = createDirectRuntimeReplyParams({
252310
shouldFollowup: false,
253311
isActive: false,
254312
});
255-
let observedReplyOperation: { freezeAbort: () => void } | undefined;
256-
replyParams.opts = { sourceReplyDeliveryMode: "message_tool_only" };
313+
const onBlockReply = vi.fn();
314+
replyParams.opts = { sourceReplyDeliveryMode: "message_tool_only", onBlockReply };
315+
resolveQueuedReplyExecutionConfigMock.mockResolvedValue({
316+
...freshCfg,
317+
agents: { defaults: { compaction: { notifyUser: true } } },
318+
});
257319
runPreflightCompactionIfNeededMock.mockResolvedValue(undefined);
258320
runMemoryFlushIfNeededMock.mockImplementation(
259321
async (params: {
260-
replyOperation: { freezeAbort: () => void };
261322
onVisibleErrorPayloads?: (payloads: Array<{ text?: string; isError?: boolean }>) => void;
262323
}) => {
263-
vi.spyOn(params.replyOperation, "freezeAbort");
264-
observedReplyOperation = params.replyOperation;
265-
expect(params.replyOperation.freezeAbort).not.toHaveBeenCalled();
266324
params.onVisibleErrorPayloads?.([
267325
{
268326
text: "⚠️ write failed: Memory flush writes are restricted to memory/2023-11-14.md; use that path only.",
269327
isError: true,
270328
},
271329
]);
272-
return undefined;
330+
return { sessionEntry: undefined, outcome: "failed" };
273331
},
274332
);
275333

276334
const result = await runReplyAgent(replyParams);
277335

278-
if (!observedReplyOperation) {
279-
throw new Error("expected memory flush reply operation");
280-
}
281-
expect(observedReplyOperation.freezeAbort).toHaveBeenCalledTimes(1);
282-
if (!result || Array.isArray(result)) {
283-
throw new Error("expected a single memory-flush error reply payload");
284-
}
285-
expect(result).toEqual({
286-
text: "⚠️ write failed: Memory flush writes are restricted to memory/2023-11-14.md; use that path only.",
287-
isError: true,
288-
replyToId: "msg-1",
289-
replyToCurrent: undefined,
290-
replyToTag: false,
291-
mediaUrl: undefined,
292-
mediaUrls: undefined,
293-
audioAsVoice: false,
336+
expect(result).toEqual({ text: "main reply" });
337+
expect(onBlockReply).not.toHaveBeenCalled();
338+
expect(runAgentTurnWithFallbackMock).toHaveBeenCalledOnce();
339+
});
340+
341+
it("rotates, rebinds, and optionally notifies when memory flush is exhausted", async () => {
342+
const { replyParams, followupRun } = createDirectRuntimeReplyParams({
343+
shouldFollowup: false,
344+
isActive: false,
345+
});
346+
const sessionKey = "agent:main:telegram:default:direct:test";
347+
const sessionEntry = {
348+
sessionId: "session-1",
349+
updatedAt: 1,
350+
compactionCount: 4,
351+
memoryFlushFailureCount: 2,
352+
};
353+
const sessionStore = { [sessionKey]: sessionEntry };
354+
replyParams.sessionKey = sessionKey;
355+
replyParams.storePath = "/tmp/sessions.json";
356+
replyParams.sessionEntry = sessionEntry;
357+
replyParams.sessionStore = sessionStore;
358+
resolveQueuedReplyExecutionConfigMock.mockResolvedValue({
359+
...freshCfg,
360+
agents: { defaults: { compaction: { notifyUser: true } } },
294361
});
295-
expect(getReplyPayloadMetadata(result)).toEqual({
296-
deliverDespiteSourceReplySuppression: true,
297-
replyDelivery: {
298-
chatType: "direct",
299-
replyToMode: "all",
362+
const onBlockReply = vi.fn();
363+
replyParams.opts = { onBlockReply };
364+
const updateSessionIdSpy = vi.fn();
365+
const replyOperation = createReplyOperation();
366+
replyOperation.updateSessionId = updateSessionIdSpy;
367+
replyParams.replyOperation = replyOperation;
368+
runPreflightCompactionIfNeededMock.mockImplementation(
369+
async (params: { sessionEntry?: unknown }) => params.sessionEntry,
370+
);
371+
runMemoryFlushIfNeededMock.mockImplementation(
372+
async (params: {
373+
sessionEntry?: typeof sessionEntry;
374+
onVisibleErrorPayloads?: (payloads: Array<{ text?: string; isError?: boolean }>) => void;
375+
}) => {
376+
params.onVisibleErrorPayloads?.([
377+
{
378+
text: "⚠️ Memory flush failed after 3 attempts; skipping for this cycle. It will retry after the next compaction.",
379+
isError: true,
380+
},
381+
]);
382+
return {
383+
sessionEntry: {
384+
...params.sessionEntry,
385+
memoryFlushFailureCount: 3,
386+
memoryFlushCompactionCount: 4,
387+
},
388+
outcome: "exhausted",
389+
};
300390
},
301-
replyDeliverySource: {
302-
channel: "telegram",
303-
accountId: "default",
391+
);
392+
resetReplyRunSessionMock.mockImplementation(async (params: unknown) => {
393+
const resetParams = params as {
394+
activeSessionEntry?: typeof sessionEntry;
395+
followupRun: typeof followupRun;
396+
onActiveSessionEntry: (entry: typeof sessionEntry) => void;
397+
onNewSession: (sessionId: string, sessionFile: string) => void;
398+
};
399+
const sessionFile = "/tmp/session-rotated.jsonl";
400+
const nextEntry = {
401+
...resetParams.activeSessionEntry,
402+
sessionId: "session-rotated",
403+
updatedAt: 1,
404+
memoryFlushFailureCount: 0,
405+
compactionCount: 0,
406+
};
407+
resetParams.followupRun.run.sessionId = nextEntry.sessionId;
408+
resetParams.followupRun.run.sessionFile = sessionFile;
409+
resetParams.onActiveSessionEntry(nextEntry);
410+
resetParams.onNewSession(nextEntry.sessionId, sessionFile);
411+
return true;
412+
});
413+
414+
const result = await runReplyAgent(replyParams);
415+
416+
expect(result).toEqual({ text: "main reply" });
417+
expect(resetReplyRunSessionMock).toHaveBeenCalledOnce();
418+
expect(resetReplyRunSessionMock.mock.calls[0]?.[0]).toMatchObject({
419+
options: {
420+
failureLabel: "memory flush exhaustion",
421+
cleanupTranscripts: false,
304422
},
423+
sessionKey,
424+
queueKey: "main",
305425
});
426+
expect(followupRun.run.sessionId).toBe("session-rotated");
427+
expect(updateSessionIdSpy).toHaveBeenCalledWith("session-rotated");
428+
expect(onBlockReply).toHaveBeenCalledWith(
429+
expect.objectContaining({
430+
text: "⚠️ Memory maintenance temporarily failed; continuing your reply.",
431+
}),
432+
);
433+
expect(runAgentTurnWithFallbackMock).toHaveBeenCalledOnce();
306434
});
307435

308436
it("does not start the main turn after cancellation during memory flush", async () => {
@@ -314,7 +442,7 @@ describe("runReplyAgent runtime config", () => {
314442
runMemoryFlushIfNeededMock.mockImplementation(
315443
async (params: { replyOperation: { abortByUser: () => boolean } }) => {
316444
expect(params.replyOperation.abortByUser()).toBe(true);
317-
return undefined;
445+
return { sessionEntry: undefined, outcome: "failed" };
318446
},
319447
);
320448

@@ -331,7 +459,7 @@ describe("runReplyAgent runtime config", () => {
331459
const codexMessage =
332460
"You've reached your Codex subscription usage limit. Codex did not return a reset time for this limit. Run /codex account for current usage details.";
333461
runPreflightCompactionIfNeededMock.mockRejectedValue(new Error(codexMessage));
334-
runMemoryFlushIfNeededMock.mockResolvedValue(undefined);
462+
runMemoryFlushIfNeededMock.mockResolvedValue({ sessionEntry: undefined, outcome: "skipped" });
335463

336464
const result = await runReplyAgent(replyParams);
337465

@@ -351,7 +479,7 @@ describe("runReplyAgent runtime config", () => {
351479
runPreflightCompactionIfNeededMock.mockRejectedValue(
352480
new Error("Preflight compaction required but failed: auth profile mismatch"),
353481
);
354-
runMemoryFlushIfNeededMock.mockResolvedValue(undefined);
482+
runMemoryFlushIfNeededMock.mockResolvedValue({ sessionEntry: undefined, outcome: "skipped" });
355483

356484
const result = await runReplyAgent(replyParams);
357485

0 commit comments

Comments
 (0)