Skip to content

Fix stuck workspace claims after failed thread setup - #4325

Merged
ymichael merged 3 commits into
mainfrom
bb/unable-to-send-messages-after-renaming-a-session-thr_qjdeq8neme
Sep 25, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/unable-to-send-messages-after-renaming-a-session-thr_qjdeq8neme

Conversation

@ymichael

@ymichael ymichael commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Failed thread setup could leave an exclusive host/path claim behind. Other threads sharing that checkout then failed to send with HTTP 409 workspace_busy (“Cannot checkout branch while another thread is using this workspace”), even though the owning preparation had already failed. This could appear after renaming a session, but renaming was not the cause.

What changed

  • Request environment cleanup immediately when thread provisioning fails.
  • Repair abandoned claims when sends, explicit environment reuse, environment admission, or provider path claims encounter them. Release ready/shared checkouts locally and continue the operation without restarting the server.
  • Preserve claims owned by threads still starting or stopping, and avoid interfering with machine removal or cleanup already in progress.
  • For unfinished resources, retain the claim and schedule the existing background lifecycle cleanup. Sends report that cleanup is pending until removal completes; admission never waits for provider removal.
  • Document recovery behavior and add regression coverage. No new startup sweep, database schema/migration, CLI flags, public SDK members, or server/daemon wire changes. Existing ownership and teardown fields carry the lifecycle changes; no protocol version bump is needed.

How you verified

  • pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/db: typechecks and all 589 DB tests passed. The server run passed 3,195 tests, including all 8 claim-recovery tests; 4 failures occurred in installer/machine-environment tests.
  • Focused rerun of test/app/install-machine-script.test.ts and test/public/machine-environment.test.ts: 47 passed, 2 installer failures remained (5-second enrollment timeout and reconnect refusal for an unowned daemon on port 38888). Both machine-environment tests passed. The installer tests exercise the unchanged shell script rather than the modified admission code; the full suite is not claimed green.
  • Follow-up explicit reuse regression reproduced the review finding before the fix. Reuse now repairs claims after project/host validation and reloads the environment before checking ownership; starting/stopping owners remain blocked. All 77 focused tests (11 claim tests and 66 environment-provider tests) and the server typecheck passed; all 40 adjacent thread-creation tests passed too. Live CLI thread spawn --environment recovered the seeded claim and received the actual assistant reply QA_EXPLICIT_REUSE_OK.
  • Recovery tests cover competing claimers, immediate failure cleanup, shared checkout preservation, admission and provider claim recovery, starting/stopping owners, no startup repair, and retaining claims until deferred removal finishes.
  • Built and ran pnpm start:worktree. Injected a stale claim into a synthetic QA workspace, sent through the built BB CLI, and received QA_ON_DEMAND_OK. Injected it again, submitted through Chromium, and received QA_BROWSER_REPAIRED; the reply persisted after reload. Server launch ID stayed unchanged throughout both repairs. Verified the checkout remained ready while owner, claim, and stale preparation message were cleared.
  • git diff --check passed. Scoped lint ran no tasks because these packages do not define lint scripts.

AGENT GENERATED

ymichael and others added 3 commits September 24, 2026 20:48
## Root cause

A provider takes an exclusive host+path claim during `create()`. When the
thread's setup then fails, `failThreadProvisioning` marks the thread failed
but never cleans up the environment the thread was preparing, so the row
keeps `owner_thread_id` and `claim_path`. No cleanup path handles it:
`prepareProviderEnvironment` rejects the errored row and the lifecycle sweep
skips rows that still have an owner.

When the thread was adopting an existing shared checkout,
`bindEnvironmentPath` had already moved its owner and claim onto the shared
ready row, which also carries over the "Preparing ..." status message. Every
thread already on that checkout then fails sends with 409 `workspace_busy`
("Cannot checkout branch while another thread is using this workspace")
until the row is edited by hand.

## Change

- `failThreadProvisioning` now calls `cancelProviderEnvironmentCreation`,
  as archive, stop and delete already do. A preparation used by no other
  thread goes through provider `remove()`, and the claim is released once
  removal finishes. A shared checkout is released at once and stays ready.
- Startup recovery calls `cancelAbandonedEnvironmentPreparations` on rows
  whose owner is no longer starting or stopping, which repairs environments
  that are already stuck.

## Verification

- `environment-path-claim-release.test.ts`: the first claimer fails and a
  racing thread gets the path; a failed adopter releases a shared checkout
  without destroying it; startup repair frees both an errored row and a
  shared row; startup repair that runs before the provider registers
  finishes on the next lifecycle sweep; a claim whose owner is still
  provisioning is kept. All but the last fail without the change.
- `turbo run lint typecheck test --filter=@bb/server --filter=@bb/db`
  passes, except `install-machine-script.test.ts` timeouts under load,
  which pass in isolation.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ymichael
ymichael merged commit dcc5837 into main Sep 25, 2026
18 checks passed
@ymichael
ymichael deleted the bb/unable-to-send-messages-after-renaming-a-session-thr_qjdeq8neme branch September 25, 2026 04:30
ymichael added a commit that referenced this pull request Nov 16, 2026
…und (#7553)

## Human comments

## What was wrong

Past environment bugs (#3650, #4325, #6828, #6892, #7194, #7242, #7311
and others) were each caught after release, one ordering at a time. No
test drove the real environment engine, the real Worktree and Project
checkout plugins, and real git together through orderings of user and
machine events. The ordering test added here found two bugs on main, and
this PR fixes both.

1. **A deleted environment stuck after an unarchive, then removed with
no grace.** `DELETE /environments/:id` only sets `teardownStatus:
"running"`; the removal happens on the next sweep. If a thread was
unarchived before that sweep, `sweepProviderEnvironmentInSlot` returned
early for an environment with live threads and never cleared the
request. The environment stayed in `teardown` indefinitely: restore
refused it ("not destroyed") and cleanup refused it ("still has live
threads"). The next archive skipped both the 30 s archive undo grace and
the 5-minute retire grace, and removed the worktree, uncommitted files
included, within a second.
2. **A thread failed when the same daemon reconnected during worktree
setup.** #5961 records a setup marker before sending
`environment.attach`. When the daemon reconnected as the same instance
(#3650's case), the server re-sent the attach, but
`runEnvironmentProvisionCommand` refused because the marker was
unfinished. The thread failed with "An earlier setup has an unknown
outcome…", even though the setup was still running and finished seconds
later. The #3650 test seeds a path the provider doesn't own, so it never
writes the marker. Proof runs show the failure starts at #5961.

## What changed

- `apps/server/src/services/environments/environment-engine.ts`
- **Bug 1:** when the sweep finds live threads on an environment whose
removal was requested but has not started (`teardownStatus: "running"`
while still `ready`; starting a removal sets `error`), it withdraws the
request (`teardownStatus` and `retireAt` back to null), and normal
retirement applies. The withdrawal is silent: nothing is added to the
thread's timeline. A removal that has already started is untouched
(#6892's path).
- **Bug 2:** a new `resumeEnvironmentProvisioningForReconnectedDaemon`,
called only from the daemon socket-open path, may re-send an attach
whose setup marker is unfinished. This is safe because the session-open
route, which is awaited before the daemon opens its socket, already
interrupts every provisioning environment when a *different* daemon
instance replaces the session. An environment still provisioning at
socket open therefore had its setup sent to this same daemon, and
`RuntimeManager.ensureEnvironment` joins the in-flight setup (or returns
the finished entry). `resumeEnvironmentProvisioningForHost` keeps main's
signature and behaviour. Every other path keeps #5961's refusal: the
periodic sweep, retries, and the server-move release.
- `apps/server/src/ws/daemon-protocol.ts`: socket open calls the new
resume.
- `packages/templates/src/templates/bb-guide-environments.md`: `bb
environment delete` notes that unarchiving a thread before removal
starts cancels the request.
- New tests:
-
`apps/server/test/services/environments/provider-orchestration.test.ts`:
archive, `DELETE /environments/:id`, unarchive; then the sweep keeps the
environment ready, and never calls `remove`.
-
`apps/server/test/environments/environment-lifecycle-orderings.test.ts`:
the ordering suite.
- **Real code, real data.** A migrated SQLite database
(`createMigratedConnection`), the real server environment engine and
routes, and the real Worktree and Project checkout plugins. Their host
halves run in host-entry harnesses against real git repositories (with a
bare `origin`) in a fresh `mkdtemp` directory, reached through
`plugin.host.call` on a fake daemon.
- **Fake daemon.** It runs turns, answers `environment.attach` by
inspecting the real workspace, can hold or fail any host operation, and
can disconnect, reconnect, or restart as a new instance.
- **Ten orderings** built from create, attach a second thread, archive,
unarchive, remove or retire, restore, failed setup, and daemon
disconnect, reconnect and restart, on one or two machines.
- **Rules checked after every ordering**, compared by rule and subject
only, never messages, counts or timings:
      - `removed-in-use`
      - `work-lost`
      - `orphaned-worktree` / `-branch` / `-claim` / `-row`
- `unsettled-environment` / `unsettled-thread` / `thread-failed` /
`create-raced`
- `setup-rerun`: a restarted daemon is never asked to re-run a setup
whose outcome is unknown. This guards #5961, and it fails if the restart
interrupt at session open is removed.

      There are no known failures.

No protocol, wire, schema, CLI, SDK or plugin API changes. No new
`@bb/db` query functions. No existing test is changed: the server-move
code and its tests, `internal-events-tool-calls.test.ts`, and #5961's
tests are identical to main.

**What a user would see differently, beyond the bugs going away
(decisions for Michael):**
- Deleting an environment and then unarchiving one of its threads before
the removal starts (up to one 10 s sweep) keeps the workspace. Within
one sweep, `bb environment show` returns to `Lifecycle: active`. Before,
the environment was stuck in `teardown` and the next archive removed it
within a second, skipping both graces.
- If the server restarts during worktree setup and the same daemon
process reconnects, setup now resumes instead of failing with "An
earlier setup has an unknown outcome". A restarted daemon still fails
the thread as before.

**Run time:** about 25 s of test time for the ordering file (10
orderings), in its own isolated worker.

## How you verified

**Live, before and after**, using `pnpm start:worktree` from this
checkout on fresh dev data dirs (never a copy of `~/.bb`), the real host
daemon, real Claude Code turns, and temp git repos with an `origin`:
- **Bug 1.** Spawn a worktree thread, `bb thread archive`, `bb
environment delete`, `bb thread unarchive`.
- *Before:* the environment stayed `teardown / running`.
`restore-environment` → 409 "Thread must be settled…"; `environment
cleanup` → 409 "still has live threads". When the thread was archived
again, the worktree and an uncommitted `notes.txt` were gone within 1 s.
- *After:* within one sweep the environment was back to `Lifecycle:
active`. The thread's timeline gets no new entry. On the next archive
the worktree and `notes.txt` survived 60 s, with `retireAt` 5 minutes
out.
- **Bug 2, daemon reconnect.** A 60 s `.bb-env-setup.sh`; the server was
paused with SIGSTOP for 40 s so the daemon's lease expired.
`host_daemon_sessions` shows the same `instance_id` reconnecting.
- *Before:* "Workspace setup interrupted" → "An earlier setup has an
unknown outcome…", while the setup then finished.
- *After:* the setup completed, the marker finished, the thread went
idle and Claude replied "ok". `.bb-env-setup.sh` ran once.
- **Bug 2, server restart.** The server process was killed with SIGKILL
during the same 60 s setup, and the launcher restarted it (new PID
within 3 s). The daemon kept its PID and `instance_id`, so its session
was replaced by the same instance. The thread went idle with Claude's
"ok", the setup marker finished, and the script's own run log has
exactly one line.
- **#5961's protection, live on the fixed build.** The daemon was killed
with SIGKILL during setup and respawned as a new instance. The thread
failed with "Host daemon restarted while preparing the workspace", and
setup was not re-run.
- **Server-move release path, shown by existing tests.** This PR doesn't
change `apps/server/src/services/server-move/environment.ts` (zero diff
against main). Its call, `resumeEnvironmentProvisioningForHost`, keeps
main's signature and behaviour (`setupRunsOnConnectedDaemon: false`).
The existing, unmodified `test/server-move/freeze-work.test.ts` asserts
that a move release calls it with `{ hostId }`. The existing, unmodified
#5961 test in `test/environments/environment-provisioning.test.ts`
("does not replace an unresolved RuntimeManager setup with a new
successful attempt") asserts that this path still refuses an unfinished
setup. Both pass.

**Proof runs of the test** (kept out of this PR). The test was run on
each listed fix's merge commit and its parent, and the violations were
diffed:

| Fix | Caught? | Ordering → violation on the parent |
|---|---|---|
| #3650 | yes | reconnect during setup → `thread-failed: A` |
| #4325 | yes | second thread's setup fails on a shared checkout →
`orphaned-claim: env(B)` |
| #6828 | yes | retire with a `refs/worktree/*` ref → `work-lost:
worktree-ref in A` |
| #6892 | yes | unarchive while removal runs → `orphaned-row: env(A)` |
| #7194 | yes | slow removal on machine a while b's grace passes →
`unsettled-environment: env(B)` |
| #7242 | yes | archive and retire → `orphaned-branch: env(B)` |
| #7311 | yes | three creates on one checkout path → `create-raced:
create C`, `thread-failed: A` |
| #3756 (extra) | yes | archive during setup → `unsettled-thread: A` |
| #4187 | no | The cancel only fired on a second placement pass while
the new thread still owned the merged checkout row. Public actions join
in one pass. |
| #5961 | no | Before #5961, attach-based setup wrote no persisted hook
record, so the retry loop it fixed never arises here. |
| #6016 | no | Directory moves are not among the orderings. |
| #6889 | no | Only an error message changed, and the test asserts
rules, not messages. |

The restart ordering and the `setup-rerun` rule were added after the
proof runs. They guard the reconnect fix and were checked by the
mutation above rather than against history.

**Local:** targeted suites pass: `test/environments`,
`test/services/environments`, thread provisioning recovery, internal
events tool calls, periodic sweeps, public environment routes,
environment providers, live commands and `test/server-move` (375 tests),
plus `@bb/thread-view` and `@bb/templates` tests. `turbo run typecheck
lint:type-aware` for `@bb/server` and `@bb/thread-view` pass, and `oxfmt
--check` is clean. CI runs the full suites.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant