Skip to content

update_environment_directory intermittently fails with "Environment at this path is error, not ready." (provisioning sweep fails the in-flight environment) #6014

Closed

Description

@ComicBit

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. Provider acp-omp.
  • Target: a plain git worktree add sibling of the project checkout.
  • The code path is unchanged on main at b143a22860944a96bf183605dfb0ffe58b1de283 (desktop-v0.46.1 = 411eac54).

Observed

  • Thread thr_uzwrwemjvt called update_environment_directory with /Users/leandropiccione/Projects/Aurora-531-bb-thread-worktree-moves. The call created env_34z5b3kkyc (createdAt 1792579222201) and returned:

    Environment at this path is error, not ready.
    
  • ~/.bb/logs/server.90.log line 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) created env_gr7fe34gnf and 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:

  1. Seed a thread on environment A and post update_environment_directory with a new path B.
  2. While the environment.attach command for B is in flight, run runEnvironmentProvisioningSweep (the job the 10 s interval runs).
  3. 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)

  1. The tool creates the environment as provisioning with 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's environmentOperations map:
    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);
    }
  2. Every 10 s the server runs runPeriodicSweeps, which calls advanceEnvironmentProvisioning for every creating/provisioning row:
    sweepInterval = setInterval(() => {
    if (!isServerMoveFrozen(db)) {
    void runPeriodicSweeps(sweepDeps);
    }
    }, 10_000);
    ,
    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",
    );
    }
    }
    }
  3. advanceEnvironmentProvisioning treats a provisioning row as in flight only if it is in that map. Otherwise it calls recoverEnvironmentProvisionRequest. That function returns null because path === null (and there is no starting thread), so the row goes to interruptUnrecoverableEnvironmentProvisioning:
    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;
    ,
    function recoverEnvironmentProvisionRequest(
    deps: CommandResultSideEffectsDeps,
    environment: EnvironmentRow,
    ): EnvironmentProvisionRequest | null {
    if (environment.path === null) return null;
  4. 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:
    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);
    }
    ,
    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",
    );
    }
  5. The attach then succeeds. provision.succeeded has no transition from error (the log line above), and the tool reads the row back as error:
    const provisionedOutcome =
    applyLoggedEnvironmentLifecycleEventInTransaction(args.deps, {
    environmentId: args.command.environmentId,
    event: { type: "provision.succeeded" },
    });
    ,
    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: {},
    };
    ,
    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 runTrackedEnvironmentProvisionCommand in environment-engine.ts, used by provisionUnmanagedEnvironmentForPath.
  • 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/server passes.

Per CONTRIBUTING.md I have not opened a pull request: I am not on the approved-contributor list.

Ruled out

AGENT GENERATED

Activity

  1. added theissue type on Oct 21, 2026
  2. added
    workspaces
    confirmed-repro
    on Oct 21, 2026
  3. bb-slop-cop commented on Oct 21, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Medium priority · Low effort; labels: workspaces, confirmed-repro.
    • Reproduction report: REPRODUCED, root-cause confidence high; repeated in two clean trusted checkouts.
    • Root cause: directory attaches bypass lifecycle operation tracking, so recovery can fail their pending environments before successful attach settlement.
    • Regression: the route-level test fails before the fix for both periodic sweeps and host-resume recovery; the control passes. After the fix, 124 relevant tests and server typecheck pass.
    • Ready fix: PR #6016, 234 changed text lines across 3 files. Not merged.

    AGENT GENERATED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reproworkspaces

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions