From cbfbbb9a8a03971a6aea408a332acbfc12c7bb49 Mon Sep 17 00:00:00 2001 From: bfs2021 <101915083+bfs2021@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:35:59 +0800 Subject: [PATCH 1/2] fix: bound pre-step overflow-and-compact cycles under --max-turns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A request the provider rejects as a context overflow before any step starts hands off to compaction, whose steps are excluded from turn accounting — so a run where every request overflows pre-step never reaches the step-start budget check and loops indefinitely when no time budget is set. Charge each unproductive recovery (an overflow closed by compaction with no counted step since the last recovery) one turn toward the budget, and enforce the budget at the session.compacted boundary where the cycle is visible. Recoveries that follow counted work steps stay free, a compaction without a pending overflow stays free, and a step cut short mid-stream still costs its counted step. --- .../opencode/src/cli/cmd/run-accounting.ts | 15 +++++++ packages/opencode/src/cli/cmd/run.ts | 24 +++++++++++ .../opencode/test/cli/run-accounting.test.ts | 43 +++++++++++++++++++ 3 files changed, 82 insertions(+) diff --git a/packages/opencode/src/cli/cmd/run-accounting.ts b/packages/opencode/src/cli/cmd/run-accounting.ts index ecd915bcb3..39ab288a09 100644 --- a/packages/opencode/src/cli/cmd/run-accounting.ts +++ b/packages/opencode/src/cli/cmd/run-accounting.ts @@ -124,6 +124,10 @@ export function create() { // An overflow is recoverable only after compaction actually completes. In // particular, compaction can be disabled or its own summarizer can fail. let pendingContextOverflow = false + // Counted (non-compaction) steps since the last completed compaction. A + // recovery that closes an overflow with none of these is an unproductive + // overflow-and-compact cycle. + let countedStepsSinceRecovery = 0 // State for the one-shot confirm-DONE prompt. Attribution follows the // actual challenge request lifetime, not step counts: one reply may use // several tool-call steps before its final DONE assertion. @@ -173,6 +177,7 @@ export function create() { onStepStart(messageID: string): boolean { if (isCompactionStep(messageID)) return false turnCount++ + countedStepsSinceRecovery++ return true }, get turnCount() { @@ -248,7 +253,17 @@ export function create() { // altimate_change end /** Confirm that a previously reported context overflow recovered. */ onCompactionRecovered() { + // A recovery that closes an overflow without a single counted step since + // the last one is an unproductive overflow-and-compact cycle: the next + // request starts without ever streaming a counted step-start (a pre-step + // overflow publishes nothing), so the step-start budget check never sees + // the cycle and `--max-turns` cannot bound it. Charge one turn per + // unproductive cycle. Recoveries that follow real work steps stay free — + // a step cut short mid-stream already cost its turn — and so does a + // compaction that completes without a pending overflow. + if (pendingContextOverflow && countedStepsSinceRecovery === 0) turnCount++ pendingContextOverflow = false + countedStepsSinceRecovery = 0 }, // altimate_change start — retain turn-limit behavior while allowing an answered time-limit finalization onBudgetExhausted(kind: "turn" | "time" = "turn") { diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index 39ec739b81..9fdd2a09df 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -1307,6 +1307,30 @@ You are speaking to a non-technical business executive. Follow these rules stric if (event.type === "session.compacted" && event.properties.sessionID === sessionID) { accounting.onCompactionRecovered() recoverableOverflowTraceErrors.recover() + // altimate_change start — enforce the turn budget at the recovery boundary + // A pre-step overflow recovered by compaction starts the next request + // without streaming any counted step-start, so an every-request- + // overflows run never reaches the step-start budget check and loops + // overflow -> compaction forever. Each unproductive cycle is charged + // a turn (see onCompactionRecovered); abort here, where the cycle is + // visible, instead of waiting for a step that never comes. + if ( + !budgetAborted && + maxTurns && + accounting.turnCount > maxTurns && + (!timeExhausted() || options?.turnLimit !== undefined) + ) { + stopTimeBudget() + budgetAborted = true + accounting.onBudgetExhausted() + error = `Budget exceeded: reached ${maxTurns} assistant turn${maxTurns !== 1 ? "s" : ""} limit` + if (!emit("budget_exhausted", { limit: maxTurns })) { + UI.println(UI.Style.TEXT_DANGER_BOLD + "!", UI.Style.TEXT_NORMAL + ` ${error}. Aborting session.`) + } + await sdk.session.abort({ sessionID }, { signal: options?.signal }) + continue + } + // altimate_change end } // altimate_change end diff --git a/packages/opencode/test/cli/run-accounting.test.ts b/packages/opencode/test/cli/run-accounting.test.ts index 0338839614..dac1d2385f 100644 --- a/packages/opencode/test/cli/run-accounting.test.ts +++ b/packages/opencode/test/cli/run-accounting.test.ts @@ -64,6 +64,49 @@ describe("RunAccounting turn accounting", () => { acc.onText("msg_compact", "summary text\nDONE") expect(acc.termination().why_model_stopped).toBe("stop") }) + + test("an overflow recovered with no counted step since the last recovery costs one turn per cycle", () => { + const acc = RunAccounting.create() + acc.onAssistantMessage({ id: "msg_compact", agent: "compaction", summary: true }) + // every request overflows before any step starts; only compaction machinery streams + acc.onSessionError("ContextOverflowError", "too long") + acc.onStepStart("msg_compact") + acc.onCompactionRecovered() + expect(acc.turnCount).toBe(1) + acc.onSessionError("ContextOverflowError", "too long") + acc.onCompactionRecovered() + expect(acc.turnCount).toBe(2) + }) + + test("a recovery that follows counted work steps is free", () => { + const acc = RunAccounting.create() + acc.onAssistantMessage({ id: "msg_work", agent: "build" }) + acc.onStepStart("msg_work") + acc.onStepStart("msg_work") + acc.onSessionError("ContextOverflowError", "too long") + acc.onCompactionRecovered() + expect(acc.turnCount).toBe(2) + }) + + test("a compaction without a pending overflow is free", () => { + const acc = RunAccounting.create() + acc.onAssistantMessage({ id: "msg_work", agent: "build" }) + acc.onCompactionRecovered() + expect(acc.turnCount).toBe(0) + }) + + test("work steps after a charged cycle make the next recovery free again", () => { + const acc = RunAccounting.create() + acc.onAssistantMessage({ id: "msg_compact", agent: "compaction", summary: true }) + acc.onAssistantMessage({ id: "msg_work", agent: "build" }) + acc.onSessionError("ContextOverflowError", "too long") + acc.onCompactionRecovered() // unproductive cycle: charged + expect(acc.turnCount).toBe(1) + acc.onStepStart("msg_work") + acc.onSessionError("ContextOverflowError", "too long") + acc.onCompactionRecovered() // a counted step ran since the last recovery + expect(acc.turnCount).toBe(2) + }) }) describe("RunAccounting termination attribution (E4)", () => { From 545228a126df78d39490f059531914dd3fa37535 Mon Sep 17 00:00:00 2001 From: bfs2021 <101915083+bfs2021@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:11:14 +0800 Subject: [PATCH 2/2] fix: preserve the committed-answer echo exemption at the recovery boundary Review follow-up for #1813 (cubic P1, CodeRabbit, kilo): the new session.compacted budget check did not carry the committed-answer exemption the step-start check grants the echo, so a committed echo that overflows after starting could be reported as budget exhaustion instead of publishing the stored answer. - onCompactionRecovered() now reports whether the unproductive charge fired; the recovery check aborts only when the charge fired and the recovering request is not a committed answer. Productive recoveries stay governed by the step-start check on the next counted step. - extract one shared abortOnTurnBudget() so the step-start and recovery enforcement points state the budget contract once and cannot drift. - the pending overflow's owning request is captured when the error surfaces (compaction rows emit no request boundary, so the active request is still the overflowing one). - accounting tests assert the charge-reporting contract. Signed-off-by: bfs2021 <101915083+bfs2021@users.noreply.github.com> --- .../opencode/src/cli/cmd/run-accounting.ts | 8 ++- packages/opencode/src/cli/cmd/run.ts | 69 ++++++++++++------- .../opencode/test/cli/run-accounting.test.ts | 13 ++-- 3 files changed, 58 insertions(+), 32 deletions(-) diff --git a/packages/opencode/src/cli/cmd/run-accounting.ts b/packages/opencode/src/cli/cmd/run-accounting.ts index 39ab288a09..22e70c8d22 100644 --- a/packages/opencode/src/cli/cmd/run-accounting.ts +++ b/packages/opencode/src/cli/cmd/run-accounting.ts @@ -260,10 +260,14 @@ export function create() { // the cycle and `--max-turns` cannot bound it. Charge one turn per // unproductive cycle. Recoveries that follow real work steps stay free — // a step cut short mid-stream already cost its turn — and so does a - // compaction that completes without a pending overflow. - if (pendingContextOverflow && countedStepsSinceRecovery === 0) turnCount++ + // compaction that completes without a pending overflow. Returns whether + // the unproductive charge fired, so the caller can enforce the turn + // budget at the exact recovery where the cycle became visible. + const unproductive = pendingContextOverflow && countedStepsSinceRecovery === 0 + if (unproductive) turnCount++ pendingContextOverflow = false countedStepsSinceRecovery = 0 + return unproductive }, // altimate_change start — retain turn-limit behavior while allowing an answered time-limit finalization onBudgetExhausted(kind: "turn" | "time" = "turn") { diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index 9fdd2a09df..49760ba8fa 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -987,6 +987,26 @@ You are speaking to a non-technical business executive. Follow these rules stric // altimate_change start — max-turns budget enforcement (count kept in accounting) const maxTurns = options?.turnLimit ?? args.maxTurns let budgetAborted = false + // The request whose ContextOverflowError is pending recovery, captured + // while the error surfaces (compaction rows emit no request boundary, so + // the active request is still the overflowing one). The + // session.compacted budget check consults it to keep the committed-answer + // exemption the step-start check grants the echo. + let overflowingRequestID: string | undefined + // One shared turn-budget abort for both enforcement points: stop the time + // budget, attribute the exhaustion, report, and abort the session. Two + // hand-maintained copies of this transition are how the step-start check + // and the recovery check drift apart. + const abortOnTurnBudget = async (sessionID: string) => { + stopTimeBudget() + budgetAborted = true + accounting.onBudgetExhausted() + error = `Budget exceeded: reached ${maxTurns} assistant turn${maxTurns !== 1 ? "s" : ""} limit` + if (!emit("budget_exhausted", { limit: maxTurns })) { + UI.println(UI.Style.TEXT_DANGER_BOLD + "!", UI.Style.TEXT_NORMAL + ` ${error}. Aborting session.`) + } + await sdk.session.abort({ sessionID }, { signal: options?.signal }) + } // altimate_change end // altimate_change start — parameterized stream @@ -1157,19 +1177,12 @@ You are speaking to a non-technical business executive. Follow these rules stric counted && maxTurns && accounting.turnCount > maxTurns && !committedAnswer && !budgetAborted && (!timeExhausted() || options?.turnLimit !== undefined) ) { - stopTimeBudget() - // altimate_change end - budgetAborted = true - accounting.onBudgetExhausted() - error = `Budget exceeded: reached ${maxTurns} assistant turn${maxTurns !== 1 ? "s" : ""} limit` - if (!emit("budget_exhausted", { limit: maxTurns })) { - UI.println(UI.Style.TEXT_DANGER_BOLD + "!", UI.Style.TEXT_NORMAL + ` ${error}. Aborting session.`) - } - await sdk.session.abort({ sessionID }, { signal: options?.signal }) + await abortOnTurnBudget(sessionID) // Drain the ordered abort/error/idle tail before starting another phase. continue } // altimate_change end + // altimate_change end if (emit("step_start", { part })) continue } @@ -1293,7 +1306,15 @@ You are speaking to a non-technical business executive. Follow these rules stric // altimate_change end // altimate_change end // altimate_change start — keep overflow trace failures recoverable only through compaction - if (props.error.name === "ContextOverflowError") recoverableOverflowTraceErrors.add(err) + if (props.error.name === "ContextOverflowError") { + recoverableOverflowTraceErrors.add(err) + // altimate_change start — remember whose request is pending recovery so + // the session.compacted budget check can honor the committed-answer + // exemption for the echo (the active request is still the overflowing + // one here: compaction rows emit no request boundary). + overflowingRequestID = requestOwnership.activeRequestID + // altimate_change end + } else error = error ? error + EOL + err : err // altimate_change end if (emit("error", { error: props.error })) continue @@ -1305,29 +1326,29 @@ You are speaking to a non-technical business executive. Follow these rules stric // completes. This event closes the pending-overflow accounting state; // without it (disabled/failed compaction) the run exits nonzero. if (event.type === "session.compacted" && event.properties.sessionID === sessionID) { - accounting.onCompactionRecovered() + const charged = accounting.onCompactionRecovered() + // altimate_change start — the recovering request decides the committed-answer exemption + const committedRecovery = overflowingRequestID !== undefined && committedRequests.has(overflowingRequestID) + overflowingRequestID = undefined recoverableOverflowTraceErrors.recover() + // altimate_change end // altimate_change start — enforce the turn budget at the recovery boundary // A pre-step overflow recovered by compaction starts the next request // without streaming any counted step-start, so an every-request- // overflows run never reaches the step-start budget check and loops // overflow -> compaction forever. Each unproductive cycle is charged - // a turn (see onCompactionRecovered); abort here, where the cycle is - // visible, instead of waiting for a step that never comes. + // a turn (see onCompactionRecovered); abort exactly when that charge + // fired — where the cycle is visible — instead of waiting for a step + // that never comes. The committed-answer echo keeps the exemption the + // step-start check grants it: its recovery must not cut off the stored + // answer before it is delivered. Productive recoveries stay governed by + // the step-start check on the next counted step, as before. if ( - !budgetAborted && - maxTurns && - accounting.turnCount > maxTurns && + charged && !committedRecovery && !budgetAborted && + maxTurns && accounting.turnCount > maxTurns && (!timeExhausted() || options?.turnLimit !== undefined) ) { - stopTimeBudget() - budgetAborted = true - accounting.onBudgetExhausted() - error = `Budget exceeded: reached ${maxTurns} assistant turn${maxTurns !== 1 ? "s" : ""} limit` - if (!emit("budget_exhausted", { limit: maxTurns })) { - UI.println(UI.Style.TEXT_DANGER_BOLD + "!", UI.Style.TEXT_NORMAL + ` ${error}. Aborting session.`) - } - await sdk.session.abort({ sessionID }, { signal: options?.signal }) + await abortOnTurnBudget(sessionID) continue } // altimate_change end diff --git a/packages/opencode/test/cli/run-accounting.test.ts b/packages/opencode/test/cli/run-accounting.test.ts index dac1d2385f..c392d81013 100644 --- a/packages/opencode/test/cli/run-accounting.test.ts +++ b/packages/opencode/test/cli/run-accounting.test.ts @@ -71,10 +71,11 @@ describe("RunAccounting turn accounting", () => { // every request overflows before any step starts; only compaction machinery streams acc.onSessionError("ContextOverflowError", "too long") acc.onStepStart("msg_compact") - acc.onCompactionRecovered() + // the charge is reported so the run loop can enforce the budget at this boundary + expect(acc.onCompactionRecovered()).toBe(true) expect(acc.turnCount).toBe(1) acc.onSessionError("ContextOverflowError", "too long") - acc.onCompactionRecovered() + expect(acc.onCompactionRecovered()).toBe(true) expect(acc.turnCount).toBe(2) }) @@ -84,14 +85,14 @@ describe("RunAccounting turn accounting", () => { acc.onStepStart("msg_work") acc.onStepStart("msg_work") acc.onSessionError("ContextOverflowError", "too long") - acc.onCompactionRecovered() + expect(acc.onCompactionRecovered()).toBe(false) expect(acc.turnCount).toBe(2) }) test("a compaction without a pending overflow is free", () => { const acc = RunAccounting.create() acc.onAssistantMessage({ id: "msg_work", agent: "build" }) - acc.onCompactionRecovered() + expect(acc.onCompactionRecovered()).toBe(false) expect(acc.turnCount).toBe(0) }) @@ -100,11 +101,11 @@ describe("RunAccounting turn accounting", () => { acc.onAssistantMessage({ id: "msg_compact", agent: "compaction", summary: true }) acc.onAssistantMessage({ id: "msg_work", agent: "build" }) acc.onSessionError("ContextOverflowError", "too long") - acc.onCompactionRecovered() // unproductive cycle: charged + expect(acc.onCompactionRecovered()).toBe(true) // unproductive cycle: charged expect(acc.turnCount).toBe(1) acc.onStepStart("msg_work") acc.onSessionError("ContextOverflowError", "too long") - acc.onCompactionRecovered() // a counted step ran since the last recovery + expect(acc.onCompactionRecovered()).toBe(false) // a counted step ran since the last recovery expect(acc.turnCount).toBe(2) }) })