#7344 · Cancellation cleanup lacks adoption provenance
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A thread can take over a workspace record that already exists and is still provisioning. Cancelling that thread invokes the provider's removal callback for the old workspace and records the workspace as destroyed, even with automatic retirement disabled. The equivalent ready-workspace control is preserved. The server loses the distinction between adoption and fresh allocation when it persists ownership. This is a deterministic service-level reproduction, not evidence of production frequency or actual filesystem data loss: the removal callback is a test double and deletes nothing.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| An unowned provisioning workspace at the returned path can be adopted. | Verified | The real provider preparation path changes the existing row's owner to the new thread and preserves its ID and provisioning status. |
| Cancellation can remove the pre-existing workspace. | Verified | Both runs call remove once with the old path and instance key, then persist status=destroyed and teardownStatus=removed. |
| The cancellation release guard treats ready and provisioning differently. | Verified | The ready control passes; the provisioning case fails two preservation assertions. |
| This initial state occurs frequently in production. | Unverified | The initial database state is seeded. No production runtime data was accessed; frequency and the origin of orphan provisioning records were not established. |
| A particular proposed patch safely fixes every lifecycle path. | Unverified | No issue-supplied patch was executed. No production fix was made. |
3. Environment
- Public repository get-bb/bb, trusted origin/main commit
7c1353d80729983b86ea1555d18b42407f320406. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; workspace Vitest 4.1.12.
- Two separate temporary clones at the same recorded commit, each with its own frozen install and generated modules.
- The existing server test harness uses
createMigratedConnection(), real migrated SQLite, fresh temporary data directories, and cleanup. No listening server or ports, real account, real provider process, or user's runtime data is required. - Provider create/remove are in-process test callbacks registered through the existing provider bridge. The database, adoption transaction, cancellation, lifecycle sweep, and removal dispatch are production implementations.
4. Minimal reproduction
- Clone the public trusted repository and check out the recorded base. Use a fresh checkout, not an issue or pull-request branch.
- Install and build. Building SDK runtime first avoids a clean-build ordering race observed on the first checkout.
git clone https://github.com/get-bb/bb.git bb-7344 cd bb-7344 git checkout --detach 7c1353d80729983b86ea1555d18b42407f320406 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build
Insert this complete test case inside the existing describe("existing-path provider selection", ...) block in apps/server/test/services/environments/provider-orchestration.test.ts. It reuses that trusted file's setup, imports, and real database harness; it needs no new production export or dependency.
it.each(["ready", "provisioning"] as const)(
"preserves a pre-existing %s workspace after adoption is cancelled",
async (status) =>
withTestHarness(async (harness) => {
const remove = vi.fn<PluginEnvironmentProviderDeclaration["remove"]>(
async () => ({ status: "removed" }),
);
const fixture = setup(harness, {
create: async () => ({
status: "created",
path: "/tmp/slopcop-7344-workspace",
ownsPath: true,
}),
remove,
policy: { retireGraceMs: null },
});
const existing = seedEnvironment(harness.deps, {
projectId: fixture.context.project.id,
hostId: fixture.host.id,
path: "/tmp/slopcop-7344-workspace",
status,
providerOwnsPath: true,
environmentProviderId: fixture.record.provider.id,
environmentProviderPluginId: "test",
environmentProviderInstanceKey: "pre-existing-workspace",
});
expect(existing.ownerThreadId).toBeNull();
fixture.ask();
await fixture.settled();
expect(fixture.row()).toMatchObject({
id: existing.id,
status,
ownerThreadId: fixture.thread.id,
});
await cancelProviderEnvironmentCreation(harness.deps, fixture.thread.id);
await sweepProviderEnvironment(harness.deps, existing.id);
expect.soft(remove).not.toHaveBeenCalled();
expect.soft(getEnvironment(harness.db, existing.id)).toMatchObject({
status,
ownerThreadId: null,
claimPath: null,
teardownStatus: null,
retireAt: null,
});
}),
);
Run from the repository root:
pnpm exec turbo run test --filter=@bb/server -- test/services/environments/provider-orchestration.test.ts -t 'preserves a pre-existing'
Expected: both cases pass; no removal callback, original status preserved, owner and cancellation metadata released. Actual, both clean runs: ready passes; provisioning invokes removal once and becomes destroyed/removed. Exit code 1 is the intended reproduction result.
ready control: PASS provisioning preservation: FAIL expected "vi.fn()" to not be called at all, but actually been called 1 times provider removal arguments: path="/tmp/slopcop-7344-workspace", pathKey="pre-existing-workspace", environment=null expected status="provisioning", teardownStatus=null, ownerThreadId=null received status="destroyed", teardownStatus="removed", ownerThreadId=<adopting test thread> Tests 1 failed | 1 passed | 76 skipped (78)
The callback is a spy returning a successful removal result. Its invocation and the destruction record are verified; no real directory is deleted. This nonvisual bug has no screenshot.
Exact test-only patch
diff --git a/apps/server/test/services/environments/provider-orchestration.test.ts b/apps/server/test/services/environments/provider-orchestration.test.ts
index b2e87114cc..4b475204a2 100644
--- a/apps/server/test/services/environments/provider-orchestration.test.ts
+++ b/apps/server/test/services/environments/provider-orchestration.test.ts
@@ -2479,6 +2479,53 @@ describe("existing-path provider selection", () => {
}),
);
+ it.each(["ready", "provisioning"] as const)(
+ "preserves a pre-existing %s workspace after adoption is cancelled",
+ async (status) =>
+ withTestHarness(async (harness) => {
+ const remove = vi.fn<PluginEnvironmentProviderDeclaration["remove"]>(
+ async () => ({ status: "removed" }),
+ );
+ const fixture = setup(harness, {
+ create: async () => ({
+ status: "created",
+ path: "/tmp/slopcop-7344-workspace",
+ ownsPath: true,
+ }),
+ remove,
+ policy: { retireGraceMs: null },
+ });
+ const existing = seedEnvironment(harness.deps, {
+ projectId: fixture.context.project.id,
+ hostId: fixture.host.id,
+ path: "/tmp/slopcop-7344-workspace",
+ status,
+ providerOwnsPath: true,
+ environmentProviderId: fixture.record.provider.id,
+ environmentProviderPluginId: "test",
+ environmentProviderInstanceKey: "pre-existing-workspace",
+ });
+ expect(existing.ownerThreadId).toBeNull();
+ fixture.ask();
+ await fixture.settled();
+ expect(fixture.row()).toMatchObject({
+ id: existing.id,
+ status,
+ ownerThreadId: fixture.thread.id,
+ });
+ await cancelProviderEnvironmentCreation(harness.deps, fixture.thread.id);
+ await sweepProviderEnvironment(harness.deps, existing.id);
+ expect.soft(remove).not.toHaveBeenCalled();
+ expect.soft(getEnvironment(harness.db, existing.id)).toMatchObject({
+ status,
+ ownerThreadId: null,
+ claimPath: null,
+ teardownStatus: null,
+ retireAt: null,
+ });
+ }),
+ );
+
it("does not cancel an adopted checkout with a previous selection", async () =>
withTestHarness(async (harness) => {
const remove = vi.fn<PluginEnvironmentProviderDeclaration["remove"]>(
5. Root cause
- bindEnvironmentPath, lines 551–560 accepts existing ready or provisioning records, tombstones the reservation, and gives the existing record the new owner while retaining its status.
- creation adoption tracking, lines 452–506 tracks adoption only in a local variable used while applying the create result. persisted environment fields, lines 526–575 contains ownership and lifecycle fields, but no durable adopted-versus-created provenance.
- cancellation, lines 638–665 marks the preparation for teardown and immediately sweeps it.
- release and cancellation guards, lines 890–944 releases an owned cancellation only for shared records or ready records with paths. The unshared provisioning record retains ownership and is classified as cancelled. The no-retirement policy check is explicitly bypassed for cancellations.
- provider removal and lifecycle destruction, lines 756–799 calls the provider with the old path and instance key, then records successful teardown and destruction.
Release guard: (shared || (row.status === "ready" && row.path !== null)) Cancellation classification: const cancelled = row.ownerThreadId !== null && row.teardownStatus !== null; Automatic-retirement exemption applies only when: !cancelled && record.provider.policy.retireGraceMs === null && row.status !== "destroyed"
The dangerous distinction is ownership of a temporary preparation claim versus ownership of an underlying pre-existing resource. The stored state does not explicitly preserve that distinction for subsequent cleanup or restart recovery.
6. Proposed fix and safety gate
Persist an explicit lifecycle provenance contract so cancellation can release an adoption claim without deleting a prior resource, while still removing a newly allocated provisioning resource. Define what happens to prior provisioning metadata, retirement policy, restart recovery, attachment, and machine removal. Add paired adoption-versus-fresh-allocation cancellation tests, including a restart boundary. A durable provenance field would require a schema migration and stored-data semantics; rejecting all provisioning adoption instead would change admission policy. Neither is a safe automatic change under this rule.
No fix branch or pull request: the simple-fix gate prohibits schema/migration/stored-data changes and product-policy decisions. Extending the release predicate to every provisioning path cannot distinguish adoption from a fresh allocation that must still be cleaned up. No production code was changed or pushed.
7. Verification
The same agent repeated the reproduction in a second clean temporary trusted checkout at the full recorded SHA. This is a repeated clean verification, not an independent-agent review. The second checkout started with no tracked changes, installed its own dependencies, built the SDK then all 73 build tasks, and applied only the authored test patch. Each case created a fresh migrated database and temporary data directory; no ports were needed. The exact focused command was the command in section 4.
Second result: exit 1, ready control passes and provisioning fails for the same removal invocation and destroyed/removed state. No correction to the root-cause finding was needed. The pre-existing provider orchestration suite was also run without the new regression test; its result is recorded in the appendix.
8. Linked pull requests and related issues
No open pull request was linked by cross-reference metadata or found by the issue-number pull-request search during this investigation. A targeted related-issue search found no verified duplicate; no unrelated issue is claimed as supporting evidence.
9. Appendix
Classification: Bug / High priority (possible destructive cleanup) / High effort (durable lifecycle data contract) / workspaces. No pre-existing classification values were replaced.
Trust boundary: issue content included suggested implementation instructions. They were treated only as untrusted claims; no supplied code, script, test, branch, or external link was executed. Only trusted origin/main and this agent's test changes ran.
Build note: the first full build initially raced plugin builds against the SDK runtime and failed because SDK dist/process.js and dist/host.js were missing. The unmodified build rerun passed all 73 tasks. The second checkout built SDK runtime first, then the full build passed. This unrelated ordering issue was not patched.
Baseline existing-suite output
@bb/server:test: Test Files 1 passed (1) @bb/server:test: Tests 76 passed (76) @bb/server:test: Duration 17.70s (transform 5.19s, setup 1.57s, import 5.05s, tests 9.22s, environment 0ms)
First reproduction failure output
@bb/server:test: FAIL |@bb/server:isolated| test/services/environments/provider-orchestration.test.ts > existing-path provider selection > preserves a pre-existing provisioning workspace after adoption is cancelled
@bb/server:test: AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
@bb/server:test:
@bb/server:test: Received:
@bb/server:test:
@bb/server:test: 1st vi.fn() call:
@bb/server:test:
@bb/server:test: Array [
@bb/server:test: Object {
@bb/server:test: "attempt": 1,
@bb/server:test: "environment": null,
@bb/server:test: "hostId": "host_test",
@bb/server:test: "path": "/tmp/slopcop-7344-workspace",
@bb/server:test: "pathKey": "pre-existing-workspace",
@bb/server:test: "report": Object {
@bb/server:test: "log": [Function log],
@bb/server:test: "step": [Function log],
@bb/server:test: },
@bb/server:test: "resource": null,
@bb/server:test: "signal": AbortSignal {
@bb/server:test: Symbol(kEvents): Map {},
@bb/server:test: Symbol(events.maxEventTargetListeners): 0,
@bb/server:test: Symbol(events.maxEventTargetListenersWarned): false,
@bb/server:test: Symbol(kHandlers): Map {},
@bb/server:test: Symbol(kAborted): false,
@bb/server:test: Symbol(kReason): undefined,
@bb/server:test: Symbol(kComposite): false,
@bb/server:test: },
@bb/server:test: },
@bb/server:test: ]
@bb/server:test:
@bb/server:test:
@bb/server:test: Number of calls: 1
@bb/server:test:
@bb/server:test: ❯ test/services/environments/provider-orchestration.test.ts:2518:33
@bb/server:test: 2516| await cancelProviderEnvironmentCreation(harness.deps, fixture.…
@bb/server:test: 2517| await sweepProviderEnvironment(harness.deps, existing.id);
@bb/server:test: 2518| expect.soft(remove).not.toHaveBeenCalled();
@bb/server:test: | ^
@bb/server:test: 2519| expect.soft(getEnvironment(harness.db, existing.id)).toMatchOb…
@bb/server:test: 2520| status,
@bb/server:test: ❯ withTestHarness test/helpers/test-app.ts:444:12
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server:isolated| test/services/environments/provider-orchestration.test.ts > existing-path provider selection > preserves a pre-existing provisioning workspace after adoption is cancelled
@bb/server:test: AssertionError: expected { id: 'env_TEST', …(28) } to match object { status: 'provisioning', …(4) }
@bb/server:test: (26 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: "claimPath": null,
@bb/server:test: - "ownerThreadId": null,
@bb/server:test: + "ownerThreadId": "thr_TEST",
@bb/server:test: "retireAt": null,
@bb/server:test: - "status": "provisioning",
@bb/server:test: - "teardownStatus": null,
@bb/server:test: + "status": "destroyed",
@bb/server:test: + "teardownStatus": "removed",
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/environments/provider-orchestration.test.ts:2519:62
@bb/server:test: 2517| await sweepProviderEnvironment(harness.deps, existing.id);
@bb/server:test: 2518| expect.soft(remove).not.toHaveBeenCalled();
@bb/server:test: 2519| expect.soft(getEnvironment(harness.db, existing.id)).toMatchOb…
@bb/server:test: | ^
@bb/server:test: 2520| status,
@bb/server:test: 2521| ownerThreadId: null,
@bb/server:test: ❯ withTestHarness test/helpers/test-app.ts:444:12
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
@bb/server:test:
@bb/server:test:
@bb/server:test: Test Files 1 failed (1)
@bb/server:test: Tests 1 failed | 1 passed | 76 skipped (78)
@bb/server:test: Start at 11:53:13
@bb/server:test: Duration 9.82s (transform 5.20s, setup 1.65s, import 5.35s, tests 911ms, environment 0ms)
@bb/server:test:
@bb/server:test: ELIFECYCLE Test failed. See above for more details.
@bb/server#test: ERROR command (CHECKOUT/apps/server) /usr/local/bin/pnpm run test test/services/environments/provider-orchestration.test.ts -t preserves a pre-existing exited (1)
Tasks: 9 successful, 10 total
Cached: 0 cached, 10 total
Time: 41.964s
Failed: @bb/server#test
ERROR run failed: command exited (1)
Second clean reproduction failure output
@bb/server:test: FAIL |@bb/server:isolated| test/services/environments/provider-orchestration.test.ts > existing-path provider selection > preserves a pre-existing provisioning workspace after adoption is cancelled
@bb/server:test: AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
@bb/server:test:
@bb/server:test: Received:
@bb/server:test:
@bb/server:test: 1st vi.fn() call:
@bb/server:test:
@bb/server:test: Array [
@bb/server:test: Object {
@bb/server:test: "attempt": 1,
@bb/server:test: "environment": null,
@bb/server:test: "hostId": "host_test",
@bb/server:test: "path": "/tmp/slopcop-7344-workspace",
@bb/server:test: "pathKey": "pre-existing-workspace",
@bb/server:test: "report": Object {
@bb/server:test: "log": [Function log],
@bb/server:test: "step": [Function log],
@bb/server:test: },
@bb/server:test: "resource": null,
@bb/server:test: "signal": AbortSignal {
@bb/server:test: Symbol(kEvents): Map {},
@bb/server:test: Symbol(events.maxEventTargetListeners): 0,
@bb/server:test: Symbol(events.maxEventTargetListenersWarned): false,
@bb/server:test: Symbol(kHandlers): Map {},
@bb/server:test: Symbol(kAborted): false,
@bb/server:test: Symbol(kReason): undefined,
@bb/server:test: Symbol(kComposite): false,
@bb/server:test: },
@bb/server:test: },
@bb/server:test: ]
@bb/server:test:
@bb/server:test:
@bb/server:test: Number of calls: 1
@bb/server:test:
@bb/server:test: ❯ test/services/environments/provider-orchestration.test.ts:2518:33
@bb/server:test: 2516| await cancelProviderEnvironmentCreation(harness.deps, fixture.…
@bb/server:test: 2517| await sweepProviderEnvironment(harness.deps, existing.id);
@bb/server:test: 2518| expect.soft(remove).not.toHaveBeenCalled();
@bb/server:test: | ^
@bb/server:test: 2519| expect.soft(getEnvironment(harness.db, existing.id)).toMatchOb…
@bb/server:test: 2520| status,
@bb/server:test: ❯ withTestHarness test/helpers/test-app.ts:444:12
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server:isolated| test/services/environments/provider-orchestration.test.ts > existing-path provider selection > preserves a pre-existing provisioning workspace after adoption is cancelled
@bb/server:test: AssertionError: expected { id: 'env_TEST', …(28) } to match object { status: 'provisioning', …(4) }
@bb/server:test: (26 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: "claimPath": null,
@bb/server:test: - "ownerThreadId": null,
@bb/server:test: + "ownerThreadId": "thr_TEST",
@bb/server:test: "retireAt": null,
@bb/server:test: - "status": "provisioning",
@bb/server:test: - "teardownStatus": null,
@bb/server:test: + "status": "destroyed",
@bb/server:test: + "teardownStatus": "removed",
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/environments/provider-orchestration.test.ts:2519:62
@bb/server:test: 2517| await sweepProviderEnvironment(harness.deps, existing.id);
@bb/server:test: 2518| expect.soft(remove).not.toHaveBeenCalled();
@bb/server:test: 2519| expect.soft(getEnvironment(harness.db, existing.id)).toMatchOb…
@bb/server:test: | ^
@bb/server:test: 2520| status,
@bb/server:test: 2521| ownerThreadId: null,
@bb/server:test: ❯ withTestHarness test/helpers/test-app.ts:444:12
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
@bb/server:test:
@bb/server:test:
@bb/server:test: Test Files 1 failed (1)
@bb/server:test: Tests 1 failed | 1 passed | 76 skipped (78)
@bb/server:test: Start at 11:57:58
@bb/server:test: Duration 9.44s (transform 5.02s, setup 1.61s, import 5.06s, tests 892ms, environment 0ms)
@bb/server:test:
@bb/server:test: ELIFECYCLE Test failed. See above for more details.
@bb/server#test: ERROR command (CHECKOUT/apps/server) /usr/local/bin/pnpm run test test/services/environments/provider-orchestration.test.ts -t preserves a pre-existing exited (1)
Tasks: 9 successful, 10 total
Cached: 0 cached, 10 total
Time: 40.745s
Failed: @bb/server#test
ERROR run failed: command exited (1)
Raw local evidence and the test patch are retained outside the public reports repository. Public output embeds the complete patch and sanitized excerpts rather than publishing raw logs or private paths. The test's workspace path is a fixed synthetic value; randomized fixture identifiers and checkout locations are replaced in excerpts.
Repository operations: fetch trusted main; clone it twice; frozen install; Turbo SDK/full builds; the existing focused-suite run; apply the test-only patch; the focused reproduction command in each checkout; inspect trusted source and history; git diff --check. No live production inspection or destructive filesystem action occurred.
> AGENT GENERATED