Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
db553c8
fix: `run --max-turns` charges completed steps, not retried attempts
anandgupta42 Nov 21, 2026
b2aa0bc
test: real-processor retry-cap test; fix header comment wrap
anandgupta42 Nov 21, 2026
f3d86f7
test: the attached fake answers the soft time-budget reminder without…
anandgupta42 Nov 21, 2026
e44eab2
refactor: drop the side-effect-free step-start wrapper; one compactio…
anandgupta42 Nov 21, 2026
60ee544
test: drop the wall-clock assertion from the time-budget bound test
anandgupta42 Nov 21, 2026
a1b6100
test: a post-budget compaction step is never charged or stopped; name…
anandgupta42 Nov 21, 2026
e70fc3e
docs: name --time-budget as the bound for repeated overflow-and-compa…
anandgupta42 Nov 21, 2026
dd48417
fix: `--max-turns` also stops runs whose step attempts never finish
anandgupta42 Nov 21, 2026
c468841
fix: the attempt-backstop message no longer claims the turn limit was…
anandgupta42 Nov 21, 2026
47c6c8a
fix: a step cut short by context overflow still costs its turn
anandgupta42 Nov 21, 2026
d1f4524
fix: overflows rejected before a step starts count toward the attempt…
anandgupta42 Nov 21, 2026
e8f89b6
fix: the attempt backstop also stops a committed echo, and skips the …
anandgupta42 Nov 21, 2026
134e8aa
fix: a pre-step overflow after the turn limit stops the run; one abor…
anandgupta42 Nov 21, 2026
d22b2d7
refactor: drop the attempt backstop; keep charging a step cut short b…
anandgupta42 Nov 21, 2026
3065db0
fix: an idle session closes the open step; unit tests record each att…
anandgupta42 Nov 21, 2026
0cbcee0
test: the endless-attempts test requires attempts after the initial b…
anandgupta42 Nov 21, 2026
72137c3
fix: a retry closes the failed attempt; help says harness turns count…
anandgupta42 Nov 21, 2026
60bb2b9
test: the attached fake counts retries per assistant step, like the p…
anandgupta42 Nov 21, 2026
efb9752
fix: a step that compaction replaces is charged regardless of event o…
anandgupta42 Nov 21, 2026
db16e07
test: share the fake's compaction-step and assistant-message helpers
anandgupta42 Nov 21, 2026
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
64 changes: 52 additions & 12 deletions packages/opencode/src/cli/cmd/run-accounting.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Fork-only helpers for the `run` command:
// - honest turn accounting: compaction-machinery steps must not consume the
// --max-turns budget. `step-start` parts carry only messageID/sessionID, so
// the owning message's summary flag is resolved via a lookup populated from
// `message.updated` events (the assistant message row is persisted — and its
// event published — before its first step-start part streams).
// --max-turns budget, and a turn is charged when a step completes, so a
// failed or retried attempt costs nothing. Step parts carry only
// messageID/sessionID, so the owning message's summary flag is resolved via
// a lookup populated from `message.updated` events (the assistant message
// row is persisted — and its event published — before its first
// step-start part streams).
// - dual-attribution termination logging: every run records TWO independent
// fields instead of one rc: `why_model_stopped` and `why_harness_stopped`,
// so model-looping, tight budgets, and harness errors stop being conflated
Expand Down Expand Up @@ -92,6 +94,9 @@ export function createRecoverableOverflowTraceErrors() {
export function create() {
const summaryMessages = new Set<string>()
let turnCount = 0
// altimate_change start — the non-compaction step streaming now, until it finishes
let openAttempt = false
// altimate_change end
// altimate_change start — track the active request's committed echo turn allowance
let committedAnswer = false
// altimate_change end
Expand Down Expand Up @@ -166,23 +171,50 @@ export function create() {
else summaryMessages.delete(info.id)
},
isCompactionStep,
/**
* Count a step-start toward the turn budget unless it belongs to a
* compaction-machinery message. Returns true when the step was counted.
*/
onStepStart(messageID: string): boolean {
if (isCompactionStep(messageID)) return false
turnCount++
return true
// altimate_change start — charge the turn budget on step-finish, not step-start
// A step-start opens an attempt; the processor retries a failed attempt
// (up to SessionRetry.RETRY_MAX_ATTEMPTS per step), and each retry streams
// its own step-start but only the attempt that completes streams a
// step-finish. Charging on start billed every failed attempt as a turn.
// A step that ends without a step-finish is free when a retry or idle
// closes it (a failed or retried attempt). A step still open when compaction
// replaces it, or cut short by a context-overflow error, is charged as
// before, so overflow-and-compact cycles stay bounded by --max-turns
// whichever of the overflow error and the compaction start arrives first.
// The processor's retry cap bounds retried attempts.
// `turnCount` is therefore the number of COMPLETED non-compaction steps;
// harness-injected generations (idle-done challenge, continuation,
// silent-turn reply) are real assistant steps and are charged the same way.
/** Track the step now streaming; a compaction step closes any unfinished one. */
onStepAttempt(messageID: string) {
if (!isCompactionStep(messageID)) {
openAttempt = true
return
}
// Compaction replacing a step that never finished: that step was cut short.
if (openAttempt) turnCount++
openAttempt = false
},
/** No step is streaming any more (the session went idle, or a retry began). */
closeOpenStep() {
openAttempt = false
},
/** Completed non-compaction assistant steps. */
get turnCount() {
return turnCount
},
/** True when `maxTurns` completed steps already ran, so no further step may start. */
turnBudgetReached(maxTurns: number | undefined): boolean {
return maxTurns !== undefined && maxTurns > 0 && turnCount >= maxTurns
},
onStepFinish(messageID: string, reason: string | undefined) {
if (isCompactionStep(messageID)) return
turnCount++
openAttempt = false
lastFinishReason = reason
lastFinishMessageID = messageID
},
// altimate_change end
onText(messageID: string, text: string, synthetic = false) {
if (isCompactionStep(messageID)) return
if (synthetic) return
Expand Down Expand Up @@ -224,6 +256,14 @@ export function create() {
}
if (errorName === "ContextOverflowError") {
pendingContextOverflow = true
// altimate_change start — a step cut short by context overflow still costs its turn
// Counted from the session event only, so the prompt result repeating the
// same overflow cannot charge it again.
if (openAttempt && source === "event") {
turnCount++
openAttempt = false
}
// altimate_change end
return
}
// the idle-done challenge is delivered by aborting the in-flight
Expand Down
28 changes: 22 additions & 6 deletions packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,8 @@ export const RunCommand = cmd({
// altimate_change start — budget limits for CI/enterprise governance
.option("max-turns", {
type: "number",
describe: "maximum assistant work turns; allows one committed-answer echo, or one best-effort reply after a budget abort",
describe:
"maximum completed assistant work turns, including harness follow-up turns (a failed or retried attempt is not counted); allows one committed-answer echo, or one best-effort reply after a budget abort",
})
// altimate_change start — wall-clock work budget, with a separate finalization allowance
.option("time-budget", {
Expand Down Expand Up @@ -1136,25 +1137,29 @@ You are speaking to a non-technical business executive. Follow these rules stric
}

if (part.type === "step-start") {
// altimate_change start — one compaction lookup serves output, `step` and the turn budget
const compactionStep = accounting.isCompactionStep(part.messageID)
// altimate_change end
// altimate_change start — `--output` keeps only the last step's text (see run-output.ts)
outputParts.stepStart(accounting.isCompactionStep(part.messageID))
outputParts.stepStart(compactionStep)
// altimate_change end
// altimate_change start — see `step` (#1334). Compaction steps do not count,
// as for the turn budget below: one running after the final answer would
// otherwise move `step` past `lastTextStep` and ask for a reply the model
// already gave. (release review)
if (!accounting.isCompactionStep(part.messageID)) step++
if (!compactionStep) step++
// altimate_change end
// altimate_change start — enforce max-turns budget
// compaction-machinery steps are excluded from turn accounting —
// the owning message's agent is resolved via the message.updated lookup
// above, so compacting models are not differentially charged turns.
const counted = accounting.onStepStart(part.messageID)
// Turns are charged on step-finish: a step may start only while fewer
// than maxTurns steps have completed, so a retried attempt is free.
const requestID = requestOwnership.ownerOf(part.messageID)
const committedAnswer = requestID !== undefined && committedRequests.has(requestID)
// altimate_change start — the time-budget abort already owns the interrupted work phase
if (
counted && maxTurns && accounting.turnCount > maxTurns && !committedAnswer && !budgetAborted &&
!compactionStep && accounting.turnBudgetReached(maxTurns) && !committedAnswer && !budgetAborted &&
(!timeExhausted() || options?.turnLimit !== undefined)
) {
stopTimeBudget()
Expand All @@ -1169,6 +1174,7 @@ You are speaking to a non-technical business executive. Follow these rules stric
// Drain the ordered abort/error/idle tail before starting another phase.
continue
}
accounting.onStepAttempt(part.messageID)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// altimate_change end
if (emit("step_start", { part })) continue
}
Expand Down Expand Up @@ -1353,6 +1359,14 @@ You are speaking to a non-technical business executive. Follow these rules stric
}
// altimate_change end

// altimate_change start — a retry begins: the failed attempt is over and stays uncharged
if (
event.type === "session.status" &&
event.properties.sessionID === sessionID &&
event.properties.status.type === "retry"
)
accounting.closeOpenStep()
// altimate_change end
if (
event.type === "session.status" &&
event.properties.sessionID === sessionID &&
Expand All @@ -1363,6 +1377,7 @@ You are speaking to a non-technical business executive. Follow these rules stric
// altimate_change end
// altimate_change start — idle gaps are not active work; continuations retain the same start time
workActive = false
accounting.closeOpenStep()
// altimate_change end
break
}
Expand Down Expand Up @@ -2049,7 +2064,8 @@ You are speaking to a non-technical business executive. Follow these rules stric
// A silent stop exactly at the work limit has no in-flight generation to
// abort. Enter finalization directly instead of spending a reply just to
// discover that it exceeds the same budget.
if (!answered() && assistantStarted && !accounting.fatal && args.maxTurns && accounting.turnCount >= args.maxTurns) {
// The same completed-step count the in-loop budget check uses.
if (!answered() && assistantStarted && !accounting.fatal && accounting.turnBudgetReached(args.maxTurns)) {
accounting.onBudgetExhausted()
error = `Budget exceeded: reached ${args.maxTurns} assistant turn${args.maxTurns !== 1 ? "s" : ""} limit`
if (!emit("budget_exhausted", { limit: args.maxTurns })) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,10 @@ Options:
statement (1-indexed) [number]
--trace enable session tracing (default: true, disable with
--no-trace) [boolean] [default: true]
--max-turns maximum assistant work turns; allows one committed-answer
echo, or one best-effort reply after a budget abort [number]
--max-turns maximum completed assistant work turns, including harness
follow-up turns (a failed or retried attempt is not counted);
allows one committed-answer echo, or one best-effort reply
after a budget abort [number]
--time-budget maximum time in seconds including startup (env:
ALTIMATE_RUN_TIME_BUDGET_S); bounded finalization may follow
[number]
Expand Down
Loading
Loading