Skip to content

fix(quota): separate tenant denial from provider exhaustion and reserve in-flight spend #109

Open

Description

@stackbilt-admin

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

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

  1. added
    bug
    on Oct 11, 2026
  2. stackbilt-admin commented on Oct 13, 2026

    @stackbilt-admin
    MemberAuthor

    Local implementation checkpoint — 2026-10-12

    This work is uncommitted/unpushed on main, based on 8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff is docs/maintenance/issue-sweep.md; it will travel with the code.

    The immediate local-denial patch is implemented:

    • Exported QuotaDeniedError is terminal for regular, streaming and image requests, before generic fallback rules. It never marks account exhaustion or degrades provider health.
    • Explicit denial cannot become fail-open admission because a quota observer throws. Quota-service errors still follow the configured fail-open/fail-closed policy.
    • Tenant isolation and continued access for other tenants are covered in tenant-safety.test.ts.
    • Streaming now awaits quota recording, exposes settlement failure through managed completion, records reported pre-output/partial usage, and retains estimated cost when actual usage is unavailable. Known unbilled admission/HTTP rejections are not charged.
    • README distinguishes approximate KV snapshot persistence from atomic admission and describes monetary ledger budgets as soft analytics/routing signals.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions