Skip to content
TypeScript

fix(server): a /compact stopped by the Claude usage limit now fails (#19583)

Scott Norteman499c9ee68b28
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 1344dc94276..fb5e867af78 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -3385,6 +3385,104 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect.each([
+ {
+ name: "fails a /compact the usage limit stopped",
+ limited: true,
+ compaction: "failed",
+ compact: true,
+ status: "failed",
+ },
+ {
+ name: "completes an unlimited failed /compact",
+ limited: false,
+ compaction: "failed",
+ compact: true,
+ status: "completed",
+ },
+ {
+ name: "completes a successful limited /compact",
+ limited: true,
+ compaction: "success",
+ compact: true,
+ status: "completed",
+ },
+ {
+ name: "completes a failed automatic compaction",
+ limited: true,
+ compaction: "failed",
+ compact: false,
+ status: "completed",
+ },
+ ] as const)("$name", ({ name, limited, compaction, compact, status }) =>
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ const resetsAt = 1791991200;
+ const compactError =
+ "Error during compaction: You've hit your session limit · resets 5:20pm (Europe/Berlin).";
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make(`attempt-claude-compaction-${name}`),
+ text: compact ? "/compact" : "Continue.",
+ attachments: [],
+ }),
+ );
+ // Claude reports a compaction's outcome on a status frame. A /compact
+ // then ends with a success result naming the command and no terminal
+ // reason, even when the compaction failed (#19327). The automatic case
+ // omits the terminal reason too, so only the missing command keeps it
+ // completed.
+ const result = makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000613",
+ result: compact ? "" : "Done.",
+ numTurns: compact ? 0 : 1,
+ terminalReason: null,
+ });
+ yield* Queue.offerAll(harness.sdkMessages, [
+ ...(limited
+ ? [
+ claudeSdkFrame({
+ type: "rate_limit_event",
+ rate_limit_info: { status: "rejected", rateLimitType: "five_hour", resetsAt },
+ uuid: "00000000-0000-4000-8000-000000000611",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ ]
+ : []),
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: null,
+ compact_result: compaction,
+ ...(compaction === "failed"
+ ? { compact_error: limited ? compactError : "Not enough messages to compact." }
+ : {}),
+ uuid: "00000000-0000-4000-8000-000000000612",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ compact ? claudeSdkFrame({ ...result, local_command: "compact" }) : result,
+ ]);
+
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal.status, status);
+ if (terminal.status !== "failed") return;
+ assert.equal(terminal.failure.class, "usage_limit");
+ assert.equal(terminal.failure.message, compactError);
+ assert.equal(
+ terminal.failure.resetAt,
+ DateTime.formatIso(DateTime.makeUnsafe(resetsAt * 1000)),
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
it.effect.each([
{ name: "parent limit", parentErrors: ["rate_limit"], expectedLimit: true },
{
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 00c48c61f4c..339a99f3d3e 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -2997,6 +2997,9 @@ interface ActiveClaudeTurnContext {
readonly rejectedRateLimitTypes: Set<string>;
readonly rateLimitResetTimes: Map<string, string | null>;
latestAssistantRateLimited: boolean;
+ // 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;
// Usage of the results that steers ended, oldest first. The final result's
// usage covers only its own segment, so the turn bills these as well.
readonly steeredSegmentUsage: Array<SDKResultMessage["usage"]>;
@@ -7010,6 +7013,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
}
}
+ if (
+ message.type === "system" &&
+ message.subtype === "status" &&
+ message.compact_result !== undefined
+ ) {
+ context.compactionFailure =
+ message.compact_result === "failed" ? { message: message.compact_error } : null;
+ }
+
if (message.type === "system" && message.subtype === "compact_boundary") {
const now = yield* DateTime.now;
const nativeItemId = message.uuid;
@@ -7749,6 +7761,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
(usageLimited
? "Claude usage limit reached. Send the message again once the limit resets."
: undefined));
+ // A /compact the usage limit stopped still ends in a success
+ // result. Failing the turn lets the usage-limit guard hold queued
+ // messages instead of sending them into the same limit (#19327).
+ const limitedCompaction =
+ usageLimited && message.subtype === "success" && message.local_command === "compact"
+ ? context.compactionFailure
+ : null;
const resetTimes = Array.from(context.rateLimitResetTimes.values());
const resetAt =
resetTimes.length > 0 && resetTimes.every((time) => time !== null)
@@ -7756,14 +7775,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
: null;
const resultFailure = interrupted
? null
- : providerFailureFromResult(message, completedAt, failureHint, usageLimited);
+ : limitedCompaction !== null
+ ? makeProviderFailure({
+ class: "usage_limit",
+ message: limitedCompaction.message ?? failureHint,
+ code: "compaction_failed",
+ })
+ : providerFailureFromResult(message, completedAt, failureHint, usageLimited);
const terminalFailure =
resultFailure?.class === "usage_limit"
? { ...resultFailure, resetAt: resetAt ?? resultFailure.resetAt ?? null }
: resultFailure;
yield* finalizeActiveTurn({
context,
- status: interrupted ? "interrupted" : terminalStatusFromResult(message, failureHint),
+ status: interrupted
+ ? "interrupted"
+ : limitedCompaction !== null
+ ? "failed"
+ : terminalStatusFromResult(message, failureHint),
completedAt,
result: message,
...(terminalFailure === null ? {} : { failure: terminalFailure }),
@@ -8586,6 +8615,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
rejectedRateLimitTypes: new Set(),
rateLimitResetTimes: new Map(),
latestAssistantRateLimited: false,
+ compactionFailure: null,
steeredSegmentUsage: [],
subagentsByTaskId: new Map(),
subagentsByToolUseId: new Map(),