From 455523fd923b729a95068315f956ada8ffdcb98e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 7 Nov 2026 23:16:20 -0600 Subject: [PATCH] fix(core): abolish pool-level quota verdicts Drew's ruling (2026-11-07): a pool cannot run out - only models and providers run out. Eligibility is now derived at decision time from per-leg state only: the leaf's own bench, its credential's gate, its provider's skip record, and - via the new ModelRoute.providerQuotaBlocked - its provider's own quota gate, which selection previously reached only through the pool verdict. poolQuotaExhausted, its evidence machinery, the pool-quota-exhausted reason, and the last-resort pool carve-out are deleted; per-leg reasons are preserved verbatim in decision detail. Supersedes #1975. --- packages/core/src/model-resolver.ts | 55 +--- packages/core/src/model-route.ts | 193 +++--------- .../core/test/fixture/mock-route-driver.ts | 20 +- packages/core/test/model-resolver.test.ts | 21 +- packages/core/test/model-route.test.ts | 275 ++++++------------ 5 files changed, 146 insertions(+), 418 deletions(-) diff --git a/packages/core/src/model-resolver.ts b/packages/core/src/model-resolver.ts index 6faa05973bf1..52a4beda3eee 100644 --- a/packages/core/src/model-resolver.ts +++ b/packages/core/src/model-resolver.ts @@ -798,21 +798,6 @@ export const layer = Layer.effect( const indexes = definition.targets.flatMap((_, index) => (triedTargets.has(index) ? [] : [index])) const unavailable = new Map() const overLimit = new Set() - // Pool-shaped pull-out (#1014 PR3): a leaf whose nested group (pool) has had two - // distinct quota evidence sources answer quota in turn is out with its pool, derived from the - // leaves' live quota benches/gates at this moment. - const poolExhausted = new Map() - for (const index of indexes) - poolExhausted.set( - index, - ModelRoute.poolQuotaExhausted( - definition, - index, - now, - (leaf) => effectiveCredential(definition.targets[leaf], now)?.id, - locationDirectory, - ), - ) const ready = indexes.filter((index) => { const target = definition.targets[index] const until = ModelRoute.cooldownUntil(target, now, locationDirectory) @@ -836,6 +821,7 @@ export const layer = Layer.effect( limited > now && ModelRoute.keepsThrough(definition.id, sessionID, target, now, credentialID, locationDirectory) const credentialUntil = credentialID ? ModelRoute.credentialCooldownUntil(target, credentialID, now) : 0 const quotaBlock = credentialID ? ModelRoute.credentialQuotaBlocked(credentialID, now, locationDirectory) : undefined + const providerBlock = ModelRoute.providerQuotaBlocked(target, now, locationDirectory) // Half-open probe (#1123): a bench whose known quota window reset has passed admits // one probe attempt instead of excluding the leaf until the ladder expires. This // admission is tentative — the claim is spent only when selection actually picks @@ -843,18 +829,12 @@ export const layer = Layer.effect( const targetProbe = until > now && ModelRoute.probeDue(target, undefined, now) const credentialProbe = credentialUntil > now && credentialID !== undefined && ModelRoute.probeDue(target, credentialID, now) - const isPoolExhausted = poolExhausted.get(index) ?? false - // A due half-open probe is the pool's recovery path, not more exhaustion - // evidence (#1390): the pool verdict (which already carves due probes out of - // its count) must not exclude the very leaf whose probe is due, e.g. a larger - // pool where two other leaves keep the verdict exhausted. - const poolProbe = targetProbe || credentialProbe if (until > now && !targetProbe) unavailable.set(index, `cooldown-until:${until}`) else if (credentialUntil > now && !credentialProbe) unavailable.set(index, `credential-cooldown-until:${credentialUntil}`) else if (quotaBlock) unavailable.set(index, `quota-known-full-until:${quotaBlock.until ?? "unknown"}`) - else if (isPoolExhausted && !poolProbe) - unavailable.set(index, `pool-quota-exhausted:${ModelRoute.poolIDOf(definition, index) ?? "pool"}`) + else if (providerBlock) + unavailable.set(index, `provider-quota-known-full-until:${providerBlock.until ?? "unknown"}`) else if (limited > now && !kept) unavailable.set(index, `provider-limit-until:${limited}`) else if (isSkipped) unavailable.set(index, "user-skip") else if (isOverBudget) unavailable.set(index, "soft-budget") @@ -863,7 +843,7 @@ export const layer = Layer.effect( (until <= now || targetProbe) && (credentialUntil <= now || credentialProbe) && quotaBlock === undefined && - (!isPoolExhausted || poolProbe) && + providerBlock === undefined && (limited <= now || kept) && !isSkipped && !isOverBudget && @@ -883,28 +863,11 @@ export const layer = Layer.effect( const credentialID = effectiveCredential(definition.targets[index], now)?.id return credentialID === undefined || ModelRoute.credentialQuotaBlocked(credentialID, now, locationDirectory) === undefined }) - // A quota-exhausted pool is a HARD exclusion, unlike budgets and skips: the last - // resort never re-offers a pool its leaves have proven walled (#1014 PR3) — the - // route resolves nothing and the cascade looks elsewhere instead. A due half-open - // probe is the exception (#1390): the last resort still offers a leaf whose own - // probe is due, so recovery is possible even when the rest of the pool keeps the - // verdict exhausted. When every - // usable target sits in an exhausted pool there is no last resort at all. - const nonPool = usable.filter((index) => { - if (!poolExhausted.get(index)) return true - const target = definition.targets[index] - const credentialID = credentialByProvider.get(definition.targets[index].providerID) - const until = ModelRoute.cooldownUntil(target, now, locationDirectory) - const credentialUntil = credentialID - ? ModelRoute.credentialCooldownUntil(target, credentialID, now) - : 0 - return ( - (until > now && ModelRoute.probeDue(target, undefined, now)) || - (credentialUntil > now && credentialID !== undefined && ModelRoute.probeDue(target, credentialID, now)) - ) - }) - const nonPoolNonFull = nonPool.filter((index) => nonFull.includes(index)) - const lastResort = nonPool.length === 0 ? [] : nonPoolNonFull.length > 0 ? nonPoolNonFull : nonPool + // No pool-level hard exclusion (Drew, 2026-11-07): a pool cannot run out — + // only a leaf's own model, credential, or provider can — so the last resort + // is the usable set itself, preferring targets whose credential is not + // known-full while any such target remains. + const lastResort = nonFull.length > 0 ? nonFull : usable const eligible = ready.length > 0 ? ready : allowCooling ? lastResort : [] const index = ModelRoute.nextTarget( definition, diff --git a/packages/core/src/model-route.ts b/packages/core/src/model-route.ts index cacf760ff269..4ce0ab72f962 100644 --- a/packages/core/src/model-route.ts +++ b/packages/core/src/model-route.ts @@ -833,16 +833,6 @@ export const availability = (now = Date.now()): AvailabilityEntry[] => { ) } -/** How many distinct quota evidence sources of one pool must be out before the pool itself is pulled: - * one leaf's quota answer can be leaf-specific, but a second distinct evidence source of the same pool - * answering quota in turn is the pool-shaped signal (#1014 PR3). */ -const POOL_QUOTA_LEAVES = 2 - -const quotaBench = (state: HealthState | undefined, now: number) => - state !== undefined && - state.cooldownUntil > now && - (state.benchReason === "quota" || state.benchReason === "quota retry-after") - /** Whether a balance is dead under a threshold, with the same floating-point tolerance * QuotaSnapshot.isKnownFull applies to live snapshots (#1461): a balance a hair above the * threshold from rounding (0.4 - 0.3 = 0.10000000000000003 against the 0.1 default) is @@ -869,155 +859,6 @@ const quotaSkipBlocks = (item: Adjustment, now: number, location?: string): bool return deadBalance(judged, currentConstants(location).quotaGate.balanceDeadThreshold) } -/** One leaf's quota-out evidence, or undefined when the leaf is not quota-out: a quota - * bench on the leaf (or on the credential that serves it) counts per leaf, a quota gate - * on the credential counts once per credential, and a quota gate on the provider (a - * known-full snapshot, a balance hold, or the reactive attempt-reported skip) counts - * once per provider. Bench evidence takes priority over a shared gate on the same - * leaf, so two genuinely independent benches under one gate still count separately. - * Balance holds count until a fresh balance increase releases them, so a pool held by - * a balance gate stays out with no timer-based re-admission (#1014). A bench whose - * half-open probe is due still produces evidence here; `poolQuotaExhausted` carves - * due probes back out so the pool verdict does not defeat the recovery path (#1390). */ -const quotaEvidence = ( - target: Model.Ref, - credentialID: string | undefined, - now: number, - location?: string, -): string | undefined => { - if (credentialID) { - if (quotaBench(credentialHealth.get(credentialKey(target, credentialID)), now)) - return `bench:${credentialKey(target, credentialID)}` - if (credentialQuotaBlocked(credentialID, now, location) !== undefined) return `cred-gate:${credentialID}` - return undefined - } - if (quotaBench(health.get(key(target)), now)) return `bench:${key(target)}` - const provider = providerQuota.get(target.providerID) - // A threshold balance hold is judged under the judging Location (#1461), but its - // verdict is not final for the provider's other skips: a timed attempt-reported - // `quota:` skip installed while the hold stands must still count. The fallthrough - // is safe for the hold's own durable record because quotaSkipBlocks re-judges - // threshold records, so an admitted threshold hold does not re-block through it. - if (provider?.balanceHold !== undefined && holdBlocks(provider.balanceHold, provider.snapshot, now, location)) - return `prov:${target.providerID}` - if ( - provider && - QuotaSnapshot.isKnownFull(provider.snapshot, now, currentConstants(location).quotaGate.balanceDeadThreshold) - ) - return `prov:${target.providerID}` - if ( - activeAdjustments(now).some( - (item) => item.id === `quota:${target.providerID}` && item.action === "skip" && quotaSkipBlocks(item, now, location), - ) - ) - return `prov:${target.providerID}` - return undefined -} - -interface PoolMembership { - readonly id: string - readonly leaves: readonly number[] -} - -/** The pool a leaf belongs to: the deepest nested group (a node other than the route root) - * that contains it. A provider-route group is named by its provider route, a nested route by - * its route id. A leaf sitting directly on the root belongs to no pool. When a leaf appears - * under several groups the deepest one is its pool — that is the tightest shared fate. */ -const poolOf = (definition: Definition, index: number): PoolMembership | undefined => { - let best: { depth: number; nodeIndex: number; leaves: number[] } | undefined - const collect = (nodeIndex: number, into: number[]) => { - const node = definition.nodes[nodeIndex] - if (!node) return - for (const child of node.children) { - if (child.leaf !== undefined) into.push(child.leaf) - else if (child.node !== undefined) collect(child.node, into) - } - } - const visit = (nodeIndex: number, depth: number) => { - const node = definition.nodes[nodeIndex] - if (!node) return - if (nodeIndex !== 0) { - const leaves: number[] = [] - collect(nodeIndex, leaves) - if (leaves.includes(index) && (best === undefined || depth > best.depth)) best = { depth, nodeIndex, leaves } - } - for (const child of node.children) if (child.node !== undefined) visit(child.node, depth + 1) - } - visit(0, 0) - if (best === undefined) return undefined - const found: { depth: number; nodeIndex: number; leaves: number[] } = best - const node = definition.nodes[found.nodeIndex] - return { id: node?.providerRoute ?? node?.routeID ?? `${definition.id}#${found.nodeIndex}`, leaves: found.leaves } -} - -/** The id of the pool (nested group) a leaf belongs to, or undefined when it sits on the root. */ -export const poolIDOf = (definition: Definition, index: number) => poolOf(definition, index)?.id - -/** Whether an independent quota gate currently blocks a leaf, apart from any bench: - * a quota gate on its credential, or one on its provider (a known-full snapshot, a - * balance hold, or the reactive attempt-reported skip). A due bench probe never - * bypasses these gates (see `probeDue`), so a gated leaf cannot recover through its - * probe until the gate's own reset passes. */ -const independentQuotaGate = ( - target: Model.Ref, - credentialID: string | undefined, - now: number, - location?: string, -): boolean => { - if (credentialID && credentialQuotaBlocked(credentialID, now, location) !== undefined) return true - const provider = providerQuota.get(target.providerID) - if (provider?.balanceHold !== undefined && holdBlocks(provider.balanceHold, provider.snapshot, now, location)) - return true - if ( - provider && - QuotaSnapshot.isKnownFull(provider.snapshot, now, currentConstants(location).quotaGate.balanceDeadThreshold) - ) - return true - return activeAdjustments(now).some( - (item) => item.id === `quota:${target.providerID}` && item.action === "skip" && quotaSkipBlocks(item, now, location), - ) -} - -/** Whether a leaf's pool is quota-exhausted: at least two distinct quota evidence - * sources across the pool's leaves are currently out, so the pool is pulled as a whole - * instead of spending attempts on its remaining leaves one by one (#1014 PR3 dynamic - * pull-out). Evidence is deduplicated by identity — two leaves out only through one - * shared credential or provider gate count as one signal, so a single provider's quota - * wall cannot hard-exclude a healthy leaf from another provider (#1389) — while a - * leaf's own quota bench always counts per leaf. A leaf whose bench probe is due - * contributes no evidence — unless an independent quota gate (on its credential or - * its provider) still blocks it: a probe never bypasses a gate whose own reset is - * still ahead, so a gated leaf's due probe cannot recover it yet and the leaf keeps - * counting (Codex review, PR #1473). An ungated due probe's bench still excludes - * ordinary candidacy, but the pool verdict must not defeat the half-open recovery - * the probe exists for (#1390). A claimed or not-yet-due bench keeps counting, - * because `probeDue` is false while a probe is outstanding and before its reset - * passes. The verdict is derived from the - * leaves' live quota state, so it lifts by itself when the benches reach their stated - * reset, when a balance hold is released by a fresh increase, or when a benched leaf - * recovers — a recovered pool re-enters rotation with no second producer. */ -export const poolQuotaExhausted = ( - definition: Definition, - index: number, - now = Date.now(), - credentialOf?: (index: number) => string | undefined, - location?: string, -): boolean => { - const pool = poolOf(definition, index) - if (!pool || pool.leaves.length < POOL_QUOTA_LEAVES) return false - const evidence = new Set() - for (const leaf of pool.leaves) { - const target = definition.targets[leaf] - if (!target) continue - const credentialID = credentialOf?.(leaf) - const source = quotaEvidence(target, credentialID, now, location) - if (!source) continue - if (probeDue(target, credentialID, now) && !independentQuotaGate(target, credentialID, now, location)) continue - evidence.add(source) - } - return evidence.size >= POOL_QUOTA_LEAVES -} - /** The half-open bench probe claim a routed pick spent (#1478, #1486): the token names the * pick's spend across every scope it claimed, so settlement lands only on scopes whose * outstanding claim is still this pick's. The credential is the snapshot credential at pick @@ -2123,6 +1964,40 @@ export const credentialQuotaBlocked = ( return undefined } +/** Whether a target's own provider quota gate currently blocks it: the provider-scope + * mirror of `credentialQuotaBlocked`, judged from the provider's own gate state alone. + * There is no pool-level verdict (Drew, 2026-11-07): a pool cannot run out — only + * models, credentials, and providers can — so a leaf is excluded by its own provider's + * gate or not at all, never by the state of other leaves in its route group. A restored + * provider balance record with no in-memory state yet is not judged here: its durable + * `quota:` skip excludes through `skipped` until the first fed snapshot re-arms the + * state, so the leaf stays out on its own provider's record either way. */ +export const providerQuotaBlocked = ( + target: Model.Ref, + now = Date.now(), + location?: string, +): { readonly until: number | null } | undefined => { + const state = providerQuota.get(target.providerID) + if (!state) return undefined + // Judged exactly as the credential scope is (#1461): a threshold-derived hold blocks + // only a Location whose own threshold still judges the retained snapshot known-full; + // a retained reactive timed gate blocks every Location until its reset. + if (state.balanceHold) { + if (holdBlocks(state.balanceHold, state.snapshot, now, location)) return { until: null } + if (state.timedGateUntil !== undefined && state.timedGateUntil > now) return { until: state.timedGateUntil } + return undefined + } + if (QuotaSnapshot.isKnownFull(state.snapshot, now, currentConstants(location).quotaGate.balanceDeadThreshold)) { + state.gated = true + return { until: state.snapshot.resetAt } + } + if (state.gated) { + state.gated = false + logHealth(state.target, "quota-readmitted", `provider:${target.providerID}`) + } + return undefined +} + /** Ends a state's bench on a success: an ordinary success only ends an expired bench * (recover), but a success on a claimed half-open probe ends the bench outright (#1123) — the * probe was admitted precisely to learn whether the leaf serves again, and it does. */ diff --git a/packages/core/test/fixture/mock-route-driver.ts b/packages/core/test/fixture/mock-route-driver.ts index f38b3e062be6..3b81ddfefceb 100644 --- a/packages/core/test/fixture/mock-route-driver.ts +++ b/packages/core/test/fixture/mock-route-driver.ts @@ -88,14 +88,6 @@ export const driveStep = async (input: DriveInput): Promise => { const indexes = definition.targets.flatMap((_, index) => (tried.has(index) ? [] : [index])) const unavailable = new Map() const overLimit = new Set() - const poolExhausted = new Map() - for (const index of indexes) - poolExhausted.set( - index, - ModelRoute.poolQuotaExhausted(definition, index, now, (leaf) => - credentialOf(definition.targets[leaf]), - ), - ) const rules = ModelRouteAutonomy.usesRules(definition.autonomy) const scope = ModelRoute.scopeOf(definition, []) const ready = indexes.filter((index) => { @@ -115,16 +107,16 @@ export const driveStep = async (input: DriveInput): Promise => { const quotaBlock = credentialID ? ModelRoute.credentialQuotaBlocked(credentialID, now) : undefined + const providerBlock = ModelRoute.providerQuotaBlocked(target, now) const targetProbe = until > now && ModelRoute.probeDue(target, undefined, now) const credentialProbe = credentialUntil > now && credentialID !== undefined && ModelRoute.probeDue(target, credentialID, now) - const isPoolExhausted = poolExhausted.get(index) ?? false if (until > now && !targetProbe) unavailable.set(index, `cooldown-until:${until}`) else if (credentialUntil > now && !credentialProbe) unavailable.set(index, `credential-cooldown-until:${credentialUntil}`) else if (quotaBlock) unavailable.set(index, `quota-known-full-until:${quotaBlock.until ?? "unknown"}`) - else if (isPoolExhausted) - unavailable.set(index, `pool-quota-exhausted:${ModelRoute.poolIDOf(definition, index) ?? "pool"}`) + else if (providerBlock) + unavailable.set(index, `provider-quota-known-full-until:${providerBlock.until ?? "unknown"}`) else if (limited > now && !kept) unavailable.set(index, `provider-limit-until:${limited}`) else if (isSkipped) unavailable.set(index, "user-skip") else if (isOverBudget) unavailable.set(index, "soft-budget") @@ -133,7 +125,7 @@ export const driveStep = async (input: DriveInput): Promise => { (until <= now || targetProbe) && (credentialUntil <= now || credentialProbe) && quotaBlock === undefined && - !isPoolExhausted && + providerBlock === undefined && (limited <= now || kept) && !isSkipped && !isOverBudget && @@ -145,9 +137,7 @@ export const driveStep = async (input: DriveInput): Promise => { const credentialID = credentialOf(definition.targets[index]) return credentialID === undefined || ModelRoute.credentialQuotaBlocked(credentialID, now) === undefined }) - const nonPool = usable.filter((index) => !poolExhausted.get(index)) - const nonPoolNonFull = nonPool.filter((index) => nonFull.includes(index)) - const lastResort = nonPool.length === 0 ? [] : nonPoolNonFull.length > 0 ? nonPoolNonFull : nonPool + const lastResort = nonFull.length > 0 ? nonFull : usable return { unavailable, eligible: ready.length > 0 ? ready : input.allowCooling ? lastResort : [] } } diff --git a/packages/core/test/model-resolver.test.ts b/packages/core/test/model-resolver.test.ts index 555b1404ca0b..04f83536f03b 100644 --- a/packages/core/test/model-resolver.test.ts +++ b/packages/core/test/model-resolver.test.ts @@ -2880,12 +2880,21 @@ describe("ModelResolver routes", () => { allProviders.map(leaf), (resolver) => Effect.gen(function* () { - yield* resolver.resolveModel(routeA) - expect(ModelRoute.poolQuotaExhausted(definitionA, 0)).toBe(true) - expect(ModelRoute.poolQuotaExhausted(definitionB, 0)).toBe(false) - - yield* resolver.resolveModel(routeB) - expect(ModelRoute.poolQuotaExhausted(definitionB, 0)).toBe(true) + // No pool verdict exists to consult (Drew, 2026-11-07): the feed's + // effect is per provider \u2014 route A's providers are gated by their + // own snapshots, route B's are not fed yet, and resolution lands on + // A's individually-clear fallback leaf. + const resolvedA = yield* resolver.resolveModel(routeA) + expect(targetOf(resolvedA)).toBe("quota-a-fallback") + expect(ModelRoute.providerQuotaBlocked(definitionA.targets[0])).toBeDefined() + expect(ModelRoute.providerQuotaBlocked(definitionA.targets[1])).toBeDefined() + expect(ModelRoute.providerQuotaBlocked(definitionB.targets[0])).toBeUndefined() + expect(ModelRoute.providerQuotaBlocked(definitionB.targets[1])).toBeUndefined() + + const resolvedB = yield* resolver.resolveModel(routeB) + expect(targetOf(resolvedB)).toBe("quota-b-fallback") + expect(ModelRoute.providerQuotaBlocked(definitionB.targets[0])).toBeDefined() + expect(ModelRoute.providerQuotaBlocked(definitionB.targets[1])).toBeDefined() }), undefined, path, diff --git a/packages/core/test/model-route.test.ts b/packages/core/test/model-route.test.ts index a215084abcff..315d0f3ca748 100644 --- a/packages/core/test/model-route.test.ts +++ b/packages/core/test/model-route.test.ts @@ -2275,33 +2275,25 @@ describe("ModelRoute machinery constants (experimental.model_route_settings)", ( expect(ModelRoute.credentialQuotaBlocked("timed-cred", now + 60_001, "/loc/a")).toEqual({ until: null }) // Timed provider skips: two providers whose threshold holds B admits each - // gain a timed attempt-reported skip; the pool then counts as out under B. + // gain a timed attempt-reported skip; the exclusion lands on each + // provider's own records \u2014 there is no pool verdict to count them together. ModelRoute.resetHealth() ModelRoute.setAdjustments([]) const leaf1 = ModelRoute.ref({ providerID: "prov-t1", model: "m" }) const leaf2 = ModelRoute.ref({ providerID: "prov-t2", model: "m" }) ModelRoute.observeProviderQuota(leaf1, { ...balance, providerID: "prov-t1" }, now, "/loc/a") ModelRoute.observeProviderQuota(leaf2, { ...balance, providerID: "prov-t2" }, now, "/loc/a") - const definition = { - id: "timed-pool-route", - targets: [leaf1, leaf2], - targetVariants: [], - health: ModelRoute.policy(), - nodes: [ - { selection: "ordered" as const, weights: [1], children: [{ node: 1 }] }, - { - routeID: "timed-pool", - selection: "ordered" as const, - weights: [1, 1], - children: [{ leaf: 0 }, { leaf: 1 }], - }, - ], - } as unknown as ModelRoute.Definition - expect(ModelRoute.poolQuotaExhausted(definition, 0, now, undefined, "/loc/b")).toBe(false) + expect(ModelRoute.providerQuotaBlocked(leaf1, now, "/loc/b")).toBeUndefined() + expect(ModelRoute.providerQuotaBlocked(leaf2, now, "/loc/b")).toBeUndefined() ModelRoute.observeQuotaFailure(leaf1, undefined, now + 60_000, now + 1, "rate-limit", "/loc/b") ModelRoute.observeQuotaFailure(leaf2, undefined, now + 60_000, now + 1, "rate-limit", "/loc/b") expect(ModelRoute.skipped(leaf1, now + 1, { location: "/loc/b" })).toBe(true) - expect(ModelRoute.poolQuotaExhausted(definition, 0, now + 1, undefined, "/loc/b")).toBe(true) + // The timed exclusion is carried by each provider's own skip record + // (skipped above); the in-memory gate still shows only the threshold + // hold, which blocks A and admits B. + expect(ModelRoute.providerQuotaBlocked(leaf1, now + 1, "/loc/b")).toBeUndefined() + expect(ModelRoute.providerQuotaBlocked(leaf1, now + 1, "/loc/a")).toEqual({ until: null }) + expect(ModelRoute.providerQuotaBlocked(leaf2, now + 1, "/loc/a")).toEqual({ until: null }) } finally { ModelRoute.setAdjustments([]) offA() @@ -2310,14 +2302,13 @@ describe("ModelRoute machinery constants (experimental.model_route_settings)", ( } }) - test("threshold-derived provider holds are judged under the requesting Location in skipped and pool pull-out (#1461)", () => { + test("threshold-derived provider holds are judged under the requesting Location in skipped (#1461)", () => { const offA = ModelRoute.onSettingsConfig(() => ({ quotaGate: { balanceDeadThreshold: 1 } }), "/loc/a") const offB = ModelRoute.onSettingsConfig(() => ({ quotaGate: { balanceDeadThreshold: 0.05 } }), "/loc/b") try { ModelRoute.resetHealth() const now = Date.now() const leafA = ModelRoute.ref({ providerID: "prov-hold", model: "m1" }) - const leafB = ModelRoute.ref({ providerID: "prov-hold", model: "m2" }) const balance = { planID: "credits-plan", window: "credits", @@ -2332,36 +2323,21 @@ describe("ModelRoute machinery constants (experimental.model_route_settings)", ( ModelRoute.observeProviderQuota(leafA, balance, now, "/loc/a") expect(ModelRoute.skipped(leafA, now, { location: "/loc/a" })).toBe(true) expect(ModelRoute.skipped(leafA, now, { location: "/loc/b" })).toBe(false) - const definition = { - id: "prov-hold-route", - targets: [leafA, leafB], - targetVariants: [], - health: ModelRoute.policy(), - nodes: [ - { selection: "ordered" as const, weights: [1], children: [{ node: 1 }] }, - { - routeID: "prov-hold-pool", - selection: "ordered" as const, - weights: [1, 1], - children: [{ leaf: 0 }, { leaf: 1 }], - }, - ], - } as unknown as ModelRoute.Definition - // Both leaves share one provider gate, which counts as a single quota - // evidence source under main's #1389 dedup, so that gate alone does not - // pull the pool under either Location; the per-Location judgement is - // carried by skipped() above (and by distinct-provider pools in the - // timed-skip test below). - expect(ModelRoute.poolQuotaExhausted(definition, 0, now, undefined, "/loc/a")).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 0, now, undefined, "/loc/b")).toBe(false) + // The provider's own gate carries the same per-Location judgement: the + // hold blocks its leaf under A and admits it under B. There is no + // pool-level fact to consult \u2014 a pool cannot run out (Drew, 2026-11-07). + expect(ModelRoute.providerQuotaBlocked(leafA, now, "/loc/a")).toEqual({ until: null }) + expect(ModelRoute.providerQuotaBlocked(leafA, now, "/loc/b")).toBeUndefined() const durable = ModelRoute.activeAdjustments(now).find((item) => item.id === "quota:prov-hold") expect(durable?.balanceHoldOrigin).toBe("threshold") ModelRoute.resetHealth() ModelRoute.setAdjustments(durable ? [durable] : []) expect(ModelRoute.skipped(leafA, now, { location: "/loc/a" })).toBe(true) expect(ModelRoute.skipped(leafA, now, { location: "/loc/b" })).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 0, now, undefined, "/loc/a")).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 0, now, undefined, "/loc/b")).toBe(false) + // After a restart the durable record alone carries the judgement through + // skipped(); no in-memory provider gate exists until the next fed snapshot. + expect(ModelRoute.providerQuotaBlocked(leafA, now, "/loc/a")).toBeUndefined() + expect(ModelRoute.providerQuotaBlocked(leafA, now, "/loc/b")).toBeUndefined() } finally { ModelRoute.setAdjustments([]) offA() @@ -2682,181 +2658,96 @@ describe("ModelRoute provider-route groups with no ready members", () => { }) }) }) - -describe("ModelRoute pool-shaped quota pull-out (#1014 PR3)", () => { +describe("ModelRoute per-leg quota state (pool verdict abolished)", () => { const policy = ModelRoute.policy({ cooldownMs: 5_000, quotaCooldownMs: 60_000 }) const leaves = [0, 1, 2].map((index) => ModelRoute.ref({ providerID: `pool-p${index}`, model: `m${index}` })) const outside = ModelRoute.ref({ providerID: "pool-outside", model: "solo" }) - // Root: the pool group (leaves 0-2, one nested route) plus one leaf that belongs to no pool. - const definition = { - id: "pool-route", - targets: [...leaves, outside], - targetVariants: [], - health: policy, - nodes: [ - { selection: "ordered" as const, weights: [1, 1], children: [{ node: 1 }, { leaf: 3 }] }, - { routeID: "pool-plan", selection: "ordered" as const, weights: [1, 1, 1], children: [{ leaf: 0 }, { leaf: 1 }, { leaf: 2 }] }, - ], - } as unknown as ModelRoute.Definition - test("two distinct leaves answering quota in turn pull the whole pool; expiry re-admits it", () => { + test("quota benches on two leaves of one group never exclude a third, individually-clear leaf", () => { ModelRoute.resetHealth() const now = Date.now() - expect(ModelRoute.poolIDOf(definition, 2)).toBe("pool-plan") - expect(ModelRoute.poolIDOf(definition, 3)).toBeUndefined() - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(false) - - // One leaf's quota answer is leaf-shaped: the pool still serves through its other leaves. ModelRoute.failed(leaves[0], policy, now, { quota: true }) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(false) - - // A second distinct leaf answering quota is the pool-shaped signal: the remaining leaf - // is pulled with its pool instead of being spent next. ModelRoute.failed(leaves[1], policy, now, { quota: true }) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(true) - expect(ModelRoute.poolQuotaExhausted(definition, 0, now)).toBe(true) - // A leaf outside the pool is never pulled by the pool's exhaustion. - expect(ModelRoute.poolQuotaExhausted(definition, 3, now)).toBe(false) - - // Restoration is automatic: once the quota benches expire the pool re-enters rotation. - expect(ModelRoute.poolQuotaExhausted(definition, 2, now + 60_001)).toBe(false) - ModelRoute.resetHealth() - }) - - test("reactive quota gates on two leaves' providers exhaust the pool until the stated reset", () => { - ModelRoute.resetHealth() + // Each benched leaf is out on its own bench... + expect(ModelRoute.cooldownUntil(leaves[0], now)).toBeGreaterThan(now) + expect(ModelRoute.cooldownUntil(leaves[1], now)).toBeGreaterThan(now) + // ...and the third leaf of the same group carries no exclusion of any kind: + // no bench and no provider gate. A pool cannot run out (Drew, 2026-11-07) \u2014 + // only its leaves' own models, credentials, and providers can. + expect(ModelRoute.cooldownUntil(leaves[2], now)).toBe(0) + expect(ModelRoute.providerQuotaBlocked(leaves[2], now)).toBeUndefined() + expect(ModelRoute.cooldownUntil(outside, now)).toBe(0) + // Expiry re-admits each benched leaf on its own clock. + expect(ModelRoute.cooldownUntil(leaves[0], now + 60_001)).toBe(0) + expect(ModelRoute.cooldownUntil(leaves[1], now + 60_001)).toBe(0) + }) + + test("a provider's own quota state blocks every leaf it serves and no other provider's leaf", () => { + ModelRoute.resetHealth() + ModelRoute.setAdjustments([]) const now = Date.now() - const resetAt = now + 30 * 60_000 - ModelRoute.observeQuotaFailure(leaves[0], undefined, resetAt, now) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(false) - ModelRoute.observeQuotaFailure(leaves[1], undefined, resetAt, now) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(true) - // The pull-out holds until the reset the providers stated, then lifts by itself. - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt + 1)).toBe(false) - ModelRoute.resetHealth() - }) - - test("one shared credential or provider gate counts once, so a healthy leaf keeps the pool open (#1389)", () => { + const resetAt = now + 3_600_000 + // Two leaves share one provider; a third leaf sits on its own provider in + // the same route group. Quota state is the provider's, so it covers + // exactly the leaves that provider serves. const shared = [0, 1].map((index) => ModelRoute.ref({ providerID: "pool-shared", model: `s${index}` })) - const healthy = ModelRoute.ref({ providerID: "pool-healthy", model: "m2" }) - const sharedDefinition = { - id: "pool-shared-route", - targets: [...shared, healthy], - targetVariants: [], - health: policy, - nodes: [ - { selection: "ordered" as const, weights: [1], children: [{ node: 1 }] }, - { routeID: "pool-shared-plan", selection: "ordered" as const, weights: [1, 1, 1], children: [{ leaf: 0 }, { leaf: 1 }, { leaf: 2 }] }, - ], - } as unknown as ModelRoute.Definition - const now = Date.now() - const resetAt = now + 30 * 60_000 - - // Two leaves behind one gated credential are one quota signal, not two. - ModelRoute.resetHealth() - const sharedCredential = (index: number) => - sharedDefinition.targets[index].providerID === "pool-shared" ? "cred-shared" : undefined - ModelRoute.observeQuotaFailure(shared[0], "cred-shared", resetAt, now) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 0, now, sharedCredential)).toBe(false) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 1, now, sharedCredential)).toBe(false) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now, sharedCredential)).toBe(false) - // A second, genuinely distinct gate on the healthy leaf's provider still exhausts the pool. - ModelRoute.observeQuotaFailure(healthy, undefined, resetAt, now) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now, sharedCredential)).toBe(true) - - // Two credential-less leaves behind one gated provider are one quota signal, not two. - ModelRoute.resetHealth() + // Attempt-reported exhaustion lands on the provider's own skip record, + // judged per leaf by skipped() \u2014 no in-memory gate, no pool fact. ModelRoute.observeQuotaFailure(shared[0], undefined, resetAt, now) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now)).toBe(false) - ModelRoute.observeQuotaFailure(healthy, undefined, resetAt, now) - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now)).toBe(true) - - // Two independent quota benches on distinct credentials still exhaust the pool. - ModelRoute.resetHealth() - const distinctCredential = (index: number) => - sharedDefinition.targets[index].providerID === "pool-shared" ? `cred-${index}` : undefined - ModelRoute.failed(shared[0], policy, now, { quota: true }, "cred-0") - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now, distinctCredential)).toBe(false) - ModelRoute.failed(shared[1], policy, now, { quota: true }, "cred-1") - expect(ModelRoute.poolQuotaExhausted(sharedDefinition, 2, now, distinctCredential)).toBe(true) - ModelRoute.resetHealth() + expect(ModelRoute.skipped(shared[0], now)).toBe(true) + expect(ModelRoute.skipped(shared[1], now)).toBe(true) + expect(ModelRoute.skipped(leaves[2], now)).not.toBe(true) + expect(ModelRoute.providerQuotaBlocked(shared[0], now)).toBeUndefined() + // A fed known-full snapshot gates the provider in memory, for both leaves. + ModelRoute.observeProviderQuota( + shared[0], + { planID: "plan", window: "weekly", providerID: "pool-shared", percent: 100, remaining: 0, resetAt, observedAt: now, stale: false }, + now, + ) + expect(ModelRoute.providerQuotaBlocked(shared[0], now)).toEqual({ until: resetAt }) + expect(ModelRoute.providerQuotaBlocked(shared[1], now)).toEqual({ until: resetAt }) + expect(ModelRoute.providerQuotaBlocked(leaves[2], now)).toBeUndefined() + // The gate lifts on the provider's own reset clock. + expect(ModelRoute.providerQuotaBlocked(shared[0], resetAt + 1)).toBeUndefined() + expect(ModelRoute.skipped(shared[0], resetAt + 1)).not.toBe(true) }) - test("due bench probes do not pull their pool; claimed and not-yet-due benches still do (#1390)", () => { + test("a shared credential's gate blocks through the credential scope only, never a provider scope", () => { ModelRoute.resetHealth() const now = Date.now() - const resetAt = now + 30_000 - const knownFullFor = (leaf: { providerID: string }, at: number, observedAt: number) => ({ - planID: "plan", - window: "five-hours", - providerID: leaf.providerID, - percent: 100, - remaining: 0, - resetAt: at, - observedAt, - stale: false, - }) - - // Two distinct leaves answering quota pulls the pool. - ModelRoute.failed(leaves[0], policy, now, { quota: true }) - ModelRoute.failed(leaves[1], policy, now, { quota: true }) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(true) - - // A trustworthy window reset learned after the benches arms their half-open probes. - ModelRoute.observeProviderQuota(leaves[0], knownFullFor(leaves[0], resetAt, now + 10), now + 10) - ModelRoute.observeProviderQuota(leaves[1], knownFullFor(leaves[1], resetAt + 30_000, now + 10), now + 10) - - // Before the reset no probe is due, so the pool exclusion still applies. - expect(ModelRoute.probeDue(leaves[0], undefined, resetAt - 1)).toBe(false) - expect(ModelRoute.probeDue(leaves[1], undefined, resetAt - 1)).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt - 1)).toBe(true) - - // Once one reset passes, that due probe stays benched for ordinary candidacy but no - // longer counts toward the pool threshold, so the recovery path can run. - expect(ModelRoute.probeDue(leaves[0], undefined, resetAt)).toBe(true) - expect(ModelRoute.probeDue(leaves[1], undefined, resetAt)).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt)).toBe(false) - - // A claimed probe counts again, alongside the other not-yet-due bench, so the pool - // exclusion applies while the half-open attempt is outstanding. - expect(ModelRoute.claimBenchProbe(leaves[0], undefined, resetAt)).toBe(true) - expect(ModelRoute.probeDue(leaves[0], undefined, resetAt)).toBe(false) - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt)).toBe(true) - ModelRoute.resetHealth() + const resetAt = now + 3_600_000 + ModelRoute.observeQuotaFailure(leaves[0], "cred-pool", resetAt, now) + expect(ModelRoute.credentialQuotaBlocked("cred-pool", now)).toEqual({ until: resetAt }) + // The credential gate says nothing about any provider gate: a leaf keeps + // whatever its own provider state says (here, nothing). + expect(ModelRoute.providerQuotaBlocked(leaves[0], now)).toBeUndefined() + expect(ModelRoute.credentialQuotaBlocked("cred-pool", resetAt + 1)).toBeUndefined() }) - test("a due probe behind an independent quota gate still counts toward its pool (#1390, Codex PR #1473)", () => { + test("a due probe does not outrank the leaf's own independent provider gate (#1390, #1473)", () => { ModelRoute.resetHealth() const now = Date.now() - const resetAt = now + 30_000 - const knownFullFor = (leaf: { providerID: string }, at: number, observedAt: number) => ({ + const resetAt = now + 5 * 3_600_000 + const longPolicy = ModelRoute.policy({ cooldownMs: 60_000, quotaCooldownMs: 900_000 }) + const knownFull = (at: number, observedAt: number) => ({ planID: "plan", window: "five-hours", - providerID: leaf.providerID, + providerID: "pool-p0", percent: 100, remaining: 0, resetAt: at, observedAt, stale: false, }) - - // Two distinct leaves answering quota pulls the pool. - ModelRoute.failed(leaves[0], policy, now, { quota: true }) - ModelRoute.failed(leaves[1], policy, now, { quota: true }) - expect(ModelRoute.poolQuotaExhausted(definition, 2, now)).toBe(true) - - // leaf0's bench learns the earlier reset, arming its probe; at the reset the - // ungated due probe is carved out and the pool verdict lifts. - ModelRoute.observeProviderQuota(leaves[0], knownFullFor(leaves[0], resetAt, now + 10), now + 10) + // Bench the leaf on the escalated ladder, which runs far past the window + // reset the provider feed then teaches it: a half-open probe comes due. + for (let index = 0; index < 8; index++) ModelRoute.failed(leaves[0], longPolicy, now + index, { quota: true }) + ModelRoute.observeProviderQuota(leaves[0], knownFull(resetAt, now + 10), now + 10) expect(ModelRoute.probeDue(leaves[0], undefined, resetAt)).toBe(true) - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt)).toBe(false) - - // A fresher known-full snapshot gates leaf0's provider until a later reset. - // The bench keeps its earliest reset, so the probe is still due -- but the - // independent gate blocks recovery, so the leaf counts toward the pool again. - ModelRoute.observeProviderQuota(leaves[0], knownFullFor(leaves[0], resetAt + 60_000, resetAt + 10), resetAt + 10) - expect(ModelRoute.probeDue(leaves[0], undefined, resetAt + 10)).toBe(true) - expect(ModelRoute.poolQuotaExhausted(definition, 2, resetAt + 10)).toBe(true) - ModelRoute.resetHealth() + // A fresher independent gate on the same provider still blocks the leaf + // itself: gates beat probes, judged per leaf, never via a pool verdict. + ModelRoute.observeProviderQuota(leaves[0], knownFull(resetAt + 60_000, resetAt), resetAt) + expect(ModelRoute.providerQuotaBlocked(leaves[0], resetAt + 10)).toEqual({ until: resetAt + 60_000 }) + expect(ModelRoute.providerQuotaBlocked(leaves[2], resetAt + 10)).toBeUndefined() }) })