diff --git a/packages/opencode/src/cli/cmd/run-accounting.ts b/packages/opencode/src/cli/cmd/run-accounting.ts index ecd915bcb3..22e70c8d22 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,21 @@ 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. 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 39ec739b81..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,8 +1326,32 @@ 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 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 ( + charged && !committedRecovery && !budgetAborted && + maxTurns && accounting.turnCount > maxTurns && + (!timeExhausted() || options?.turnLimit !== undefined) + ) { + await abortOnTurnBudget(sessionID) + 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..c392d81013 100644 --- a/packages/opencode/test/cli/run-accounting.test.ts +++ b/packages/opencode/test/cli/run-accounting.test.ts @@ -64,6 +64,50 @@ 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") + // 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") + expect(acc.onCompactionRecovered()).toBe(true) + 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") + 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" }) + expect(acc.onCompactionRecovered()).toBe(false) + 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") + expect(acc.onCompactionRecovered()).toBe(true) // unproductive cycle: charged + expect(acc.turnCount).toBe(1) + acc.onStepStart("msg_work") + acc.onSessionError("ContextOverflowError", "too long") + expect(acc.onCompactionRecovered()).toBe(false) // a counted step ran since the last recovery + expect(acc.turnCount).toBe(2) + }) }) describe("RunAccounting termination attribution (E4)", () => {