From 76c2f085b6451a969adee827020109f236ef30dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9B=B7=E7=94=B5=E8=8A=BD=E8=A1=A3?= Date: Sun, 19 Apr 2026 01:03:44 -0400 Subject: [PATCH] fix(session): evaluate rotation against post-accumulation totals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `accumulateAndRotateSession` called `evaluateRotation` on the pre-accumulation `session` object, then re-read the row only inside the shouldRotate branch. A run that tipped the token threshold on its own usage would read "below threshold" on this cycle and wait a full additional run before rotating — long enough for the transcript to keep growing past the point where rotation was supposed to protect the context window. Read once after accumulation, evaluate against the fresh totals, rotate from the same object. No new queries, no new branches — the failure mode is just an off-by-one-run bug in the original read-eval-rotate sequence. --- src/main/worker/handlers/run-finished-helpers.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/worker/handlers/run-finished-helpers.ts b/src/main/worker/handlers/run-finished-helpers.ts index e37b8065..498218b6 100644 --- a/src/main/worker/handlers/run-finished-helpers.ts +++ b/src/main/worker/handlers/run-finished-helpers.ts @@ -116,14 +116,16 @@ export function accumulateAndRotateSession( event.outputTokens ?? 0, event.runId, ); - const rotationResult = sessionService.evaluateRotation(session); + // Re-read after accumulation: evaluateRotation must see the counts + // that include this run, otherwise a run that just crossed the + // threshold waits a full additional cycle to rotate — the exact + // failure mode that let transcripts balloon past the context window. + const updatedSession = db.getSessionById(agentRecord.sessionId); + if (!updatedSession) return; + const rotationResult = sessionService.evaluateRotation(updatedSession); if (rotationResult.shouldRotate) { - // Re-read to get updated counts after accumulation. - const updatedSession = db.getSessionById(agentRecord.sessionId); - if (updatedSession) { - sessionService.rotateSession(updatedSession); - logger.info(`[session] Rotated session for agent ${run.agentId}: ${rotationResult.reason}`); - } + sessionService.rotateSession(updatedSession); + logger.info(`[session] Rotated session for agent ${run.agentId}: ${rotationResult.reason}`); } }