Repository navigation
Description
Priority and outcome
P0 for tenant-denial poisoning · impact H · effort S for immediate fix, M/L for reservations + durable example · risk: policy/accounting migration.
A tenant quota denial currently quarantines the provider for other tenants and other clients. CreditLedger budgets are routing signals, not enforced spend caps; concurrent requests also bypass its rate checks.
Evidence and repro
- src/factory.ts:1651: quotaHook denial becomes QuotaExceededError.
- src/factory.ts:738: every such error marks the provider globally exhausted.
- src/utils/exhaustion.ts:139: registry is a module singleton.
- src/factory.ts:1838: ledger admission checks rate counters only, no remaining monetary budget.
- src/model-catalog.ts:936: budget use only subtracts ranking score.
- src/utils/credit-ledger.ts:226: counters increase after successful completion.
- src/factory.ts:658 and src/factory.ts:1688: spend/quota record after completion; quota persistence is fire-and-forget.
- README.md:299: read-modify-write snapshot example has no concurrency control.
Verified synthetic probes: a denied tenant makes defaultExhaustionRegistry.isExhausted('openai') true; monthlyBudget: 0 still dispatches and records positive spend; rpm: 1 admits two simultaneous calls before either completes.
PR 1: stop the outage amplification
Add a distinct terminal local-policy error. It must never mark provider exhaustion, affect breakers, or trigger fallback into another provider when the tenant/global budget is denied.
import { LLMProviderError } from './errors.js';
export class QuotaDeniedError extends LLMProviderError {
constructor(provider: string, message = 'Local quota policy denied request') {
super(message, 'QUOTA_DENIED', provider, false, 403);
}
}Use this for quotaHook denied/fail-closed errors; handle it before fallback rules. Preserve QuotaExceededError for vendor-reported account exhaustion. Provider-specific budget rejection may skip that route, but tenant/global denial terminates the logical request. Add scope explicitly if the consumer needs both.
PR 2: additive atomic admission contract
Proposed API, not a claim about existing exports:
import type { TokenUsage } from './types.js';
export interface SpendReservationInput {
requestId: string;
tenantId: string;
provider: string;
model: string;
reservedUsd: number;
reservedTokens: number;
expiresAt: number;
}
export type SpendAdmission =
| { allowed: true; reservationId: string }
| { allowed: false; scope: 'tenant' | 'provider'; reason: string };
export interface SpendSettlement {
reservationId: string;
outcome: 'success' | 'error' | 'cancelled';
usage?: TokenUsage;
unknownUsagePolicy: 'retain-reservation' | 'release';
}
export interface QuotaCoordinator {
reserve(input: SpendReservationInput): Promise<SpendAdmission>;
settle(input: SpendSettlement): Promise<void>;
}Reserve immediately before each physical attempt, atomically counting in-flight money/requests/tokens. Settle idempotently on every terminal path. Charge failed/billed attempts when usage is available; preserve uncertainty rather than zeroing partial/unknown usage. Define reservation expiration, period rollover and late settlement explicitly. Make maxTokens/output bounds and pricing policy explicit: a local estimate does not guarantee the vendor's final bill. Keep CreditLedger analytics compatible; do not advertise a hard USD cap for unknown-priced models.
Provide an in-memory implementation with synchronous mutation before awaiting, then an optional SQLite Durable Object example keyed by the policy's coordination scope (e.g. tenant). Do not use one global DO. Tenant-wide budgets across providers require one tenant coordination domain; credential/account provider health can use a separate domain. Keep Cloudflare-specific imports outside the portable root.
Workers KV is not an atomic counter: Cloudflare documents overwritten concurrent writes and write-frequency limits. Replace the README's per-request KV restore/put recipe with a warning plus safe durable example. Durable Objects guidance.
Tests / acceptance
- Tenant A denial does not exhaust a provider or affect tenant B.
- Local denial never falls through generic error rules; true vendor exhaustion still skips the affected account.
- Parallel requests cannot spend the same available reservation; failed/retried physical attempts are counted.
- Zero budget rejects; positive budget subtracts in-flight commitments; projected token use is checked.
- Duplicate settlement, abandoned lease, rollover, restart and late settlement preserve accounting.
- Unknown partial usage follows explicit conservative policy.
- Settlement is awaited before completion, or exposed as a promise for ctx.waitUntil; no silent background writes.
- Workers runtime concurrency test across two callers; memory and durable adapter parity.
Semver / migration / README
Ship local-denial classification as a patch. Reservation APIs and durable example as a minor, opt-in; changing existing soft budgets to enforced budgets by default belongs in the next major.
Suggested README text:
CreditLedger tracks local spend and influences routing. For concurrent or multi-isolate budget enforcement, configure an atomic QuotaCoordinator. Tenant denial stops the request; provider-account exhaustion may fail over. KV snapshots preserve approximate history, not atomic admission.
Follow-up to closed #65 and #14: snapshots and post-completion counters did not solve admission races.
Activity
stackbilt-admin commentedon Oct 13, 2026
Local implementation checkpoint — 2026-10-12
This work is uncommitted/unpushed on
main, based on8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff isdocs/maintenance/issue-sweep.md; it will travel with the code.The immediate local-denial patch is implemented:
QuotaDeniedErroris terminal for regular, streaming and image requests, before generic fallback rules. It never marks account exhaustion or degrades provider health.tenant-safety.test.ts.Not implemented: atomic reserve/settle coordinator, in-flight money/request/token commitments, physical retry-attempt admission, leases, idempotency/rollover/late settlement, durable adapter and multi-isolate tests. Non-streaming quota persistence is still fire-and-forget. No hard concurrent USD-cap claim is made. Reservations are the next larger work item after #112.
Validation for the combined local sweep: 605 tests pass across 27 files, TypeScript typecheck passes, Worker-targeted bundle/import smoke passes. Packed entrypoint exports/client methods and all 33 JavaScript sourcemaps were checked on Windows with Node 24.19.0/npm 11.17.0. No live/billable providers or workerd execution; this does not prove minimum Node-version compatibility.
feat: streaming lifecycle, tenant-safe caching, client-scoped resilie…