Skip to content

Active-turn compaction repeats until the turn fails #2017

Open

Description

@dcramer

Problem

Active-turn compaction can repeat in one turn until the turn fails. The turn compacts, does the same work again, and compacts again. Nothing stops a compaction that frees no room for progress.

Evidence

A real-model integration eval (#2001 agent test fixture) sets limits.contextWindowTokens: 24_000. The trigger is then 21,600 tokens. The agent reads three deployment logs of about 7,500 tokens each through an MCP tool:

  1. The agent reads all three logs in one parallel batch. The context is about 37,000 estimated tokens.
  2. Junior compacts it to about 700 tokens. The summary is correct. It has all three results and the current UTC time.
  3. The model reads all three logs again, and the context is over the trigger again.
  4. Steps 2 and 3 repeat 12 to 19 times. The turn then fails with a provider 503 (AI provider error: server) and posts "The model provider had a temporary connection problem."

Compaction details from the reporting API repeat with almost the same values:

{"reason":"capacity","estimatedInputTokens":37231,"replacementInputTokens":724,"triggerTokens":21600,"inputLimitTokens":22800,"inputMessageCount":10,"retainedMessageCount":1,"summaryChars":1293}

The summary also says "All requested information has been successfully retrieved and reported to the user." That is false: no reply was posted.

An 8,000-token window shows the same loop with a single log (19 compactions).

Likely cause

compactActiveContextIfNeeded() in packages/junior/src/chat/services/context-compaction.ts replaces history with:

  1. the runtime turn context
  2. the retained instruction
  3. the summary, as <thread-context authority="evidence-only">

The model sees the instruction and treats the summary as evidence only, so it does the work again. Each repeat of a large tool read makes the same overflow.

Expected

After an active-turn compaction, the agent continues from the summary and finishes the task. A compaction that does not let the turn progress must not repeat without a limit.

Reproduction

The removed eval case and its MCP fixture tool are below. They are not in the #2001 conversation slice, so the fix can add them back as its regression test.

Eval case (evals/integration/conversation/lifecycle.eval.ts)
  test("when tool results fill the context window, compact them and finish the task", async ({
    agent,
  }) => {
    // Three deployment logs are larger than the compaction trigger of this
    // context window, so Junior compacts during the turn.
    const { run } = await agent({
      plugins: defineJuniorPlugins([evalOperation]),
      limits: { contextWindowTokens: 24_000 },
    });
    const conversation = await run(
      mention(
        "Read the deployment logs for checkout-api, payments-api, and search-api with the eval-operation tools. Then tell me which deploys succeeded, and the current UTC time.",
      ),
      {
        criteria: rubric({
          pass: [
            "The reply says checkout-api and search-api succeeded and payments-api failed.",
            "The reply gives the current time in UTC.",
          ],
          fail: [
            "The reply only gives a plan, checkpoint summary, or promise to check later.",
          ],
        }),
      },
    );

    expect(conversation.turns.map((turn) => turn.status)).toEqual([
      "succeeded",
    ]);
    expect(conversation.turns[0]!.compactions).toBeGreaterThan(0);
    expect(completedToolCalls("systemTime", conversation)).not.toHaveLength(0);
    expect(conversation.replies).toHaveLength(1);
  });

The eval-operation plugin also needs deployment-log in allowedTools. The case needs a Turn.compactions count in the fixture results, from compaction report events.

MCP fixture tool and fixture result change
diff --git a/packages/junior-evals/src/fixture/results.ts b/packages/junior-evals/src/fixture/results.ts
index 51911ecbd..2e86921d2 100644
--- a/packages/junior-evals/src/fixture/results.ts
+++ b/packages/junior-evals/src/fixture/results.ts
@@ -61,6 +61,8 @@ export function toolOutput(call: ToolCall): unknown {
 export type TurnStatus = "failed" | "no_reply" | "started" | "succeeded";
 
 export interface Turn {
+  /** Times Junior compacted the context during the turn. */
+  compactions: number;
   replies: Reply[];
   status: TurnStatus;
   toolCalls: ToolCall[];
@@ -129,6 +131,7 @@ export function readCallEvents(args: {
     const data = event.data;
     if (data.type === "turn_lifecycle") {
       const turn = turns.get(data.turnId) ?? {
+        compactions: 0,
         replies: [],
         status: data.state,
         toolCalls: [],
@@ -164,6 +167,10 @@ export function readCallEvents(args: {
       }
       continue;
     }
+    if (data.type === "compaction") {
+      if (currentTurn) currentTurn.compactions += 1;
+      continue;
+    }
     if (data.type === "tool_calls") {
       for (const call of data.calls) {
         const existing = toolCalls.get(call.toolCallId);
diff --git a/packages/junior/tests/msw/handlers/eval-mcp-auth.ts b/packages/junior/tests/msw/handlers/eval-mcp-auth.ts
index 1f3dfc5bc..d9bfd0501 100644
--- a/packages/junior/tests/msw/handlers/eval-mcp-auth.ts
+++ b/packages/junior/tests/msw/handlers/eval-mcp-auth.ts
@@ -37,9 +37,47 @@ let releasePushCalls = 0;
  */
 export const EVAL_RELEASE_PUSH_STALL_MS = 45_000;
 
-function stall(ms: number): Promise<void> {
+/**
+ * Characters in the deployment log. It fills a small context window and stays
+ * under the MCP result limit, so Junior keeps the last line.
+ */
+const EVAL_DEPLOYMENT_LOG_CHARS = 30_000;
+
+/** Result of the latest eval deployment of each service. */
+const EVAL_DEPLOYMENT_RESULTS: Record<string, string> = {
+  "checkout-api": "succeeded, build 4182 is live",
+  "payments-api": "failed, build 977 rolled back after error budget alarm",
+  "search-api": "succeeded, build 2310 is live",
+};
+
+/** A long deployment log whose last line gives the result. */
+function deploymentLog(service: string): string {
+  const result = EVAL_DEPLOYMENT_RESULTS[service];
+  if (!result) return `No deployment found for ${service}.`;
+  const lines: string[] = [];
+  let length = 0;
+  for (let step = 1; length < EVAL_DEPLOYMENT_LOG_CHARS; step += 1) {
+    const line = `[${service}] step ${step}: synced shard ${step % 64}, health check passed`;
+    lines.push(line);
+    length += line.length + 1;
+  }
+  lines.push(`[${service}] RESULT: ${result}`);
+  return lines.join("\n");
+}
+
+/** Wait `ms`, or less when the client drops the request. */
+function stall(ms: number, signal: AbortSignal): Promise<void> {
   return new Promise((resolve) => {
-    setTimeout(resolve, ms).unref();
+    const timer = setTimeout(resolve, ms);
+    timer.unref();
+    signal.addEventListener(
+      "abort",
+      () => {
+        clearTimeout(timer);
+        resolve();
+      },
+      { once: true },
+    );
   });
 }
 
@@ -220,6 +258,23 @@ export const evalMcpAuthHandlers = [
                 additionalProperties: false,
               },
             },
+            {
+              name: "deployment-log",
+              title: "Deployment Log",
+              description:
+                "Return the full log of the latest eval deployment of one service.",
+              inputSchema: {
+                type: "object",
+                properties: {
+                  service: {
+                    type: "string",
+                    enum: Object.keys(EVAL_DEPLOYMENT_RESULTS),
+                  },
+                },
+                required: ["service"],
+                additionalProperties: false,
+              },
+            },
             {
               name: "delete-eval-workspace",
               title: "Delete Eval Workspace",
@@ -443,7 +498,7 @@ export const evalMcpAuthHandlers = [
               isError: true,
             });
           }
-          await stall(EVAL_RELEASE_PUSH_STALL_MS);
+          await stall(EVAL_RELEASE_PUSH_STALL_MS, request.signal);
           return jsonRpcResult(message?.id ?? null, {
             content: [
               {
@@ -457,6 +512,17 @@ export const evalMcpAuthHandlers = [
             isError: false,
           });
         }
+        if (toolName === "deployment-log") {
+          return jsonRpcResult(message?.id ?? null, {
+            content: [
+              {
+                type: "text",
+                text: deploymentLog(String(args?.service ?? "")),
+              },
+            ],
+            isError: false,
+          });
+        }
         if (toolName === "release-status") {
           return jsonRpcResult(message?.id ?? null, {
             content: [

Found while moving the conversation integration evals to the agent test fixture (#2001). The old eval injected a fake paused-turn checkpoint (active_turn_compaction), so it never ran this path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions