GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request #1393 from developing-today/queue/6192-1380-balanc… · developing-today-forks/opencode@78c48b5

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src
      • model-route.ts
      • session/runner
        • step.ts
    • test
      • model-route.test.ts
      • session-step-failure.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/model-route.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/model-route.ts
+50-12Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,16 @@ const releasesHold = (hold: BalanceHold, snapshot: QuotaSnapshot.Snapshot): bool
870870
return hold.benchedBalance === null || snapshot.remaining > hold.benchedBalance
871871
}
872872

873+
/** Whether a snapshot shows its own grant was reclassified out of balance: it comes from
874+
* the hold's exact grant (same plan + window) but is no longer balance-shaped -- e.g. the
875+
* window gained `windowHours`, so derive() now reports a resetting usage window instead of
876+
* a point-in-time balance (#1380). The grant the hold benches on no longer exists as a
877+
* balance grant, so the hold is stale: the snapshot replaces it and gates (or not) as the
878+
* window's normal timed gate. A non-balance snapshot from any OTHER grant is not evidence
879+
* about this hold and never clears it. */
880+
const grantReclassified = (hold: BalanceHold, snapshot: QuotaSnapshot.Snapshot): boolean =>
881+
hold.grant !== undefined && grantIdentity(snapshot) === hold.grant && snapshot.balance !== true
882+
873883
type QuotaGateState = {
874884
snapshot: QuotaSnapshot.Snapshot
875885
target: Model.Ref
@@ -924,17 +934,22 @@ const observeCredentialQuotaState = (
924934
// A balance hold restored from its durable baseline after a restart has no in-memory
925935
// state: the persisted baseline re-arms the hold, like the provider path (#1014).
926936
const restored = previous ? undefined : restoredCredentialHold(credentialID)
927-
const hold = previous?.balanceHold ?? restored
937+
let hold = previous?.balanceHold ?? restored
928938
if (hold && !releasesHold(hold, snapshot)) {
929-
if (!previous)
930-
credentialQuota.set(credentialID, {
931-
snapshot,
932-
target,
933-
gated: true,
934-
balanceHold: hold,
935-
resetObservedAt: snapshot.observedAt,
936-
})
937-
return
939+
// A reclassified grant (#1380) releases the stale hold by no longer being a balance
940+
// grant: fall through and let this snapshot's normal timed gate replace it (the
941+
// persist step below clears the durable baseline because `hold` is still set).
942+
if (!grantReclassified(hold, snapshot)) {
943+
if (!previous)
944+
credentialQuota.set(credentialID, {
945+
snapshot,
946+
target,
947+
gated: true,
948+
balanceHold: hold,
949+
resetObservedAt: snapshot.observedAt,
950+
})
951+
return
952+
}
938953
}
939954
// Out-of-order delivery must not rewind the gate: an observation older than the retained
940955
// one carries no new information, even when it is still fresh — a below-limit reading
@@ -1036,7 +1051,7 @@ export const observeProviderQuota = (
10361051
}
10371052
: undefined)
10381053
if (hold) {
1039-
if (!releasesHold(hold, snapshot)) {
1054+
if (!releasesHold(hold, snapshot) && !grantReclassified(hold, snapshot)) {
10401055
if (!previous)
10411056
providerQuota.set(target.providerID, {
10421057
snapshot,
@@ -1047,6 +1062,8 @@ export const observeProviderQuota = (
10471062
})
10481063
return
10491064
}
1065+
// A reclassified grant (#1380) falls through: processing below replaces the balance
1066+
// skip with this snapshot's normal timed gate (or removes it when not full).
10501067
}
10511068
if (previous && snapshot.observedAt < previous.snapshot.observedAt) return
10521069
const full = QuotaSnapshot.isKnownFull(snapshot, now, currentConstants().quotaGate.balanceDeadThreshold)
@@ -1106,8 +1123,29 @@ export const reconcileQuotaGate = (providerID: string, livePlanIDs: ReadonlySet<
11061123
if (grantPlan !== undefined && !livePlanIDs.has(grantPlan)) removeAdjustment(credentialBaselineID(credentialID))
11071124
if (state.gated) logHealth(state.target, "quota-readmitted", `credential:${credentialID}`, undefined, credentialID)
11081125
}
1126+
// Durable balance baselines restored after a restart may have no in-memory state at
1127+
// all (#1380): the loops above only see live gate state, so a deleted plan's baseline
1128+
// record would otherwise persist -- and keep blocking its credential via the restored
1129+
// hold -- indefinitely. Clear those whose grant's plan no longer feeds the gate; a
1130+
// baseline whose grant plan is still live is a still-applicable depleted balance plan
1131+
// and keeps its hold.
1132+
for (const item of [...adjustments]) {
1133+
if (item.providerID !== providerID || item.credentialID === undefined) continue
1134+
if (item.id !== credentialBaselineID(item.credentialID) || item.balanceBaseline === undefined) continue
1135+
if (credentialQuota.has(item.credentialID)) continue
1136+
const grantPlan = item.balanceGrant?.split("\n")[0]
1137+
if (grantPlan !== undefined && !livePlanIDs.has(grantPlan)) removeAdjustment(item.id)
1138+
}
11091139
const state = providerQuota.get(providerID)
1110-
if (!state || state.snapshot.planID.startsWith("attempt:") || livePlanIDs.has(state.snapshot.planID)) return
1140+
if (!state) {
1141+
// Same restored-only gap on the provider scope: a balance skip record with no
1142+
// in-memory state whose grant's plan has ended is stale and clears here.
1143+
const record = adjustments.find((item) => item.id === `quota:${providerID}` && item.balanceBaseline !== undefined)
1144+
const grantPlan = record?.balanceGrant?.split("\n")[0]
1145+
if (record && grantPlan !== undefined && !livePlanIDs.has(grantPlan)) removeAdjustment(record.id)
1146+
return
1147+
}
1148+
if (state.snapshot.planID.startsWith("attempt:") || livePlanIDs.has(state.snapshot.planID)) return
11111149
providerQuota.delete(providerID)
11121150
const record = adjustments.find((item) => item.id === `quota:${providerID}`)
11131151
if (record) {
Collapse file

‎packages/core/src/session/runner/step.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/runner/step.ts
+32-6Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,34 @@ export const isQuotaFailure = (failure: AIError) => {
178178
return reason._tag === "RateLimit" && reason.http?.status === 429
179179
}
180180

181+
/** Text reporting that some limit is spent. Broad on purpose: it only opens the quota-failure
182+
* path (a timed gate); it does NOT by itself prove a balance was exhausted (#1380). */
183+
const exhaustionText = /insufficient credits|quota exhausted|usage limit exceeded|reached your .* limit/i
184+
185+
/** Text that explicitly reports credits/a balance spent — the only text (besides the
186+
* `QuotaExceeded` tag) that may classify a failure as balance exhaustion. Generic limit
187+
* wording ("reached your rate limit", "usage limit exceeded", "quota exhausted") is a
188+
* window/rate statement, not a balance statement (#1380). */
189+
const balanceExhaustionText =
190+
/insufficient credits|insufficient balance|insufficient funds|out of credits|credits? exhausted|balance exhausted|credit balance is too low|no credits (?:left|remaining)/i
191+
192+
/**
193+
* How a quota-path failure gates its pool (#1014, #1380): "balance-exhaustion" may install
194+
* an increase-only balance hold with no expiry, so it requires a `QuotaExceeded` tag or
195+
* explicitly credit/balance-specific text. A failure that only matches the broad
196+
* exhaustion wording — a plain HTTP 429 rate limit, say — classifies as "rate-limit" and
197+
* keeps its timed recovery even when the pool's last snapshot was balance-shaped.
198+
* Returns undefined when the failure does not enter the quota-failure path at all.
199+
*/
200+
export const quotaFailureClassification = (
201+
failure: AIError,
202+
): "balance-exhaustion" | "rate-limit" | undefined => {
203+
const reason = failure.reason as { _tag?: string; message?: string; body?: string }
204+
const text = `${reason.message ?? ""} ${reason.body ?? ""}`
205+
if (!isQuotaFailure(failure) && !exhaustionText.test(text) && !balanceExhaustionText.test(text)) return undefined
206+
return reason._tag === "QuotaExceeded" || balanceExhaustionText.test(text) ? "balance-exhaustion" : "rate-limit"
207+
}
208+
181209
/** Assistant messages that already switched credential for a provider (#6): at most one switch
182210
* per provider per assistant message, so a turn cannot cycle a provider's whole credential pool. */
183211
const credentialSwitches = new Set<string>()
@@ -440,19 +468,17 @@ export const make = Effect.gen(function* () {
440468
// then stops spending attempts — and collecting 429s — on an exhausted pool. The
441469
// text check catches providers that report exhaustion without a quota tag
442470
// (commandcode's "insufficient credits" arrives as an unknown-provider error).
443-
const exhaustionText = /insufficient credits|quota exhausted|usage limit exceeded|reached your .* limit/i
444-
const reason = llmFailure?.reason as { _tag?: string; message?: string; body?: string } | undefined
445-
const exhaustion = exhaustionText.test(`${reason?.message ?? ""} ${reason?.body ?? ""}`)
446-
if (failed && llmFailure && (isQuotaFailure(llmFailure) || exhaustion)) {
471+
const quotaClassification = failed && llmFailure ? quotaFailureClassification(llmFailure) : undefined
472+
if (llmFailure && quotaClassification) {
447473
const hint = failureHint(llmFailure)
448474
ModelRoute.observeQuotaFailure(
449475
input.model.ref,
450476
input.model.routing?.credentialID,
451477
hint.retryAfterMs === undefined ? undefined : Date.now() + hint.retryAfterMs,
452478
Date.now(),
453479
// Only a real exhaustion answer may install an increase-only balance hold; a
454-
// plain HTTP 429 rate limit keeps its stated timed recovery (#1014).
455-
reason?._tag === "QuotaExceeded" || exhaustion ? "balance-exhaustion" : "rate-limit",
480+
// plain HTTP 429 rate limit keeps its stated timed recovery (#1014, #1380).
481+
quotaClassification,
456482
)
457483
}
458484
// A success that advertised no limit headers replaces the serving credential's hold:
Collapse file

‎packages/core/test/model-route.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/model-route.test.ts
+106Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,112 @@ describe("ModelRoute quota bench reset", () => {
494494
expect(ModelRoute.activeAdjustments(now).some((item) => item.id === "quota-credential:cred-balance")).toBe(false)
495495
})
496496

497+
test("a reclassified window replaces a balance hold with its normal timed gate (#1380)", () => {
498+
const now = 500_000_000
499+
const resetAt = now + 5 * 3_600_000
500+
const balance = {
501+
planID: "credits-plan",
502+
window: "credits",
503+
providerID: "reset-provider",
504+
percent: 100,
505+
remaining: 0,
506+
resetAt: null,
507+
observedAt: now,
508+
stale: false,
509+
balance: true,
510+
}
511+
// The same plan + window after a windowHours reclassification: derive() no longer
512+
// reports it as a balance, so the snapshot is a resetting usage window.
513+
const windowed = {
514+
planID: "credits-plan",
515+
window: "credits",
516+
providerID: "reset-provider",
517+
percent: 100,
518+
remaining: 0,
519+
resetAt,
520+
observedAt: now + 1,
521+
stale: false,
522+
}
523+
ModelRoute.resetHealth()
524+
ModelRoute.observeCredentialQuota(target, "cred-reclass", balance, now)
525+
expect(ModelRoute.credentialQuotaBlocked("cred-reclass", now)).toEqual({ until: null })
526+
expect(
527+
ModelRoute.activeAdjustments(now).some((item) => item.id === "quota-credential:cred-reclass"),
528+
).toBe(true)
529+
530+
ModelRoute.observeCredentialQuota(target, "cred-reclass", windowed, now + 1)
531+
// The stale increase-only hold is gone: the credential is gated only until the
532+
// window's stated reset, and the durable baseline record is cleared.
533+
expect(ModelRoute.credentialQuotaBlocked("cred-reclass", now + 1)).toEqual({ until: resetAt })
534+
expect(
535+
ModelRoute.activeAdjustments(now + 1).some((item) => item.id === "quota-credential:cred-reclass"),
536+
).toBe(false)
537+
538+
// A non-balance snapshot from a DIFFERENT grant is not evidence about the hold.
539+
ModelRoute.resetHealth()
540+
ModelRoute.observeCredentialQuota(target, "cred-other", balance, now)
541+
ModelRoute.observeCredentialQuota(
542+
target,
543+
"cred-other",
544+
{ ...windowed, planID: "other-plan", window: "five-hours" },
545+
now + 1,
546+
)
547+
expect(ModelRoute.credentialQuotaBlocked("cred-other", now + 1)).toEqual({ until: null })
548+
549+
// The provider scope follows the same rule: its balance skip is replaced by the
550+
// window's timed skip, with no balance baseline left on the record.
551+
ModelRoute.resetHealth()
552+
ModelRoute.observeProviderQuota(target, balance, now)
553+
expect(
554+
ModelRoute.activeAdjustments(now).find((item) => item.id === "quota:reset-provider")?.balanceBaseline,
555+
).toBe(0)
556+
ModelRoute.observeProviderQuota(target, windowed, now + 1)
557+
const skip = ModelRoute.activeAdjustments(now + 1).find((item) => item.id === "quota:reset-provider")
558+
expect(skip?.balanceBaseline).toBeUndefined()
559+
expect(skip?.until).toBe(resetAt)
560+
})
561+
562+
test("reconciling clears restored balance baselines whose grant plan ended (#1380)", () => {
563+
const now = 550_000_000
564+
ModelRoute.resetHealth()
565+
// A baseline record restored after a restart, with no in-memory gate state: it blocks
566+
// its credential until a fed snapshot releases it -- or until reconciliation clears it.
567+
ModelRoute.addAdjustment({
568+
id: "quota-credential:cred-restored",
569+
match: "credential:cred-restored",
570+
action: "skip",
571+
balanceBaseline: 0,
572+
balanceGrant: "dead-plan\ncredits",
573+
credentialID: "cred-restored",
574+
providerID: "reset-provider",
575+
note: "credential balance exhausted; held until a fresh balance increase (durable baseline record -- not a selection skip)",
576+
})
577+
expect(ModelRoute.credentialQuotaBlocked("cred-restored", now)).toEqual({ until: null })
578+
// While the grant's plan still feeds the gate, the hold is still-applicable and stays.
579+
ModelRoute.reconcileQuotaGate("reset-provider", new Set(["dead-plan"]))
580+
expect(ModelRoute.credentialQuotaBlocked("cred-restored", now)).toEqual({ until: null })
581+
// The grant's plan is gone and no balance grant remains: the stale baseline clears.
582+
ModelRoute.reconcileQuotaGate("reset-provider", new Set(["live-plan"]))
583+
expect(ModelRoute.credentialQuotaBlocked("cred-restored", now)).toBeUndefined()
584+
expect(
585+
ModelRoute.activeAdjustments(now).some((item) => item.id === "quota-credential:cred-restored"),
586+
).toBe(false)
587+
588+
// The provider scope's restored balance skip follows the same rule.
589+
ModelRoute.addAdjustment({
590+
id: "quota:reset-provider",
591+
match: "reset-provider/",
592+
action: "skip",
593+
balanceBaseline: 0,
594+
balanceGrant: "dead-plan\ncredits",
595+
note: "quota exhausted (proactive snapshot); held until the stated reset",
596+
})
597+
ModelRoute.reconcileQuotaGate("reset-provider", new Set(["dead-plan"]))
598+
expect(ModelRoute.activeAdjustments(now).some((item) => item.id === "quota:reset-provider")).toBe(true)
599+
ModelRoute.reconcileQuotaGate("reset-provider", new Set(["live-plan"]))
600+
expect(ModelRoute.activeAdjustments(now).some((item) => item.id === "quota:reset-provider")).toBe(false)
601+
})
602+
497603
test("leaves the ladder unchanged for missing, invalid, elapsed or stale provider resets", () => {
498604
const now = 300_000_000
499605
const snapshots = [
Collapse file

‎packages/core/test/session-step-failure.test.ts‎

Copy file name to clipboardExpand all lines: packages/core/test/session-step-failure.test.ts
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
QuotaExceededError,
77
RateLimitError,
88
TransportError,
9+
UnknownProviderError,
910
} from "@opencode/ai"
1011
import { ModelRoute } from "@opencode/core/model-route"
1112
import { SessionStep } from "@opencode/core/session/runner/step"
@@ -78,6 +79,45 @@ describe("SessionStep.failureHint", () => {
7879
})
7980
})
8081

82+
describe("SessionStep.quotaFailureClassification", () => {
83+
test("a QuotaExceeded tag is balance exhaustion", () => {
84+
expect(
85+
SessionStep.quotaFailureClassification(error(new QuotaExceededError({ message: "out of quota" }))),
86+
).toBe("balance-exhaustion")
87+
})
88+
89+
test("explicitly credit/balance-specific text is balance exhaustion", () => {
90+
expect(
91+
SessionStep.quotaFailureClassification(error(new UnknownProviderError({ message: "insufficient credits" }))),
92+
).toBe("balance-exhaustion")
93+
expect(
94+
SessionStep.quotaFailureClassification(
95+
error(new UnknownProviderError({ message: "Your credit balance is too low" })),
96+
),
97+
).toBe("balance-exhaustion")
98+
})
99+
100+
test("generic limit text is only a rate limit, never balance exhaustion (#1380)", () => {
101+
expect(
102+
SessionStep.quotaFailureClassification(
103+
error(new RateLimitError({ message: "You have reached your rate limit" })),
104+
),
105+
).toBe("rate-limit")
106+
expect(
107+
SessionStep.quotaFailureClassification(error(new UnknownProviderError({ message: "usage limit exceeded" }))),
108+
).toBe("rate-limit")
109+
expect(
110+
SessionStep.quotaFailureClassification(error(new UnknownProviderError({ message: "quota exhausted" }))),
111+
).toBe("rate-limit")
112+
})
113+
114+
test("an ordinary failure does not enter the quota-failure path", () => {
115+
expect(
116+
SessionStep.quotaFailureClassification(error(new ProviderInternalError({ message: "overloaded" }))),
117+
).toBeUndefined()
118+
})
119+
})
120+
81121
describe("SessionStep failed attempt counter", () => {
82122
test("counts per key and clears on request", () => {
83123
expect(SessionStep.countFailedAttempt("a|x/y")).toBe(1)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.