Reports · Issue #7708

Recurring automation retry consent has a pre-association race

Bug · Priority: Medium · Effort: Medium · plugins, automations, provider-retry
November 17, 2026 · trusted main: 1320c88e8abdd3f145bc9a5c305eace269fb2f28

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: medium for the reported incident; high for the demonstrated race.

1. TL;DR

A scheduled automation normally declines provider retries, but it cannot recognize its new thread until the thread-spawn SDK call returns. When a failure and retry-consent request arrive before that response, the real automations plugin answers allow, and the real provider-retry plugin submits a retry. The same request is declined immediately after the spawn response. The early failure notification also misses the automation run; restarting its sweep service with the failed thread state reconciles the run and submits a fresh automation spawn. This controlled interleaving reproduces competing retry submissions, not the reporter's full macOS wake sequence or three completed prompts.

2. Claims vs findings

ClaimFindingEvidence
A recurring scheduled turn can receive consent for a provider retry.Verified under a forced startup interleaving.Consent is allow before the spawn response; one actual call from provider-retry to the SDK retry boundary.
The automation can also resubmit its work.Verified with an explicit sweep-service restart after the early failure.Startup reconciliation plus a 30-second virtual-time advance produces a second SDK spawn submission.
The ordinary recurring-turn consent guard is ineffective.Not generally true.The same request is declined after thread association; all 200 existing tests pass.
macOS wake and Claude Code HTTP 503 produce three threads running the full prompt.Unverified.No macOS, live Claude process, wake transition, real queue dispatch, or full prompt execution was used.

3. Environment

4. Minimal reproduction

In a fresh checkout of the recorded commit, save the complete patch below as repro.patch outside the repository, install and build, then apply it. The patch changes only the existing automations test owner and imports the existing provider-retry entry point. Production source is unchanged.

git clone https://github.com/get-bb/bb.git bb-repro
cd bb-repro
git checkout --detach 1320c88e8abdd3f145bc9a5c305eace269fb2f28
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types build --filter=@get-bb/plugin-sdk
pnpm exec turbo run build
git apply ../repro.patch
pnpm exec turbo run test --filter=bb-plugin-automations -- src/server-harness.test.ts -t 'spawn response is pending'

Expected: a recurring schedule-owned first turn answers {kind: "decline"} even if failure notification arrives before its spawn response. Actual: the assertion fails because consent is {kind: "allow"}. The test deliberately retains this failing assertion as the regression contract.

bb-plugin-automations:test: {"beforeSpawn":{"kind":"allow"},"afterSpawn":{"kind":"decline","reason":"automation \"Startup race\" runs again on its schedule"},"runStatus":"running","providerRetries":1,"spawned":2}
bb-plugin-automations:test:  FAIL  src/server-harness.test.ts > automations server plugin harness > declines a recurring first-turn retry while the spawn response is pending
bb-plugin-automations:test: AssertionError: expected { kind: 'allow' } to match object { kind: 'decline' }
bb-plugin-automations:test:  Test Files  1 failed (1)
bb-plugin-automations:test:       Tests  1 failed | 39 skipped (40)
 Tasks:    6 successful, 7 total
Cached:    5 cached, 7 total

providerRetries: 1 counts actual SDK retry submissions by the real provider-retry plugin. spawned: 2 counts initial plus recovery SDK spawn submissions, not live provider processes. runStatus: "running" is read after the first failure and before recovery, demonstrating the missed settlement.

Complete reproduction patch, including the new regression test
diff --git a/plugins/automations/src/server-harness.test.ts b/plugins/automations/src/server-harness.test.ts
index ad57a57581..e6df26454e 100644
--- a/plugins/automations/src/server-harness.test.ts
+++ b/plugins/automations/src/server-harness.test.ts
@@ -4,11 +4,13 @@ import { afterEach, describe, expect, it, vi } from "vitest";
 import {
   createFakePluginHost,
   makeThreadResponse,
+  makeTurnFailedEvent,
   PluginContextStaleError,
   type FakePluginHost,
 } from "@get-bb/plugin-sdk/testing";
 import { createScriptRunScope } from "./script-runner.js";
 import plugin from "./server.js";
+import providerRetryPlugin from "../../provider-retry/server.js";
 import { createAutomationService } from "./service.js";
 import {
   automationListResponseSchema,
@@ -1973,6 +1975,134 @@ describe("automations server plugin harness", () => {
     await harness.dispose();
   });
 
+  it("declines a recurring first-turn retry while the spawn response is pending", async () => {
+    vi.useFakeTimers();
+    vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
+    const host = await bootAutomationsPlugin();
+    const { harness } = host;
+    const answers: unknown[] = [];
+    let spawned = 0;
+    const retryHost = createFakePluginHost({
+      pluginId: "provider-retry",
+      sdk: {
+        plugins: {
+          experimental_discoverRpc: async () => [
+            {
+              pluginId: "automations",
+              displayName: "Automations",
+              method: "provider-retry.v1.consent",
+            },
+          ],
+          callRpc: async ({ input }) => {
+            const answer = await harness.callRpc(
+              "provider-retry.v1.consent",
+              input,
+            );
+            answers.push(answer);
+            return answer;
+          },
+        },
+        threads: {
+          retry: async ({ turnRequestId, sendAt }) => ({
+            ok: true,
+            delivery: "queued",
+            turnRequestId,
+            attempt: 2,
+            queuedMessageId: "queued_race",
+            waitingOn: { kind: "time" },
+            sendAt,
+          }),
+        },
+      },
+    });
+    await providerRetryPlugin(retryHost.bb);
+    harness.sdk.stub("threads.events.list", async () => [
+      {
+        type: "client/turn/requested",
+        data: {
+          requestId: FAILED_REQUEST_ID,
+          target: { kind: "thread-start" },
+        },
+      },
+    ]);
+    harness.sdk.stub("threads.spawn", async () => {
+      spawned += 1;
+      const thread = makeThreadResponse({
+        id: `thr_spawned_${spawned}`,
+        projectId: PROJECT_ID,
+      });
+      if (spawned > 1) return thread;
+      await harness.emitThreadEvent("thread.failed", {
+        thread: { ...thread, status: "error" },
+        error: "Provider unavailable",
+      });
+      const result = await retryHost.harness.emitThreadEvent(
+        "turn.failed",
+        makeTurnFailedEvent({
+          threadId: thread.id,
+          requestId: FAILED_REQUEST_ID,
+          originPluginId: "automations",
+          errorInfo: {
+            category: "internal",
+            httpStatusCode: 503,
+            providerCode: null,
+          },
+        }),
+      );
+      expect(result.errors).toEqual([]);
+      return thread;
+    });
+    const automation = await createAgentAutomation(harness, {
+      name: "Startup race",
+      trigger: { triggerType: "schedule", cron: "* * * * *", timezone: "UTC" },
+    });
+    vi.setSystemTime(new Date("2026-01-01T00:01:05.000Z"));
+    const service = harness.runService("automation-sweep");
+    await vi.waitFor(() => expect(answers).toHaveLength(1));
+    service.controller.abort();
+    await service.done;
+    const afterSpawn = await harness.callRpc("provider-retry.v1.consent", {
+      threadId: "thr_spawned_1",
+      requestId: FAILED_REQUEST_ID,
+      reason: "Provider unavailable",
+      sendAt: Date.now() + 60_000,
+    });
+    const { runs } = automationRunListResponseSchema.parse(
+      await harness.callRpc("automations_runs", {
+        projectId: PROJECT_ID,
+        automationId: automation.id,
+      }),
+    );
+    const providerRetries =
+      retryHost.harness.sdk.callsTo("threads.retry").length;
+    harness.sdk.stub(
+      "threads.get",
+      async ({ threadId }: { threadId: string }) => ({
+        ...makeThreadResponse({ id: threadId, projectId: PROJECT_ID }),
+        status: "error",
+      }),
+    );
+    const restarted = harness.runService("automation-sweep");
+    await vi.advanceTimersByTimeAsync(30_000);
+    await vi.waitFor(() => expect(spawned).toBe(2));
+    restarted.controller.abort();
+    await restarted.done;
+    console.log(
+      JSON.stringify({
+        beforeSpawn: answers[0],
+        afterSpawn,
+        runStatus: runs[0]?.status,
+        providerRetries,
+        spawned,
+      }),
+    );
+    await retryHost.harness.dispose();
+    await harness.dispose();
+    expect(providerRetries).toBe(1);
+    expect(afterSpawn).toMatchObject({ kind: "decline" });
+    expect(answers[0]).toMatchObject({ kind: "decline" });
+  });
+
   it("disables automations targeting a deleted thread", async () => {
     const { harness } = await bootAutomationsPlugin();
     const automation = await createAgentAutomation(harness, {

The whole runnable patch is embedded here so this report is self-contained. Raw logs and the patch are retained locally, not committed as separate files, following the reports repository's publication policy.

5. Root cause

  1. executeAgentRun awaits spawn before persisting the thread ID. Thus the run exists but cannot yet be queried by that thread.
  2. answerRetryConsent looks up the run by thread ID and allows a missing run. The fixture uses a matching request ID and thread-start target, so the missing association, not a parse error, causes consent.
  3. askSender calls the sender's consent RPC and the handler only suppresses retry on an explicit decline. A valid allow answer falls through to the existing SDK retry submission path.
  4. failure settlement also depends on the thread/run association. The first failure event finds no run, leaving it running after spawn eventually returns.
  5. startup reconciliation settles running rows using the thread's failed state. recurring failures schedule bounded quick retries, allowing a fresh spawn even though provider-retry has already submitted its retry.

Core schedules thread provisioning before returning the admitted thread; provisioning advances asynchronously. This supports the plausibility of an earlier lifecycle notification, but the reproduction intentionally forces that ordering at the SDK boundary. It does not prove that the real HTTP transport and lifecycle event dispatcher produce it during a macOS wake.

6. Proposed fix and safety decision

Associate automation ownership with the first request before provider execution can emit lifecycle events, and ensure a settlement cannot be lost during thread creation. Keep the request-ID and schedule/manual distinctions; blanket refusal of all automation retries could break one-shot and manual turns.

No fix PR: only a controlled boundary interleaving is confirmed, not the full reported transport sequence. A safe repair needs verified early run/thread ownership across spawn and lifecycle delivery; no under-500-line, single-subsystem repair with a passing regression has been established. The next experiment is a core integration test delaying the real spawn HTTP response while provisioning emits a structured 503, with durable queue state inspected before and after plugin restart.

7. Verification

The same agent repeated the reproduction in a second clean temporary checkout at the exact recorded commit, with a separate frozen dependency installation and freshly created plugin databases. Both checkouts built all 74 build tasks successfully after explicitly building the SDK runtime/types. Neither checkout modifies production code; the second receives only the saved test patch. Turbo test execution was forced in the second checkout to prevent a cached failure from masquerading as a rerun.

pnpm exec turbo run test --force --filter=bb-plugin-automations -- src/server-harness.test.ts -t 'spawn response is pending'
bb-plugin-automations:test: {"beforeSpawn":{"kind":"allow"},"afterSpawn":{"kind":"decline","reason":"automation \"Startup race\" runs again on its schedule"},"runStatus":"running","providerRetries":1,"spawned":2}
bb-plugin-automations:test:  FAIL  src/server-harness.test.ts > automations server plugin harness > declines a recurring first-turn retry while the spawn response is pending
bb-plugin-automations:test: AssertionError: expected { kind: 'allow' } to match object { kind: 'decline' }
bb-plugin-automations:test:  Test Files  1 failed (1)
bb-plugin-automations:test:       Tests  1 failed | 39 skipped (40)
 Tasks:    6 successful, 7 total
Cached:    0 cached, 7 total

Second-run result: the same allow-before/decline-after observation, one provider retry submission, two spawn submissions after service recovery, and the same intended assertion failure. No report correction was required. This is a repeated check by the same agent, not independent verification.

8. Existing coverage and related work

Unmodified main's automations suite passes 167 tests in 12 files; provider-retry passes 33 tests in one file. Those suites cover decline after a run is attached and provider-retry honoring a sender's decline. The new case isolates their missing cross-plugin startup ordering. The test patch also passes the automations package typecheck and git diff --check.

No open pull request linked to #7708 was present in the issue timeline or the issue-number PR search at investigation time. Trusted history shows the current recurring retry policy and consent guard were changed by the existing consent implementation; no linked PR branch was checked out or run.

9. Appendix and limitations

Commands used in addition to the reproduction: baseline pnpm exec turbo run test --filter=bb-plugin-automations --filter=bb-plugin-provider-retry; typecheck pnpm exec turbo run typecheck --filter=bb-plugin-automations; git diff --check; recorded-commit source inspection and GitHub issue/PR metadata reads. The initial broad build failed because SDK runtime output was absent; explicitly building the SDK and rerunning the same broad build resolved this setup failure. The second checkout built the SDK first and completed the broad build successfully.

The controlled spawn response has already allocated its thread fixture before emitting failure. Recovery is an explicit restart of the registered automation-sweep service, not a real machine wake or process restart. SDK retry delivery returns a queued receipt fixture; the durable queue and provider continuation are not exercised. These limits are why the verdict is partial and root-cause confidence for the reported incident is medium.

Trust boundary: issue text was treated only as untrusted claims. No issue-supplied scripts, commands, branches, or external URLs were executed or fetched. All executable repository code came from trusted main plus the evidence-derived test patch.