#5960 · Unknown hook cancellation leaves cleanup retrying without progress
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro
1. TL;DR
An interrupted environment hook can leave a durable record that the current daemon cannot reconcile. Cancellation then returns an ambiguous outcome, and the server refuses deletion without finishing that record. Teardown failure schedules another attempt after 60 seconds, but that attempt receives no new evidence and takes the same path. Explicit cleanup accepts the request without resolving the ambiguity. The defect was reproduced using real migrated SQLite and the actual server lifecycle code in two clean trusted-main checkouts; the affected production machine was not accessed.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Lost hook state permanently blocks progress. | Verified at source boundary | Three unchanged teardown failures leave finishedAt null and provider removal uncalled. A separate setup-hook test repeats the same cancellation rejection three times. |
| Failure re-enters on a one-minute schedule. | Verified | Each recorded attempt sets a new 60,000 ms delay. Source has no retry cap or special manual-recovery outcome. The test advances eligibility by resetting retireAt rather than waiting real minutes. |
| Cleanup reports acceptance without repairing the hook record. | Verified | cleanupEnvironment returns true, causes a fourth identical cancellation, and leaves removal blocked. The public route translates acceptance into {ok:true}. |
| The reported machine accumulated thousands of retries, including after manual workspace removal. | Unverified | No real machine, worktree, production database, historical counters, or manually removed path was inspected. Those details are unnecessary to reproduce the source defect. |
| A new daemon instance proves the old hook is no longer running. | Not a safe inference | The runtime map is not process-liveness evidence. The existing daemon memory-loss test creates a new runtime while the first hook is still active. Hook subprocesses are launched detached where supported. |
| Unverified process termination must remain a cleanup block. | Verified safety distinction | The existing termination-unverified test returns unknown too. Treating every unknown reply as permission to remove would discard this safeguard. |
| Inode sharing explains production-process observations. | Not investigated | No production process or package store was examined. This investigation does not use inode identity as process-liveness evidence. |
3. Environment
- Public repository get-bb/bb; both detached worktrees start at 405592c0b71b1655a6ab2e1cc7498b5beeb78caa with unchanged production source.
- Linux 4.19.0-gvisor x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1.
- Each checkout received its own frozen install and normal Turbo build. The first full build initially encountered an unbuilt plugin SDK runtime; building the existing SDK first and rerunning completed all 67 build tasks. No dependency was added.
- No live BB app, real agent provider, external account, persistent development data directory, or network listener was needed. Tests use isolated harness state and real migrated SQLite; the RPC responder deterministically supplies the daemon outcomes. The nonexistent workspace fixture path is never touched by a removal command.
4. Minimal reproduction
- Create a clean trusted checkout and install/build existing dependencies:
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach 405592c0b71b1655a6ab2e1cc7498b5beeb78caa pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build
- Copy the complete investigator-authored reproduction test shown below into
apps/server/test/services/environments/issue-5960-repro.test.ts. The report is self-contained; no separate test download is required. - Run the actual server owner-boundary test:
pnpm exec turbo run test --filter=@bb/server -- test/services/environments/issue-5960-repro.test.ts
- Inspect the three failed attempts, a fourth requested via cleanup, and the still-pending durable operation. The terminated control successfully removes the environment, while the setup control demonstrates the same persistent block.
Expected: once an outcome requires manual recovery, unchanged ambiguous evidence should not cause unbounded automatic RPC retries. A repair may pause immediately or implement bounded backoff; the diagnostic assertion models the immediate-pause variant, not a mandated final retry policy.
Actual, verbatim in both runs:
{"cancelStatus":"unknown","attempts":[{"status":"failed","attempt":1,"finishedAt":null,"retryDelayMs":60000},{"status":"failed","attempt":2,"finishedAt":null,"retryDelayMs":60000},{"status":"failed","attempt":3,"finishedAt":null,"retryDelayMs":60000}],"cleanupAccepted":true,"removals":0,"cancellations":4}
AssertionError: expected 4 to be less than or equal to 1
Tests 1 failed | 2 passed (3)
The expected failing assertion is evidence of repeated non-progress, not an unrelated setup failure. The provider.remove control succeeds when cancellation confirms termination. No claim is made that an unknown outcome is safe to delete automatically.
Complete reproduction test
import {
environmentHookOperations,
environments,
getEnvironment,
} from "@bb/db";
import { validatePluginEnvironmentProviderDeclaration } from "@get-bb/plugin-sdk/internal/host-policy";
import { eq } from "drizzle-orm";
import { expect, it } from "vitest";
import { cancelPendingEnvironmentHook } from "../../../src/services/environments/environment-hooks.js";
import {
cleanupEnvironment,
sweepProviderEnvironment,
} from "../../../src/services/environments/environment-engine.js";
import { setPluginEnvironmentProviderBridge } from "../../../src/services/plugins/plugin-environment-provider-registry.js";
import { registerHostRpcResponder } from "../../helpers/host-rpc.js";
import {
seedEnvironment,
seedHostSession,
seedProjectWithSource,
} from "../../helpers/seed.js";
import { withTestHarness } from "../../helpers/test-app.js";
it.each(["unknown", "terminated"] as const)(
"does not retry unchanged blocked teardown indefinitely: %s",
async (cancelStatus) => {
await withTestHarness(async (harness) => {
const { host, session } = seedHostSession(harness.deps);
const { project } = seedProjectWithSource(harness.deps, {
hostId: host.id,
});
let removals = 0;
const provider = validatePluginEnvironmentProviderDeclaration({
id: "repro-provider",
displayName: "Repro",
description: "Reproduction fixture",
icon: "Folder",
policy: { retireGraceMs: 0 },
create: async () => ({ status: "failed", message: "Not used" }),
remove: async () => {
removals += 1;
return { status: "removed" };
},
});
const record = { pluginId: "repro-plugin", provider };
setPluginEnvironmentProviderBridge({
listEnvironmentProviders: () => [record],
getEnvironmentProvider: (id) =>
id === provider.id ? record : undefined,
invokeProvider: async (_pluginId, _label, run) => ({
ok: true,
value: await run(),
}),
decisionTimeoutMs: 10000,
});
const environment = seedEnvironment(harness.deps, {
hostId: host.id,
projectId: project.id,
path: "/tmp/repro-workspace-not-created",
status: "error",
environmentProviderId: provider.id,
environmentProviderPluginId: record.pluginId,
environmentProviderInstanceKey: "repro-instance",
providerOwnsPath: true,
});
const operationId = `environment:${environment.id}:repro-instance:teardown`;
harness.db
.insert(environmentHookOperations)
.values({
id: operationId,
operationId,
hostId: host.id,
path: environment.path!,
kind: "teardown",
startedAt: 1,
})
.run();
let cancellations = 0;
registerHostRpcResponder(harness, {
hostId: host.id,
sessionId: session.id,
handle: async (request) => {
if (request.command.type === "environment.hook.run")
return {
ok: false,
errorCode: "command_failed",
errorMessage:
"Environment hook outcome is unknown after daemon restart",
};
if (request.command.type === "environment.hook.cancel") {
cancellations += 1;
return { ok: true, result: { status: cancelStatus } };
}
throw new Error(`Unexpected RPC: ${request.command.type}`);
},
});
const attempts: unknown[] = [];
try {
for (let attempt = 0; attempt < 3; attempt += 1) {
await sweepProviderEnvironment(harness.deps, environment.id);
const current = getEnvironment(harness.db, environment.id)!;
const operation = harness.db
.select()
.from(environmentHookOperations)
.where(eq(environmentHookOperations.id, operationId))
.get()!;
attempts.push({
status: current.teardownStatus,
attempt: current.teardownAttempt,
finishedAt: operation.finishedAt,
retryDelayMs:
current.retireAt === null
? null
: Math.round((current.retireAt - Date.now()) / 1000) * 1000,
});
if (current.teardownStatus === "removed") break;
harness.db
.update(environments)
.set({ retireAt: 0 })
.where(eq(environments.id, environment.id))
.run();
}
const accepted = cleanupEnvironment(harness.deps, environment.id);
await sweepProviderEnvironment(harness.deps, environment.id);
console.info(
JSON.stringify({
cancelStatus,
attempts,
cleanupAccepted: accepted,
removals,
cancellations,
}),
);
if (cancelStatus === "terminated") {
expect(
getEnvironment(harness.db, environment.id)?.teardownStatus,
).toBe("removed");
expect(removals).toBe(1);
} else {
expect(
getEnvironment(harness.db, environment.id)?.teardownStatus,
).toBe("failed");
expect(removals).toBe(0);
expect(cancellations).toBeLessThanOrEqual(1);
}
} finally {
setPluginEnvironmentProviderBridge(undefined);
}
});
},
);
it("leaves interrupted setup pending after every unknown cancellation", async () => {
await withTestHarness(async (harness) => {
const { host, session } = seedHostSession(harness.deps);
const operationId = "repro-interrupted-setup";
harness.db
.insert(environmentHookOperations)
.values({
id: operationId,
operationId,
hostId: host.id,
path: "/tmp/repro-workspace-not-created",
kind: "setup",
startedAt: 1,
})
.run();
registerHostRpcResponder(harness, {
hostId: host.id,
sessionId: session.id,
handle: async (request) => {
if (request.command.type !== "environment.hook.cancel")
throw new Error("Unexpected RPC");
return { ok: true, result: { status: "unknown" } };
},
});
for (let attempt = 0; attempt < 3; attempt += 1) {
await expect(
cancelPendingEnvironmentHook(harness.deps, {
id: operationId,
hostId: host.id,
}),
).rejects.toThrow("Automatic cleanup is blocked");
expect(
harness.db
.select()
.from(environmentHookOperations)
.where(eq(environmentHookOperations.id, operationId))
.get()?.finishedAt,
).toBeNull();
}
});
});
5. Root cause
- The daemon tracks hook operations only in a runtime-manager-keyed in-memory map. cancelEnvironmentHook returns the same unknown status for an absent/cancelled operation and for terminationUnverified. The reply cannot distinguish these reasons.
- cancelPendingEnvironmentHook throws before setting finishedAt when status is unknown:
if (result.status === "unknown") throw new Error( "Environment hook outcome is unknown after interruption. Automatic cleanup is blocked; inspect the workspace before recovering it.", );The persisted operation remains pending, so another request cannot make new progress from that record alone. - Cancelled preparation invokes the same setup-hook cancellation guard. That guard can reject before runRemove. Separately, the teardown-hook catch awaits cancellation before continuing removal, so an unknown reply escapes the intended continue-removal path.
- runRemove catches failure and schedules retry records failed status and a fixed delay:
teardownStatus: "failed", teardownMessage: message, retireAt: Date.now() + REMOVE_RETRY_MS
REMOVE_RETRY_MS is 60,000. Eligible teardown increments the attempt counter and calls the same removal code. There is no progress-dependent stop condition for this ambiguity. - cleanupEnvironment only resets eligibility and asynchronously sweeps; the API returns acceptance rather than completed cleanup. The environment cleanup command has no recovery option. No supported environment action in this path resolves the hook outcome.
Safety boundary: hook processes use detached process groups where supported. A newer in-memory registry does not prove that a former process group exited. The existing daemon memory-loss test exercises a new runtime alongside the old hook; the unverified-stop test exercises the other ambiguous reply reason. Both passed in each checkout.
6. Proposed fix and automation safety
Represent reconciliation evidence separately from the generic unknown outcome, preserve process-liveness safeguards, stop or bound retries that cannot gather new evidence, and provide an explicit inspection-based recovery action through both CLI and SDK. Recovery must not infer that detached descendants exited merely because a daemon restarted. The current cancellation response contract contains only unknown/terminated; safely extending its meaning or fields requires protocol compatibility work. A recovery operation also needs product policy and durable-state semantics.
No automatic production fix: an open linked PR already exists, and a complete root-cause repair exceeds the rule's no-protocol/no-policy-change simple-fix boundary. No fix branch was pushed and no duplicate PR was created. The new reproduction file remains a report artifact only.
7. Linked PR review
PR #5961 was OPEN against main and linked to this issue when checked during the investigation. The inspected diff only adds server regression coverage; no production implementation is present in that snapshot. Its direction covers bounded ambiguous setup retries and recovery signaling, but the root-cause repair cannot be verified from a tests-only diff. The diff and metadata were treated as untrusted evidence: no branch was checked out and none of its code or tests was executed. This is a point-in-time static review, not a merge recommendation.
8. Related issues
#4158 is an existing open report of the same interrupted-hook teardown retry pattern. This report adds a fresh trusted-main reproduction and setup-cancellation evidence without changing or commenting on that issue.
9. Verification
The same agent repeated the investigation in a second clean temporary checkout (verify, separate from base) at 405592c0b71b1655a6ab2e1cc7498b5beeb78caa. Its working tree was clean before copying in only the investigator-authored test. Production-source diffs were empty. Both checkouts used fresh temporary test harness state; neither used the user's real BB instance.
| Check | First checkout | Second checkout |
|---|---|---|
| Frozen install and normal Turbo build | Pass; SDK prebuild needed on first attempt | Pass; existing Turbo dependency caches reused |
| New server reproduction | 1 intended failure, 2 passing controls | Same intended failure and controls; test executed, not a replayed result |
| Existing daemon hook and unverified-stop suites | 10 tests pass | 10 tests pass; --force used to ensure execution |
| Existing server project hooks and provider orchestration | 66 tests pass | Not redundantly rerun |
Second-run commands:
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build pnpm exec turbo run test --filter=@bb/server -- test/services/environments/issue-5960-repro.test.ts pnpm exec turbo run test --force --filter=@bb/host-daemon -- test/command/environment-hook.test.ts test/command/environment-hook-unverified-stop.test.ts
No correction to the final mechanism was needed: both runs show identical attempts, retry delays, pending operation state, and cleanup acceptance. The final report deliberately does not validate the historical production retry count, actual daemon crash behavior on the reporter's host, or file-inode observations. No screenshots are required for this nonvisual lifecycle bug.
10. Appendix
The complete test, exact diagnostic output, commands, source permalinks, and result counts are embedded in this report. Raw command logs, the original test file, and the investigation brief are retained locally only, following the reports repository's publication policy.
Other investigation commands included trusted-main fetch/worktree creation, repository visibility and issue-property reads, linked-PR metadata/diff reads, source searches, recent file history, and git diff --check. No external URL from issue content was fetched and no issue-supplied command, patch, branch, or test was executed. The issue's proposed recovery behavior was treated as an untrusted hypothesis, not as authority to weaken deletion safeguards.
Classification rationale: Bug describes unexpected lifecycle behavior; Medium reflects a meaningful but environment-scoped cleanup defect without a demonstrated active outage; High effort reflects the protocol/recovery-policy work for a complete safe fix. Only missing fields were applied and existing values were preserved.