mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-11-24 04:43:07 +00:00
fix(claude): gate opted-in accounts whose plan windows and extra-usage cap are both spent (#18059)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
- fix(claude): stop routing to an extra-usage-enabled Claude account whose plan windows and monthly spend cap are both exhausted (#18059)
|
||||
97
src/domain/claudeExtraUsageCap.ts
Normal file
97
src/domain/claudeExtraUsageCap.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Claude extra-usage monthly spend cap, as a pre-dispatch signal (#18059).
|
||||
*
|
||||
* A Claude connection that opted into extra usage (`blockExtraUsage === false`) bypasses the
|
||||
* plan-window quota filter, so an account whose plan windows AND monthly cap are both spent used
|
||||
* to stay eligible until the upstream "monthly spend limit" 429. The cap is tracked here, apart
|
||||
* from the plan windows, because it alone never makes an account ineligible: the plan windows
|
||||
* still serve requests while the cap is spent. Only the combination does.
|
||||
*/
|
||||
import {
|
||||
buildClaudeExtraUsageConnectionUpdate,
|
||||
isClaudeExtraUsageAllowed,
|
||||
} from "@/lib/providers/claudeExtraUsage";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
|
||||
/** connectionId -> epoch ms at which the spent cap stops being trusted (next billing month). */
|
||||
const spentCapUntil = new Map<string, number>();
|
||||
|
||||
function asRecord(value: unknown): JsonRecord {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
|
||||
}
|
||||
|
||||
/** First instant of the next UTC month: where Anthropic's monthly spend cap rolls over. */
|
||||
function nextBillingMonthStartMs(now: number): number {
|
||||
const d = new Date(now);
|
||||
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1);
|
||||
}
|
||||
|
||||
/** True when the payload says extra usage is enabled and its monthly cap is fully spent. */
|
||||
export function isClaudeExtraUsageCapSpent(extraUsage: unknown): boolean {
|
||||
const eu = asRecord(extraUsage);
|
||||
if (eu.is_enabled !== true) return false;
|
||||
const { monthly_limit: limit, used_credits: used, utilization } = eu;
|
||||
if (typeof limit === "number" && limit > 0 && typeof used === "number") return used >= limit;
|
||||
return typeof utilization === "number" && utilization >= 100;
|
||||
}
|
||||
|
||||
/** Record the cap state from a fresh usage reading (a non-spent reading clears it). */
|
||||
export function recordClaudeExtraUsageCap(
|
||||
connectionId: string,
|
||||
provider: string | null | undefined,
|
||||
usage: unknown,
|
||||
now: number = Date.now()
|
||||
): void {
|
||||
if (provider !== "claude" || !connectionId) return;
|
||||
const record = asRecord(usage);
|
||||
if (!Object.prototype.hasOwnProperty.call(record, "extraUsage")) return;
|
||||
if (isClaudeExtraUsageCapSpent(record.extraUsage)) {
|
||||
spentCapUntil.set(connectionId, nextBillingMonthStartMs(now));
|
||||
} else {
|
||||
spentCapUntil.delete(connectionId);
|
||||
}
|
||||
}
|
||||
|
||||
/** True while the last reading showed a spent cap and the billing month has not rolled over. */
|
||||
export function isClaudeExtraUsageCapKnownSpent(
|
||||
connectionId: string,
|
||||
now: number = Date.now()
|
||||
): boolean {
|
||||
const until = spentCapUntil.get(connectionId);
|
||||
if (until === undefined) return false;
|
||||
if (now >= until) {
|
||||
spentCapUntil.delete(connectionId);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the operator's extra-usage opt-in makes cached plan windows irrelevant for this request.
|
||||
* It stops doing so once the monthly cap is known spent: the account then has no pay-as-you-go
|
||||
* headroom left, so the plan-window check applies again (exhausted plan windows + spent cap).
|
||||
*/
|
||||
export function isClaudeExtraUsageBypassingQuota(
|
||||
connectionId: string,
|
||||
provider: string,
|
||||
providerSpecificData: unknown
|
||||
): boolean {
|
||||
return (
|
||||
isClaudeExtraUsageAllowed(provider, providerSpecificData) &&
|
||||
!isClaudeExtraUsageCapKnownSpent(connectionId)
|
||||
);
|
||||
}
|
||||
|
||||
/** Records the cap, then builds the connection's extra-usage state update (one call site). */
|
||||
export function trackCapAndBuildClaudeExtraUsageUpdate(
|
||||
connection: Parameters<typeof buildClaudeExtraUsageConnectionUpdate>[0] & { id: string },
|
||||
usage: JsonRecord
|
||||
) {
|
||||
recordClaudeExtraUsageCap(connection.id, connection.provider, usage);
|
||||
return buildClaudeExtraUsageConnectionUpdate(connection, usage);
|
||||
}
|
||||
|
||||
export function __resetClaudeExtraUsageCapForTests(): void {
|
||||
spentCapUntil.clear();
|
||||
}
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
type CodexPersistedQuotaState,
|
||||
} from "@omniroute/open-sse/services/codexAccount/index.ts";
|
||||
import { selectAntigravityQuotaWindowNames } from "@omniroute/open-sse/services/antigravityQuotaFamily.ts";
|
||||
import { isClaudeExtraUsageAllowed } from "@/lib/providers/claudeExtraUsage";
|
||||
import { isClaudeExtraUsageBypassingQuota } from "./claudeExtraUsageCap";
|
||||
import { filterCodexQuotaWindows } from "@omniroute/open-sse/services/codexQuotaWindowPolicy.ts";
|
||||
import { isCodexQuotaFilteringDisabled } from "@/lib/providers/codexQuotaFiltering";
|
||||
import { resolveProviderId } from "@/shared/constants/providers";
|
||||
@@ -759,7 +759,7 @@ function isQuotaFilterBypassed(
|
||||
if (provider === "codex") getQuotaCache(connectionId); // expire a replaced owner's override
|
||||
if (isQuotaHealthy(connectionId)) return true;
|
||||
if (isCodexQuotaFilteringDisabled(provider, providerSpecificData)) return true;
|
||||
if (isClaudeExtraUsageAllowed(provider, providerSpecificData)) return true;
|
||||
if (isClaudeExtraUsageBypassingQuota(connectionId, provider, providerSpecificData)) return true;
|
||||
// Subscription snapshots cannot decide paid-credit eligibility. The mandatory
|
||||
// Codex preflight checks the credit balance before dispatch; cooldowns remain separate.
|
||||
return isCodexPaidCreditsEnabled(provider, providerSpecificData, requestedModel);
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
} from "@/lib/db/providerLimits";
|
||||
import { syncToCloud } from "@/lib/cloudSync";
|
||||
import { setQuotaCache } from "@/domain/quotaCache";
|
||||
import { buildClaudeExtraUsageConnectionUpdate } from "@/lib/providers/claudeExtraUsage";
|
||||
import { trackCapAndBuildClaudeExtraUsageUpdate } from "@/domain/claudeExtraUsageCap";
|
||||
import { clearRecoveredProviderState } from "@/sse/services/auth";
|
||||
import { hasObservedClaudeQuotaResetAfter } from "@/lib/db/quotaResetEvents";
|
||||
import {
|
||||
@@ -722,7 +722,7 @@ async function syncClaudeExtraUsageStateIfNeeded(
|
||||
connection: ProviderConnectionLike,
|
||||
usage: JsonRecord
|
||||
): Promise<ProviderConnectionLike> {
|
||||
const update = buildClaudeExtraUsageConnectionUpdate(connection, usage);
|
||||
const update = trackCapAndBuildClaudeExtraUsageUpdate(connection, usage);
|
||||
if (!update) return connection;
|
||||
|
||||
await updateProviderConnection(connection.id, update);
|
||||
|
||||
104
tests/unit/claude-extra-usage-cap-preflight-18059.test.ts
Normal file
104
tests/unit/claude-extra-usage-cap-preflight-18059.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-18059-"));
|
||||
process.env.DATA_DIR = TEST_DATA_DIR;
|
||||
process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "test-18059-secret";
|
||||
|
||||
const core = await import("../../src/lib/db/core.ts");
|
||||
const quotaCache = await import("../../src/domain/quotaCache.ts");
|
||||
const cap = await import("../../src/domain/claudeExtraUsageCap.ts");
|
||||
const { normalizeClaudeUsageQuotas } = await import("../../open-sse/services/usage/claudeQuota.ts");
|
||||
|
||||
test.after(() => {
|
||||
core.resetDbInstance();
|
||||
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test.beforeEach(() => cap.__resetClaudeExtraUsageCapForTests());
|
||||
|
||||
const R = new Date(Date.now() + 3 * 24 * 3600 * 1000).toISOString();
|
||||
const CAP_SPENT = {
|
||||
is_enabled: true,
|
||||
monthly_limit: 5000,
|
||||
used_credits: 5000,
|
||||
utilization: 100,
|
||||
decimal_places: 2,
|
||||
};
|
||||
const PLAN_EXHAUSTED = {
|
||||
five_hour: { utilization: 100, resets_at: R },
|
||||
seven_day: { utilization: 100, resets_at: R },
|
||||
};
|
||||
const PLAN_ROOM = {
|
||||
five_hour: { utilization: 10, resets_at: R },
|
||||
seven_day: { utilization: 20, resets_at: R },
|
||||
};
|
||||
const OPT_IN = { blockExtraUsage: false };
|
||||
|
||||
function load(id: string, payload: Record<string, unknown>, extraUsage: unknown) {
|
||||
const usage = { ...normalizeClaudeUsageQuotas(payload), extraUsage };
|
||||
quotaCache.setQuotaCache(
|
||||
id,
|
||||
"claude",
|
||||
usage.quotas as Record<string, unknown>,
|
||||
usage.modelQuotas as Record<string, unknown>
|
||||
);
|
||||
cap.recordClaudeExtraUsageCap(id, "claude", usage);
|
||||
}
|
||||
|
||||
test("opt-in, plan windows exhausted AND monthly cap spent -> excluded pre-dispatch", () => {
|
||||
load("c-gap", PLAN_EXHAUSTED, CAP_SPENT);
|
||||
assert.equal(
|
||||
quotaCache.isQuotaExhaustedForRequest("c-gap", "claude", "claude-opus-4-5", OPT_IN),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test("opt-in, plan windows exhausted, cap has room -> stays eligible", () => {
|
||||
load("c-room", PLAN_EXHAUSTED, { ...CAP_SPENT, used_credits: 1000, utilization: 20 });
|
||||
assert.equal(
|
||||
quotaCache.isQuotaExhaustedForRequest("c-room", "claude", "claude-opus-4-5", OPT_IN),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("opt-in, plan has room + cap spent -> stays eligible (never block on the cap alone)", () => {
|
||||
load("c-plan-room", PLAN_ROOM, CAP_SPENT);
|
||||
assert.equal(
|
||||
quotaCache.isQuotaExhaustedForRequest("c-plan-room", "claude", "claude-opus-4-5", OPT_IN),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("default policy keeps excluding exhausted plan windows (unchanged)", () => {
|
||||
load("c-ctrl", PLAN_EXHAUSTED, CAP_SPENT);
|
||||
assert.equal(
|
||||
quotaCache.isQuotaExhaustedForRequest("c-ctrl", "claude", "claude-opus-4-5", {}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test("a fresh reading with cap room clears the spent state", () => {
|
||||
load("c-clear", PLAN_EXHAUSTED, CAP_SPENT);
|
||||
load("c-clear", PLAN_EXHAUSTED, { ...CAP_SPENT, used_credits: 0, utilization: 0 });
|
||||
assert.equal(
|
||||
quotaCache.isQuotaExhaustedForRequest("c-clear", "claude", "claude-opus-4-5", OPT_IN),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test("spent cap is ignored after the billing month rolls over", () => {
|
||||
const now = Date.UTC(2026, 10, 19);
|
||||
cap.recordClaudeExtraUsageCap("c-roll", "claude", { extraUsage: CAP_SPENT }, now);
|
||||
assert.equal(cap.isClaudeExtraUsageCapKnownSpent("c-roll", now + 1000), true);
|
||||
assert.equal(cap.isClaudeExtraUsageCapKnownSpent("c-roll", Date.UTC(2026, 11, 1)), false);
|
||||
});
|
||||
|
||||
test("cap detection: disabled extra usage or missing fields is not spent", () => {
|
||||
assert.equal(cap.isClaudeExtraUsageCapSpent({ ...CAP_SPENT, is_enabled: false }), false);
|
||||
assert.equal(cap.isClaudeExtraUsageCapSpent(undefined), false);
|
||||
assert.equal(cap.isClaudeExtraUsageCapSpent({ is_enabled: true, utilization: 100 }), true);
|
||||
});
|
||||
Reference in New Issue
Block a user