Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/opencode/src/cli/cmd/run-accounting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -173,6 +177,7 @@ export function create() {
onStepStart(messageID: string): boolean {
if (isCompactionStep(messageID)) return false
turnCount++
countedStepsSinceRecovery++
return true
},
get turnCount() {
Expand Down Expand Up @@ -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") {
Expand Down
67 changes: 56 additions & 11 deletions packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down
44 changes: 44 additions & 0 deletions packages/opencode/test/cli/run-accounting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The enforcement path that ends the #1813 loop is untested

These cases pin the accounting charge, but nothing exercises the new session.compacted abort in run.ts — the part that actually stops the pre-step overflow cycle. Deleting the abort, or moving accounting.onCompactionRecovered() after the budget check, would leave this suite green. The existing subprocess suite (test/cli/run/budget-finalization.test.ts, mock LLM + --max-turns) can express the issue directly: have every request fail as a pre-step context overflow, let compaction succeed, and assert the run exits budget-exhausted with why_harness_stopped: "budget-exhausted" instead of looping.

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)", () => {
Expand Down
Loading