Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix runtime skip deactivated accounts
  • Loading branch information
ndycode committed May 1, 2026
commit ebb901171c19ed649adcd40eead5288d87fd864b
23 changes: 15 additions & 8 deletions lib/request/fetch-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,13 +328,25 @@ export function isWorkspaceDisabledError(
code: unknown,
bodyText: string,
): boolean {
const normalizedCode = typeof code === "string" ? code.trim().toLowerCase() : "";
const haystack = `${normalizedCode} ${bodyText}`.toLowerCase();
const normalizedTokens = normalizedCode
.split(/[^a-z0-9_]+/i)
.map((token) => token.trim())
.filter((token) => token.length > 0);

if (status === 402) {
return (
normalizedCode === "deactivated_workspace" ||
normalizedTokens.includes("deactivated_workspace") ||
/\bdeactivated_workspace\b/i.test(bodyText)
);
}

if (status !== 403) {
return false;
}

const normalizedCode = typeof code === "string" ? code.trim().toLowerCase() : "";
const haystack = `${normalizedCode} ${bodyText}`.toLowerCase();

const disabledPatterns = [
/workspace.*(?:disabled|expired|deactivated|terminated)/i,
/account\s+(?:has\s+been|is)\s+(?:disabled|expired|deactivated|terminated|closed)/i,
Expand Down Expand Up @@ -362,11 +374,6 @@ export function isWorkspaceDisabledError(
return true;
}

const normalizedTokens = normalizedCode
.split(/[^a-z0-9_]+/i)
.map((token) => token.trim())
.filter((token) => token.length > 0);

return normalizedTokens.some((token) => workspaceErrorCodes.has(token));
}

Expand Down
78 changes: 73 additions & 5 deletions lib/runtime-rotation-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
loadRuntimePolicyState,
type RuntimePolicyDecision,
} from "./policy/runtime-policy.js";
import { isWorkspaceDisabledError } from "./request/fetch-helpers.js";
import { SessionAffinityStore } from "./session-affinity.js";
import type { OAuthAuthDetails, RequestBody, TokenResult } from "./types.js";
import { isRecord } from "./utils.js";
Expand Down Expand Up @@ -91,6 +92,7 @@ type ExhaustionReason =
| "network-error"
| "auth-failure"
| "budget"
| "deactivated"
| "no-account";
type RuntimeProxyHttpError = Error & {
statusCode: number;
Expand Down Expand Up @@ -558,6 +560,26 @@ async function readErrorBody(response: Response): Promise<string> {
}
}

function extractErrorCodeFromBody(bodyText: string): string | null {
if (!bodyText.trim()) return null;
try {
const parsed = JSON.parse(bodyText) as unknown;
if (!isRecord(parsed)) return null;
const directCode = parsed.code;
if (typeof directCode === "string" && directCode.trim()) {
return directCode.trim();
}
const maybeError = parsed.error;
if (!isRecord(maybeError)) return null;
const nestedCode = maybeError.code;
return typeof nestedCode === "string" && nestedCode.trim()
? nestedCode.trim()
: null;
} catch {
return null;
}
}

function getQuotaWindowWaitMs(headers: Headers, prefix: string, now: number): number {
const resetAfterSeconds = Number.parseInt(
headers.get(`${prefix}-reset-after-seconds`) ?? "",
Expand Down Expand Up @@ -923,12 +945,17 @@ export async function startRuntimeRotationProxy(
);
const attemptedIndexes = new Set<number>();
let exhaustionReason: ExhaustionReason = "no-account";
const accountAttemptLimit = Math.max(
const accountCount = accountManager.getAccountCount();
const transientAttemptLimit = Math.max(
1,
Math.min(accountManager.getAccountCount(), maxRuntimeAccountAttempts),
Math.min(accountCount, maxRuntimeAccountAttempts),
);
let transientAttempts = 0;

while (attemptedIndexes.size < accountAttemptLimit) {
while (
attemptedIndexes.size < accountCount &&
transientAttempts < transientAttemptLimit
) {
const selected = chooseAccount({
accountManager,
sessionAffinityStore,
Expand Down Expand Up @@ -959,6 +986,7 @@ export async function startRuntimeRotationProxy(
accountManager.refundToken(selected, context.family, context.model);
exhaustionReason = "auth-failure";
if (!refreshed.retryable) continue;
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -974,6 +1002,7 @@ export async function startRuntimeRotationProxy(
"auth-failure",
);
exhaustionReason = "auth-failure";
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
Expand Down Expand Up @@ -1018,6 +1047,7 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "network-error";
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -1041,11 +1071,46 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "rate-limit";
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
}

if (upstream.status === 402 || upstream.status === HTTP_STATUS.FORBIDDEN) {
const bodyText = await readErrorBody(upstream);
const errorCode = extractErrorCodeFromBody(bodyText);
if (isWorkspaceDisabledError(upstream.status, errorCode, bodyText)) {
accountManager.refundToken(
refreshed.account,
context.family,
context.model,
);
accountManager.recordFailure(
refreshed.account,
context.family,
context.model,
);
accountManager.setAccountEnabled(refreshed.account.index, false);
sessionAffinityStore?.forgetSession(context.sessionKey);
accountManager.saveToDiskDebounced();
exhaustionReason = "deactivated";
status.retries += 1;
status.rotations += 1;
continue;
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

res.writeHead(upstream.status, responseHeadersForClient(upstream.headers));
res.end(bodyText);
await usageRecorder.record({
outcome: "failure",
statusCode: upstream.status,
errorCode,
account: refreshed.account,
});
return;
}

if (upstream.status === HTTP_STATUS.UNAUTHORIZED) {
await readErrorBody(upstream);
accountManager.refundToken(refreshed.account, context.family, context.model);
Expand All @@ -1057,6 +1122,7 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "auth-failure";
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -1073,6 +1139,7 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "server-error";
transientAttempts += 1;
status.retries += 1;
status.rotations += 1;
continue;
Expand Down Expand Up @@ -1137,8 +1204,9 @@ export async function startRuntimeRotationProxy(
}

if (
attemptedIndexes.size >= accountAttemptLimit &&
accountAttemptLimit < accountManager.getAccountCount()
transientAttempts >= transientAttemptLimit &&
attemptedIndexes.size < accountCount &&
exhaustionReason !== "deactivated"
) {
exhaustionReason = "budget";
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Expand Down
11 changes: 10 additions & 1 deletion test/fetch-helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,12 +688,21 @@ describe('isWorkspaceDisabledError', () => {
expect(isWorkspaceDisabledError(403, 'error.usage_not_included', '')).toBe(false);
});

it('returns false for non-403 status even with disabled message', () => {
it('returns true for 402 deactivated_workspace signals', () => {
expect(isWorkspaceDisabledError(402, 'deactivated_workspace', '')).toBe(true);
expect(isWorkspaceDisabledError(402, 'error.deactivated_workspace', '')).toBe(true);
expect(
isWorkspaceDisabledError(402, '', '{"error":{"code":"deactivated_workspace"}}'),
).toBe(true);
});

it('returns false for statuses without supported disabled signals', () => {
expect(isWorkspaceDisabledError(400, '', 'Your workspace has been disabled')).toBe(false);
expect(isWorkspaceDisabledError(401, '', 'Your workspace has been disabled')).toBe(false);
expect(isWorkspaceDisabledError(500, '', 'Your workspace has been disabled')).toBe(false);
expect(isWorkspaceDisabledError(400, 'workspace_disabled', '')).toBe(false);
expect(isWorkspaceDisabledError(402, 'payment_required', '')).toBe(false);
expect(isWorkspaceDisabledError(402, '', 'Your workspace has been disabled')).toBe(false);
});

it('returns false for 403 with unrelated messages', () => {
Expand Down
113 changes: 113 additions & 0 deletions test/runtime-rotation-proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,119 @@ describe("runtime rotation proxy", () => {
expect(proxy.getStatus().retries).toBe(1);
});

it("disables a deactivated workspace account and rebinds session affinity", async () => {
const now = Date.now();
const persisted: AccountStorageV3[] = [];
withAccountStorageTransactionMock.mockImplementation(async (handler) =>
handler(null, async (storage: AccountStorageV3) => {
persisted.push(structuredClone(storage));
}),
);
const accountManager = new AccountManager(undefined, createStorage(now, 2));
const { calls, fetchImpl } = createRecordingFetch((_call, attempt) => {
if (attempt === 1) {
return new Response(
JSON.stringify({ error: { code: "deactivated_workspace" } }),
{
status: 402,
headers: { "content-type": "application/json" },
},
);
}
return textEventStream("data: recovered\n\n");
});
const proxy = await startProxy({ accountManager, fetchImpl });
const body = {
model: "gpt-5-codex",
stream: true,
metadata: { session_id: "thread-deactivated" },
};

const first = await postResponses(proxy, body);
expect(first.status).toBe(HTTP_STATUS.OK);
expect(await first.text()).toBe("data: recovered\n\n");
const second = await postResponses(proxy, body);
expect(second.status).toBe(HTTP_STATUS.OK);
await second.text();
await accountManager.flushPendingSave();

expect(calls.map((call) => call.headers.get(OPENAI_HEADERS.ACCOUNT_ID))).toEqual([
"acc_1",
"acc_2",
"acc_2",
]);
expect(accountManager.getAccountByIndex(0)?.enabled).toBe(false);
expect(accountManager.getAccountByIndex(1)?.enabled).toBe(true);
expect(proxy.getStatus()).toMatchObject({
retries: 1,
rotations: 1,
lastAccountIndex: 1,
});
expect(persisted.at(-1)?.accounts[0]?.enabled).toBe(false);

const reloadedStorage = persisted.at(-1);
expect(reloadedStorage).toBeDefined();
if (!reloadedStorage) throw new Error("expected persisted storage");
const reloadedManager = new AccountManager(undefined, reloadedStorage);
const reloadedFetch = createRecordingFetch(() => textEventStream("data: restart\n\n"));
const reloadedProxy = await startProxy({
accountManager: reloadedManager,
fetchImpl: reloadedFetch.fetchImpl,
});

await (await postResponses(reloadedProxy, { model: "gpt-5-codex" })).text();

expect(
reloadedFetch.calls.map((call) => call.headers.get(OPENAI_HEADERS.ACCOUNT_ID)),
).toEqual(["acc_2"]);
});

it("returns pool exhaustion after all accounts are deactivated", async () => {
const now = Date.now();
const accountManager = new AccountManager(undefined, createStorage(now, 6));
const { calls, fetchImpl } = createRecordingFetch(() =>
new Response(JSON.stringify({ error: { code: "deactivated_workspace" } }), {
status: 402,
headers: { "content-type": "application/json" },
}),
);
const proxy = await startProxy({ accountManager, fetchImpl });

const response = await postResponses(proxy, { model: "gpt-5-codex" });
const payload = (await response.json()) as { error: { code: string; reason: string } };

expect(response.status).toBe(HTTP_STATUS.SERVICE_UNAVAILABLE);
expect(payload.error).toMatchObject({
code: "codex_runtime_rotation_pool_exhausted",
reason: "deactivated",
});
expect(calls).toHaveLength(6);
expect(accountManager.getAccountsSnapshot().every((account) => account.enabled === false)).toBe(
true,
);
});

it("forwards unrelated 402 errors without disabling the account", async () => {
const now = Date.now();
const accountManager = new AccountManager(undefined, createStorage(now, 2));
const { calls, fetchImpl } = createRecordingFetch(() =>
new Response(JSON.stringify({ error: { code: "payment_required" } }), {
status: 402,
headers: { "content-type": "application/json" },
}),
);
const proxy = await startProxy({ accountManager, fetchImpl });

const response = await postResponses(proxy, { model: "gpt-5-codex" });
const payload = (await response.json()) as { error: { code: string } };

expect(response.status).toBe(402);
expect(payload.error.code).toBe("payment_required");
expect(calls).toHaveLength(1);
expect(accountManager.getAccountByIndex(0)?.enabled).toBe(true);
expect(accountManager.getAccountByIndex(1)?.enabled).toBe(true);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

it("persists cooldowns so a restarted proxy avoids limited accounts", async () => {
const now = Date.now();
const persisted: AccountStorageV3[] = [];
Expand Down