Repository navigation
Description
Summary
update_environment_directory to a directory with no existing environment sometimes fails on the first call with Environment at this path is error, not ready. The new unmanaged environment is moved to error while its environment.attach command is still running. The periodic environment-provisioning sweep (every 10 s) treats the in-flight row as an unrecoverable orphan. A retry usually succeeds.
Versions and environment
- bb 0.46.1 (npm
bb-app), macOS 26.7.1 arm64, Node v26.8.1. Provideracp-omp. - Target: a plain
git worktree addsibling of the project checkout. - The code path is unchanged on
mainatb143a22860944a96bf183605dfb0ffe58b1de283(desktop-v0.46.1=411eac54).
Observed
-
Thread
thr_uzwrwemjvtcalledupdate_environment_directorywith/Users/leandropiccione/Projects/Aurora-531-bb-thread-worktree-moves. The call createdenv_34z5b3kkyc(createdAt1792579222201) and returned:Environment at this path is error, not ready. -
~/.bb/logs/server.90.logline 3128, 677 ms after the environment was created:{"level":30,"time":1792579222878,"component":"server","detail":"no transition for provision.succeeded from status error","environmentId":"env_34z5b3kkyc","event":"provision.succeeded","reason":"illegal-transition","msg":"Environment lifecycle event not applied"}This is the only log line that mentions the environment, in the server logs and in the host-daemon logs. No daemon session opened or disconnected in that window, so the host reconnect and disconnect paths are ruled out.
-
After
bb environment delete env_34z5b3kkyc, a second call (~1792579268160) createdenv_gr7fe34gnfand succeeded (ready). An earlier move of the same thread to another sibling worktree (env_mtp7x7c57j) succeeded on the first try.
Steps to reproduce
The race is timing-dependent: it needs a sweep tick inside the attach window. I did not reproduce it live on demand. The regression test below drives the same code path deterministically on main:
- Seed a thread on environment A and post
update_environment_directorywith a new path B. - While the
environment.attachcommand for B is in flight, runrunEnvironmentProvisioningSweep(the job the 10 s interval runs). - Report the attach command as successful.
Actual on main: the tool returns success: false, text Environment at this path is error, not ready.
Expected: the environment stays provisioning through the sweep, becomes ready, and the thread moves to it.
Root cause (base b143a22860944a96bf183605dfb0ffe58b1de283)
- The tool creates the environment as
provisioningwith no path and no owner thread. It then runs the attach as a plain live host command. That command is not registered in the engine'senvironmentOperationsmap:bb/apps/server/src/services/threads/thread-environment-directory.ts
Lines 229 to 264 in b143a22
const environment = createEnvironment(deps.db, deps.hub, { projectId: args.thread.projectId, hostId: args.currentEnvironment.hostId, providerOwnsPath: false, status: "provisioning", environmentProvider: null, }); const command = buildEnvironmentProvisionCommand({ environmentId: environment.id, hostId: args.currentEnvironment.hostId, initiator: null, path: args.path, setupScriptTimeoutMs: null, }); try { await runLiveHostCommand(deps, { hostId: args.currentEnvironment.hostId, command, timeoutMs: UPDATE_ENVIRONMENT_DIRECTORY_TIMEOUT_MS, }); } catch (error) { const message = error instanceof Error ? error.message : String(error); return toolCallFailure( `Could not update environment directory to ${args.path}: ${message}`, ); } const readyEnvironment = getEnvironment(deps.db, environment.id); if (!readyEnvironment) { return toolCallFailure("Prepared environment no longer exists."); } const ready = resolveReadyEnvironment(readyEnvironment); if ("failure" in ready) { return toolCallFailure(ready.failure); } - Every 10 s the server runs
runPeriodicSweeps, which callsadvanceEnvironmentProvisioningfor everycreating/provisioningrow:,bb/apps/server/src/start-server.ts
Lines 467 to 471 in b143a22
sweepInterval = setInterval(() => { if (!isServerMoveFrozen(db)) { void runPeriodicSweeps(sweepDeps); } }, 10_000); bb/apps/server/src/services/system/periodic-sweeps.ts
Lines 312 to 336 in b143a22
export async function runEnvironmentProvisioningSweep( deps: LoggedPendingInteractionWorkSessionDeps, ): Promise<void> { const provisioningEnvironments = deps.db .select({ id: environments.id }) .from(environments) .where(inArray(environments.status, ["creating", "provisioning"])) .all(); for (const environment of provisioningEnvironments) { try { await advanceEnvironmentProvisioning(deps, { environmentId: environment.id, }); } catch (error) { deps.logger.warn( { err: error, environmentId: environment.id, }, "Environment provisioning sweep failed", ); } } } advanceEnvironmentProvisioningtreats aprovisioningrow as in flight only if it is in that map. Otherwise it callsrecoverEnvironmentProvisionRequest. That function returnsnullbecausepath === null(and there is nostartingthread), so the row goes tointerruptUnrecoverableEnvironmentProvisioning:,bb/apps/server/src/services/environments/environment-engine.ts
Lines 1918 to 1932 in b143a22
if ( environment.status !== "provisioning" || map.has(environment.id) || findHostDataDir(deps, environment.hostId) === null ) return; const request = args.request ?? recoverEnvironmentProvisionRequest(deps, environment); if (request === null) { interruptUnrecoverableEnvironmentProvisioning(deps, { environmentId: environment.id, reason: "Environment setup did not finish. Retry provisioning to continue.", }); return; bb/apps/server/src/services/environments/environment-engine.ts
Lines 1683 to 1687 in b143a22
function recoverEnvironmentProvisionRequest( deps: CommandResultSideEffectsDeps, environment: EnvironmentRow, ): EnvironmentProvisionRequest | null { if (environment.path === null) return null; - That applies
provision.failed(provisioning → error). An applied event is not logged and no thread is bound yet, so nothing shows up in the logs:,bb/apps/server/src/services/environments/environment-engine.ts
Lines 1228 to 1264 in b143a22
function recordEnvironmentProvisioningFailureInTransaction( deps: EnvironmentProvisionTransactionDeps, args: FailEnvironmentProvisioningDurablyArgs, ): string[] { const environment = getEnvironment(deps.db, args.environmentId); if (!environment) { return []; } const liveThreads = listLiveEnvironmentThreads(deps, environment.id); const failureThreads = liveThreads.filter( (thread) => !shouldPreserveThreadProvisionCancellationOutcome(deps, { provisioningId: args.provisioningId, thread, }), ); if (failureThreads.length === 0 && liveThreads.length > 0) { if (environment.status === "destroyed") return []; const outcome = applyLoggedEnvironmentLifecycleEventInTransaction(deps, { environmentId: environment.id, event: { type: "provision.cancelled" }, }); if (outcome.applied) deps.hub.notifyEnvironment(environment.id, outcome.changes); return []; } const failureOutcome = applyLoggedEnvironmentLifecycleEventInTransaction( deps, { environmentId: environment.id, event: { type: "provision.failed" }, }, ); if (failureOutcome.applied) { deps.hub.notifyEnvironment(environment.id, failureOutcome.changes); } bb/apps/server/src/services/environments/lifecycle-outcome.ts
Lines 26 to 43 in b143a22
function logUnappliedEnvironmentLifecycleEvent( logger: ServerLogger, args: ApplyEnvironmentLifecycleEventArgs, outcome: ApplyEnvironmentLifecycleEventOutcome, ): void { if (outcome.applied) { return; } logger.info( { detail: outcome.detail, environmentId: args.environmentId, event: args.event.type, reason: outcome.reason, }, "Environment lifecycle event not applied", ); } - The attach then succeeds.
provision.succeededhas no transition fromerror(the log line above), and the tool reads the row back aserror:,bb/apps/server/src/services/environments/environment-engine.ts
Lines 1355 to 1359 in b143a22
const provisionedOutcome = applyLoggedEnvironmentLifecycleEventInTransaction(args.deps, { environmentId: args.command.environmentId, event: { type: "provision.succeeded" }, }); ,bb/packages/domain/src/environment-lifecycle.ts
Lines 31 to 49 in b143a22
provisioning: { "provision.succeeded": "ready", "provision.failed": "error", "provision.cancelled": { withWorkspacePath: "ready", withoutWorkspacePath: "destroyed", }, }, ready: { "provision.requested": "provisioning", "destroy.recorded": "destroyed", }, error: { "provision.requested": "provisioning", "destroy.recorded": "destroyed", }, destroyed: {}, }; bb/apps/server/src/services/threads/thread-environment-directory.ts
Lines 125 to 131 in b143a22
function resolveReadyEnvironment( environment: EnvironmentRow, ): ReadyEnvironment | { failure: string } { if (environment.status !== "ready") { return { failure: `Environment at this path is ${environment.status}, not ready.`, };
The failure rate is roughly attach duration ÷ 10 s. For a 0.7 s attach that is about 7 %, so the failure is intermittent.
Proposed fix
Register the tool's attach as a tracked attach operation keyed by the new environment id. The engine already skips rows in that map (map.has(environment.id)), so the sweep and resumeEnvironmentProvisioningForHost leave the row alone while the command runs. Command errors still reach the tool. The daemon disconnect/restart interruption still fails the row, as it should.
Fork branch: ComicBit/bb@main...ComicBit:bb:fix/update-environment-directory-provision-race (commit 58b452401da3276e12eaeaf28b9aa3504c0fe28d)
- New
runTrackedEnvironmentProvisionCommandinenvironment-engine.ts, used byprovisionUnmanagedEnvironmentForPath. - Regression test in
apps/server/test/internal/internal-events-tool-calls.test.ts("keeps a new unmanaged environment provisioning when the provisioning sweep runs mid-move"). Without the fix it fails with"text": "Environment at this path is error, not ready."; with the fix it passes. pnpm exec turbo run test --filter=@bb/server -- test/internal/internal-events-tool-calls.test.ts test/services/environments/provider-orchestration.test.ts test/threads/thread-provisioning-recovery.test.ts test/services/periodic-sweeps.test.ts: 4 files, 123 tests pass.turbo run typecheck --filter=@bb/serverpasses.
Per CONTRIBUTING.md I have not opened a pull request: I am not on the approved-contributor list.
Ruled out
- Host daemon reconnect/disconnect (
interruptEnvironmentProvisioningForHost,resumeEnvironmentProvisioningForHost): no session events in the window. The fix covers the resume path too. - A failed attach report: that path (
!initiator && !report.ok) would make the tool returnCould not update environment directory …, not… is error, not ready. - Duplicates: searched
update_environment_directory,not ready,provision.succeeded from status error,environment provisioning sweep,Environment setup did not finish. Related but different: update_environment_directory commits the switch but strands the Pi tool call until manual interruption #3187, Continue automatically after switching a thread's directory #4778.
AGENT GENERATED
Activity
bb-slop-cop commentedon Oct 21, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotworkspaces,confirmed-repro.Track directory attaches during environment recovery (#6016)