Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
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
90 changes: 85 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,18 @@ 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;
let transientExhaustionReason: ExhaustionReason | null = null;

while (attemptedIndexes.size < accountAttemptLimit) {
while (
attemptedIndexes.size < accountCount &&
transientAttempts < transientAttemptLimit
) {
const selected = chooseAccount({
accountManager,
sessionAffinityStore,
Expand Down Expand Up @@ -959,6 +987,8 @@ export async function startRuntimeRotationProxy(
accountManager.refundToken(selected, context.family, context.model);
exhaustionReason = "auth-failure";
if (!refreshed.retryable) continue;
transientAttempts += 1;
transientExhaustionReason = "auth-failure";
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -974,6 +1004,8 @@ export async function startRuntimeRotationProxy(
"auth-failure",
);
exhaustionReason = "auth-failure";
transientAttempts += 1;
transientExhaustionReason = "auth-failure";
status.retries += 1;
status.rotations += 1;
continue;
Expand Down Expand Up @@ -1018,6 +1050,8 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "network-error";
transientAttempts += 1;
transientExhaustionReason = "network-error";
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -1041,11 +1075,47 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "rate-limit";
transientAttempts += 1;
transientExhaustionReason = "rate-limit";
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 +1127,8 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "auth-failure";
transientAttempts += 1;
transientExhaustionReason = "auth-failure";
status.retries += 1;
status.rotations += 1;
continue;
Expand All @@ -1073,6 +1145,8 @@ export async function startRuntimeRotationProxy(
);
accountManager.saveToDiskDebounced();
exhaustionReason = "server-error";
transientAttempts += 1;
transientExhaustionReason = "server-error";
status.retries += 1;
status.rotations += 1;
continue;
Expand Down Expand Up @@ -1137,10 +1211,16 @@ export async function startRuntimeRotationProxy(
}

if (
attemptedIndexes.size >= accountAttemptLimit &&
accountAttemptLimit < accountManager.getAccountCount()
transientAttempts >= transientAttemptLimit &&
attemptedIndexes.size < accountCount &&
exhaustionReason !== "deactivated"
) {
exhaustionReason = "budget";
} else if (
exhaustionReason === "deactivated" &&
transientExhaustionReason
) {
exhaustionReason = transientExhaustionReason;
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

await usageRecorder?.record({
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
Loading