Reports

#6379 · Provider maintenance bypasses compaction admission

BugHighEffort: Mediumproviders · threads · provider-pi

GitHub issue · October 27, 2026 · Base b6743a36bd9eae1408c35cfc2c7ab1d2419dc79d

Verdict: REPRODUCED at the server dispatch boundary. Root-cause confidence: high.

1. TL;DR

A message arriving during a provider-owned maintenance turn is dispatched immediately rather than retained until compaction finishes. The server recognizes manual compaction from a bb command request, not from the provider's own maintenance events. Pi emits a separate turn and a context-compaction item for manual compaction even when bb did not request it. A focused public send-route test fails on untouched main in two clean checkouts: expected queued, received sent. This reproduces the admission defect; an authenticated live Pi extension run and its full error/message-loss chain were not executed.

2. Claims vs findings

ClaimFindingEvidence
Provider-started manual compaction opens a turn.Verified in trusted source.Pi translator emits turn.open and item.open for manual compaction; existing translator test covers the resulting turn/started and item/started events.
The send is steered rather than queued.Reproduced.Public API regression sends mode steer during an active maintenance turn and receives delivery sent instead of queued.
bb-requested compaction queues messages.Verified.All 12 pre-existing public compaction tests pass, including compaction queue/drain behavior.
Pi rejects prompts while manual compaction runs.Verified in installed dependency source, not a live session.AgentSession.prompt checks its manual-compaction controller before input handling and throws.
The full thread fails and the message is never delivered.Not reproduced end to end.The harness acknowledges host RPCs. It proves the wrong admission decision, not a real Pi failure or the eventual UI state.

3. Environment

4. Minimal reproduction

  1. Clone the trusted repository and select the recorded commit:
    git clone https://github.com/get-bb/bb.git bb-repro
    cd bb-repro
    git checkout --detach b6743a36bd9eae1408c35cfc2c7ab1d2419dc79d
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build
    The first broad build in the investigation failed because SDK runtime entries had not been built. After the normal SDK build, the broad build passed: 72 tasks successful.
  2. Save the exact patch below as /tmp/6379-regression.patch and apply it. This adds a test only; production remains unchanged.
    git apply /tmp/6379-regression.patch
    pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-compaction.test.ts
  3. The test seeds the provider's persisted turn-start and context-compaction item shape, with no bb compaction request. It calls the real public send route and checks persistent queue retention, no premature host submission, and eventual delivery after completion.

Exact reproduction test patch (all helper implementations already exist on the recorded base):

diff --git a/apps/server/test/public/public-thread-compaction.test.ts b/apps/server/test/public/public-thread-compaction.test.ts
index ddff11d36..c038fba85 100644
--- a/apps/server/test/public/public-thread-compaction.test.ts
+++ b/apps/server/test/public/public-thread-compaction.test.ts
@@ -32,7 +32,11 @@ import { withTestHarness, type TestAppHarness } from "../helpers/test-app.js";
 
 function seedCompactableThread(
   harness: TestAppHarness,
-  args: { providerId: string; providerThreadId: string },
+  args: {
+    providerId: string;
+    providerThreadId: string;
+    status?: "idle" | "active";
+  },
 ) {
   const { host, session } = seedHostSession(harness.deps);
   const { project } = seedProjectWithSource(harness.deps, {
@@ -46,7 +50,7 @@ function seedCompactableThread(
     environmentId: environment.id,
     projectId: project.id,
     providerId: args.providerId,
-    status: "idle",
+    status: args.status ?? "idle",
   });
   seedThreadRuntimeState(harness.deps, {
     environmentId: environment.id,
@@ -106,6 +110,215 @@ function seedAcceptedProviderTurn(
 }
 
 describe("public thread compaction", () => {
+  it("retains sends during provider-started compaction and delivers them afterward", async () => {
+    await withTestHarness(async (harness) => {
+      const { host, session, thread } = seedCompactableThread(harness, {
+        providerId: "pi",
+        providerThreadId: "provider-maintenance",
+        status: "active",
+      });
+      const responder = registerSuccessfulTurnResponder(harness, {
+        hostId: host.id,
+        sessionId: session.id,
+      });
+      const turnId = "provider-maintenance-turn";
+      seedTurnStarted(harness.deps, {
+        threadId: thread.id,
+        environmentId: thread.environmentId,
+        providerThreadId: "provider-maintenance",
+        turnId,
+      });
+      seedEvent(harness.deps, {
+        threadId: thread.id,
+        environmentId: thread.environmentId,
+        providerThreadId: "provider-maintenance",
+        sequence:
+          getLatestThreadSequence(harness.db, { threadId: thread.id }) + 1,
+        type: "item/started",
+        scope: turnScope(turnId),
+        data: { item: { type: "contextCompaction", id: "maintenance-item" } },
+      });
+
+      const response = await harness.app.request(
+        `/api/v1/threads/${thread.id}/send`,
+        {
+          method: "POST",
+          headers: { "content-type": "application/json" },
+          body: JSON.stringify({
+            mode: "steer",
+            input: [{ type: "text", text: "Continue after maintenance" }],
+          }),
+        },
+      );
+      expect(response.status).toBe(200);
+      await expect(readJson(response)).resolves.toMatchObject({
+        delivery: "queued",
+        queuedMessage: { waitingOn: { kind: "thread-busy" } },
+      });
+      expect(listQueuedThreadMessages(harness.db, thread.id)).toHaveLength(1);
+      expect(
+        responder.requests.filter(
+          ({ command }) => command.type === "turn.submit",
+        ),
+      ).toHaveLength(0);
+      expect(
+        await sendNextQueuedMessageIfPresent(harness.deps, {
+          threadId: thread.id,
+        }),
+      ).toBe(false);
+
+      seedEvent(harness.deps, {
+        threadId: thread.id,
+        environmentId: thread.environmentId,
+        providerThreadId: "provider-maintenance",
+        sequence:
+          getLatestThreadSequence(harness.db, { threadId: thread.id }) + 1,
+        type: "turn/completed",
+        scope: turnScope(turnId),
+        data: { providerThreadId: "provider-maintenance", status: "completed" },
+      });
+      applyTurnCompletedEvent(harness.deps, {
+        threadId: thread.id,
+        providerThreadId: "provider-maintenance",
+        type: "turn/completed",
+        scope: turnScope(turnId),
+        status: "completed",
+      });
+      expect(
+        await sendNextQueuedMessageIfPresent(harness.deps, {
+          threadId: thread.id,
+        }),
+      ).toBe(true);
+      expect(listQueuedThreadMessages(harness.db, thread.id)).toHaveLength(0);
+      await expect
+        .poll(() =>
+          responder.requests.filter(
+            ({ command }) => command.type === "turn.submit",
+          ),
+        )
+        .toMatchObject([
+          {
+            command: {
+              input: [{ type: "text", text: "Continue after maintenance" }],
+            },
+          },
+        ]);
+    });
+  });
+
+  it.each(["requested-turn", "completed-item", "previous-turn", "nested-item"])(
+    "does not block steering for compaction in %s",
+    async (scenario) => {
+      await withTestHarness(async (harness) => {
+        const { host, session, thread } = seedCompactableThread(harness, {
+          providerId: "pi",
+          providerThreadId: "provider-compaction-control",
+          status: scenario === "requested-turn" ? "idle" : "active",
+        });
+        const responder = registerSuccessfulTurnResponder(harness, {
+          hostId: host.id,
+          sessionId: session.id,
+        });
+        if (!thread.environmentId) {
+          throw new Error("Expected compactable thread environment");
+        }
+        const turnId = "control-turn";
+        if (scenario === "requested-turn") {
+          const response = await harness.app.request(
+            `/api/v1/threads/${thread.id}/send`,
+            {
+              method: "POST",
+              headers: { "content-type": "application/json" },
+              body: JSON.stringify({
+                mode: "start",
+                input: [{ type: "text", text: "Start ordinary work" }],
+              }),
+            },
+          );
+          expect(response.status).toBe(200);
+          const request = responder.requests.find(
+            ({ command }) => command.type === "turn.submit",
+          );
+          if (!request || request.command.type !== "turn.submit") {
+            throw new Error("Expected ordinary turn request");
+          }
+          seedAcceptedProviderTurn(harness, {
+            clientRequestId: request.command.requestId,
+            environmentId: thread.environmentId,
+            providerThreadId: "provider-compaction-control",
+            threadId: thread.id,
+            turnId,
+          });
+        } else {
+          seedTurnStarted(harness.deps, {
+            threadId: thread.id,
+            environmentId: thread.environmentId,
+            providerThreadId: "provider-compaction-control",
+            turnId,
+          });
+        }
+        const itemEvent = {
+          threadId: thread.id,
+          environmentId: thread.environmentId,
+          providerThreadId: "provider-compaction-control",
+          scope: turnScope(
+            scenario === "previous-turn" ? "older-turn" : turnId,
+          ),
+          data: {
+            item: {
+              type: "contextCompaction" as const,
+              id: "control-compaction",
+              ...(scenario === "nested-item"
+                ? { parentToolCallId: "child-work" }
+                : {}),
+            },
+          },
+        };
+        seedEvent(harness.deps, {
+          ...itemEvent,
+          sequence:
+            getLatestThreadSequence(harness.db, { threadId: thread.id }) + 1,
+          type: "item/started",
+        });
+        if (scenario === "completed-item") {
+          seedEvent(harness.deps, {
+            ...itemEvent,
+            sequence:
+              getLatestThreadSequence(harness.db, { threadId: thread.id }) + 1,
+            type: "item/completed",
+          });
+        }
+        const submissionsBefore = responder.requests.filter(
+          ({ command }) => command.type === "turn.submit",
+        ).length;
+        const response = await harness.app.request(
+          `/api/v1/threads/${thread.id}/send`,
+          {
+            method: "POST",
+            headers: { "content-type": "application/json" },
+            body: JSON.stringify({
+              mode: "steer",
+              input: [{ type: "text", text: "Keep working" }],
+            }),
+          },
+        );
+        expect(response.status).toBe(200);
+        await expect(readJson(response)).resolves.toMatchObject({
+          delivery: "sent",
+        });
+        expect(listQueuedThreadMessages(harness.db, thread.id)).toHaveLength(0);
+        await expect
+          .poll(
+            () =>
+              responder.requests.filter(
+                ({ command }) => command.type === "turn.submit",
+              ).length,
+          )
+          .toBe(submissionsBefore + 1);
+      });
+    },
+  );
+
   it("dispatches the same structured /compact turn as the composer", async () => {
     await withTestHarness(async (harness) => {
       const { host, session, thread } = seedCompactableThread(harness, {

Expected: delivery: queued with waitingOn.kind: thread-busy, no host submission during compaction, then one delivery after completion.

Actual on both clean checkouts, excerpted verbatim from the assertion diff:

-   "delivery": "queued",
-   "queuedMessage": {
-     "waitingOn": {
-       "kind": "thread-busy",
-     },
-   },
+   "delivery": "sent",

Test Files  1 failed (1)
Tests  1 failed | 16 passed (17)

5. Root cause

plugins/provider-pi/src/delta-translation.ts:727-L743 translates manual compaction into its own turn and compaction item. packages/provider-bridge-protocol/src/assembler/delta-assembler.ts:775-L783 turns that delta into a contextCompaction item.

apps/server/src/services/threads/thread-events.ts:865-L889 only recognizes an active manual compaction when its associated request, or the last thread request, is a standalone built-in compact command. A provider-owned maintenance turn has no matching client request. Therefore a valid compaction item does not satisfy this predicate.

apps/server/src/services/threads/dispatch-attempt.ts:490-L500 uses that predicate as the compaction wait gate. When it returns false, the active-turn send proceeds toward steering. The dependency's AgentSession.prompt rejects prompts whenever its manual compaction controller exists. That explains the reported rejection, but the complete live rejection/error cascade remains a source-supported inference, not a reproduced transcript.

6. Proposed fix

Preserve the existing command-request guard. For an active provider-owned turn without an accepted bb request, inspect that turn's root contextCompaction lifecycle and wait while its item is open. Use a targeted thread/turn query, not a whole-thread event scan. Preserve steering during ordinary requested turns, including provider automatic compaction that does not own a separate maintenance turn. No provider protocol, persisted schema, or product-policy change is required. The added route-level regression must fail before the fix and pass afterward, including queue drain.

7. Linked pull request metadata

GitHub cross-reference metadata identifies PR #6380 as closed and unmerged. No linked branch was checked out or executed, and no patch from it was used. No open linked PR was found at investigation time. This is metadata-only, not a code-review verdict.

8. Related issues

No other issue was investigated. This report distinguishes provider-owned maintenance admission from the existing bb-requested compaction cases by running the existing public suite as a control.

9. Verification

The same agent repeated the test in a second clean worktree created directly at b6743a36bd9eae1408c35cfc2c7ab1d2419dc79d. Only the authored regression patch was applied; production stayed byte-identical to main. The frozen install and SDK prerequisite build were repeated, and Turbo ran the identical focused command above. Both runs exited 1 at the same delivery assertion: queued was expected and sent was returned. Neither failure was a timeout or setup failure. All 16 control tests passed in each run.

Correction: the initially published draft used an invalid fixture state update, leaving the thread idle. The fixture now creates an active thread directly, and both clean reproductions were repeated with unchanged production code. The earlier draft runs are not counted as evidence. The patch embedded here is the corrected test and includes the steering controls.

10. Appendix and limits

The trusted-base control command pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-compaction.test.ts passed all 12 existing tests before the regression was added. The reproduction patch is embedded here rather than publishing raw logs, paths, or test artifacts. Local evidence is retained in isolated investigation storage.

Issue content, comments, and linked material were treated as untrusted claims. No issue-provided scripts, patches, branches, commands, or external links were executed or fetched. This is a deterministic server-boundary reproduction, not an independent-agent verification, a desktop/macOS reproduction, or a live extension test.