From 5788066510187e70e35518a1bd6945b4decd80fc Mon Sep 17 00:00:00 2001 From: Solveit Date: Fri, 20 Mar 2026 22:11:27 +0000 Subject: [PATCH] fix: clamp reserveTokensFloor to prevent negative memory flush threshold When reserveTokensFloor equals contextWindowTokens, the flush threshold becomes zero and memory flush never triggers. Clamp reserveTokens so the threshold always remains positive. Fixes #50611 --- src/auto-reply/reply/memory-flush.ts | 7 +++++-- src/auto-reply/reply/reply-state.test.ts | 13 ++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/auto-reply/reply/memory-flush.ts b/src/auto-reply/reply/memory-flush.ts index 95f6dbaa053..967f1007a0a 100644 --- a/src/auto-reply/reply/memory-flush.ts +++ b/src/auto-reply/reply/memory-flush.ts @@ -197,9 +197,12 @@ export function shouldRunMemoryFlush(params: { return false; } const contextWindow = Math.max(1, Math.floor(params.contextWindowTokens)); - const reserveTokens = Math.max(0, Math.floor(params.reserveTokensFloor)); const softThreshold = Math.max(0, Math.floor(params.softThresholdTokens)); - const threshold = Math.max(0, contextWindow - reserveTokens - softThreshold); + const reserveTokens = Math.min( + Math.max(0, Math.floor(params.reserveTokensFloor)), + Math.max(0, contextWindow - softThreshold - 1), + ); + const threshold = contextWindow - reserveTokens - softThreshold; if (threshold <= 0) { return false; } diff --git a/src/auto-reply/reply/reply-state.test.ts b/src/auto-reply/reply/reply-state.test.ts index f83d313e2d3..4db8c4c39d3 100644 --- a/src/auto-reply/reply/reply-state.test.ts +++ b/src/auto-reply/reply/reply-state.test.ts @@ -357,6 +357,17 @@ describe("shouldRunMemoryFlush", () => { }), ).toBe(false); }); + + it("triggers when reserveTokensFloor equals contextWindowTokens", () => { + expect( + shouldRunMemoryFlush({ + entry: { totalTokens: 199_000, compactionCount: 0 }, + contextWindowTokens: 200_000, + reserveTokensFloor: 200_000, + softThresholdTokens: 4_000, + }), + ).toBe(true); + }); }); describe("hasAlreadyFlushedForCurrentCompaction", () => { @@ -483,4 +494,4 @@ describe("incrementCompactionCount", () => { // totalTokens unchanged expect(stored[sessionKey].totalTokens).toBe(180_000); }); -}); +}); \ No newline at end of file