diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 63e3145622e34..6a338aa967f58 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -12767,6 +12767,130 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // t4 fork (AI-151): usa-rs USA-3134 (2026-11-24). Account 1 hit its 5-hour limit, and its + // process answered a background notice with the same refusal after the turn had ended; that + // sat in the wake buffer. The thread moved to account 2, and the next wake replayed the old + // refusal there - and marked account 2 used up, though it had 83% left. + it.effect("marks a replayed refusal on the account that sent it, not the next one", () => + Effect.gen(function* () { + const dir = NodeFS.mkdtempSync(NodePath.join(process.env.TMPDIR ?? "/tmp", "t4-acct-")); + NodeFS.writeFileSync(NodePath.join(dir, "1.token"), "token-one\n"); + NodeFS.writeFileSync(NodePath.join(dir, "2.token"), "token-two\n"); + const saved = process.env.T4_CLAUDE_ACCOUNTS; + process.env.T4_CLAUDE_ACCOUNTS = `${dir}/1.token,${dir}/2.token`; + resetClaudeAccountState(); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (saved === undefined) delete process.env.T4_CLAUDE_ACCOUNTS; + else process.env.T4_CLAUDE_ACCOUNTS = saved; + resetClaudeAccountState(); + }), + ); + const readState = () => + JSON.parse(NodeFS.readFileSync(NodePath.join(dir, "state.json"), "utf8")) as { + readonly exhaustedUntil: Record; + }; + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); + const now = yield* DateTime.now; + const resetsAt = Math.floor(DateTime.toEpochMillis(now) / 1000) + 3 * 3_600; + const refusal = (uuid: string) => + makeAssistantErrorFrame({ + uuid, + error: "rate_limit", + text: "You've hit your 5-hour limit", + apiErrorParams: { + rate_limit_info: { status: "rejected", rateLimitType: "five_hour", resetsAt }, + }, + }); + + // Account 1: the turn starts a background check and hits the limit. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-t4-replayed-limit-1"), + text: "Run the check in the background.", + attachments: [], + }), + ); + yield* Queue.offerAll(harness.sdkMessages, [ + wakeTaskStarted, + refusal("00000000-0000-4000-8000-000000000b01"), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000b02", + result: "You've hit your 5-hour limit", + isError: true, + apiErrorStatus: 429, + terminalReason: "api_error", + }), + ]); + const first = yield* Queue.take(harness.terminalReceipts); + assert.equal(first.status, "failed"); + assert.deepEqual(Object.keys(readState().exhaustedUntil), ["1"]); + + // Account 1's process answers the background notice with the refusal again: buffered. + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(refusal("00000000-0000-4000-8000-000000000b03")); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000b04", + result: "You've hit your 5-hour limit", + isError: true, + apiErrorStatus: 429, + terminalReason: "api_error", + origin: { kind: "task-notification" }, + }), + ); + + // The user's next turn opens a process on account 2, which works. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-t4-replayed-limit-2"), + text: "Continue where you left off.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + assert.lengthOf(harness.processQueues, 2); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000b05", result: "Done." }), + ); + const second = yield* Queue.take(harness.terminalReceipts); + assert.equal(second.status, "completed"); + + // The next wake drains the buffer on account 2's process. + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-t4-replayed-limit-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.deepEqual(Object.keys(readState().exhaustedUntil), ["1"]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + const providerThreadRosterEvents = ( events: ReadonlyArray, ) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5b46115937242..878e4bc6b1726 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5203,6 +5203,10 @@ interface ActiveClaudeTurnContext { readonly type: string | null; readonly resetAt: string | null; } | null; + // t4 fork (AI-151): the Claude account whose process sent this turn's limit evidence. A wake + // buffer outlives a process replaced for the same session, so a continuation on the next + // account can replay the old account's refusal; the old account is the one used up. + t4LimitAccount: string | null; // Set while this turn's latest compaction status reports a failure, with // Claude's error text when it sent one. compactionFailure: { readonly message: string | undefined } | null; @@ -6147,6 +6151,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); // A gateway's relative reset counts from the result's arrival, not its replay. const bufferedResultArrivals = new WeakMap(); + // t4 fork (AI-151): the Claude account of the process that sent a buffered frame. + const bufferedFrameAccounts = new WeakMap(); const wakeBuffers = yield* Ref.make( new Map< string, @@ -10241,6 +10247,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (message.type === "result") { bufferedResultArrivals.set(message, yield* DateTime.now); } + const bufferingAccount = (yield* Ref.get(queryContext))?.t4Account; + if (bufferingAccount !== undefined && !bufferedFrameAccounts.has(message)) { + bufferedFrameAccounts.set(message, bufferingAccount); + } if (isClaudeRootTurnFrame(message)) { yield* forgetAbsorbedWake(wakeInput.nativeThreadId); } @@ -10825,6 +10835,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const blocked = rateLimitInfo.status === "rejected" && !overageAllowed; const limitType = rateLimitInfo.rateLimitType ?? "unknown"; if (blocked) { + context.t4LimitAccount = bufferedFrameAccounts.get(message) ?? liveQuery.t4Account; context.rejectedRateLimitTypes.add(limitType); context.rateLimitResetTimes.set( limitType, @@ -10849,7 +10860,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const notice = t4Live !== null && anotherClaudeAccountFree( - t4Live.t4Account, + context.t4LimitAccount ?? t4Live.t4Account, DateTime.toEpochMillis(now), process.env, limitType === FABLE_RATE_LIMIT_TYPE ? t4Live.selection.apiModelId : null, @@ -11199,6 +11210,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.nativeMessageCursor = message.uuid; context.latestAssistantRateLimit = message.error === "rate_limit" ? { type: null, resetAt: null } : null; + if (message.error === "rate_limit") { + context.t4LimitAccount = bufferedFrameAccounts.get(message) ?? liveQuery.t4Account; + } if (message.error === "rate_limit" && isClaudeBlockedAssistantRateLimit(message)) { const info = message.api_error_params.rate_limit_info; const overageAllowed = @@ -12267,10 +12281,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( [...t4LimitTypes].every((type) => type === FABLE_RATE_LIMIT_TYPE) ? ("fable" as const) : ("all" as const); + const t4LimitAccount = + context.t4LimitAccount ?? bufferedFrameAccounts.get(message) ?? liveQuery.t4Account; const t4ResumeAtMs = usageLimited && !interrupted ? markClaudeAccountExhausted( - liveQuery.t4Account, + t4LimitAccount, claudeResetAt === null ? null : Date.parse(claudeResetAt), DateTime.toEpochMillis(completedAt), process.env, @@ -12280,7 +12296,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (t4ResumeAtMs !== undefined) { yield* Effect.logInfo("t4.claude-account-limit", { threadId: context.input.threadId, - account: liveQuery.t4Account, + account: t4LimitAccount, + ...(t4LimitAccount === liveQuery.t4Account + ? {} + : { processAccount: liveQuery.t4Account }), scope: t4LimitScope, resetAt: claudeResetAt, }); @@ -12303,7 +12322,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (terminalFailure?.class === "usage_limit") { next.set(liveQuery.nativeThreadId, { failure: terminalFailure, - account: liveQuery.t4Account, + account: t4LimitAccount, claudeResetAt, scope: t4LimitScope, }); @@ -13769,6 +13788,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( rejectedRateLimitTypes: new Set(), rateLimitResetTimes: new Map(), latestAssistantRateLimit: null, + t4LimitAccount: null, compactionFailure: null, nativeSessionTitle: null, steeredSegmentUsage: [],