← reports

#7963 · Scheduler progress in a desktop watcher test

BugPriority: MediumEffort: LowdesktopIssue2026-11-21

Trusted main commit: 4e45c9bc12fbed430f2e804fb827ac46089fc582

REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro

1. TL;DR

A desktop unit test can fail even though the watcher has correctly queued another lock check. The test drives its own manual scheduler only twice, then waits using real timers; waiting alone cannot execute callbacks in that manual scheduler. If the initial filesystem read is still pending when the fallback poll runs, the poll asks for a later recheck instead of reading the newly written marker immediately. A deterministic filesystem-completion gate reproduces the original zero-callback assertion in two clean checkouts without changing production code. Driving the scheduler during the wait makes all 51 tests in the file pass in the first checkout.

2. Claims vs findings

ClaimFindingEvidence
The watch-error test can fail with no move callback.VerifiedThe original callback assertion fails after a controlled, valid ordering of an actual missing-file read and a fallback poll, in both checkouts.
A concurrent poll requests a check which is queued after the final flush.VerifiedAfter releasing the initial read: two scheduled callbacks remain and zero moves have been delivered. Code inspection identifies the recurring poll and debounced recheck.
Continuing scheduler progress removes this failure.VerifiedA locally authored interval that flushes the scheduler during the assertion wait makes the complete 51-test file pass; production code is unchanged.
The particular earlier CI run failed for exactly this interleaving.UnverifiedThe historical failure's precise I/O ordering was not observable. This report reproduces the same assertion and independently establishes a sufficient cause, not the original CI timeline.

3. Environment

4. Minimal reproduction

The failing test remains the existing repository test, rather than a reimplementation of the watcher. The added helper wraps the real filesystem read: it preserves the actual ENOENT result, but holds its delivery until the test has fired the poll. The success path, marker write, validation, watcher, and assertion remain real. This forces an ordering which naturally occurs under asynchronous I/O without requiring sleeps.

  1. Prepare the trusted base and build its owning subsystem:
    git clone https://github.com/get-bb/bb.git bb-7963
    cd bb-7963
    git checkout --detach 4e45c9bc12fbed430f2e804fb827ac46089fc582
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/desktop
  2. Optional baseline: the uninstrumented focused test passed in the first checkout. One pass does not disprove a race.
    pnpm exec turbo run test --filter=@bb/desktop -- test/server-moved.test.ts -t 'closes the watcher and polls after a watch error'
    
    Test Files  1 passed (1)
         Tests  1 passed | 50 skipped (51)
  3. Save the following complete patch as /tmp/reproduce-7963.patch and apply it with git apply /tmp/reproduce-7963.patch. It changes only test instrumentation. The entire helper test-support file is included in this patch.
    diff --git a/apps/desktop/test/server-moved.test.ts b/apps/desktop/test/server-moved.test.ts
    index 65b45536a8..67ea7a3245 100644
    --- a/apps/desktop/test/server-moved.test.ts
    +++ b/apps/desktop/test/server-moved.test.ts
    @@ -1,3 +1,4 @@
    +import { missingReadGate } from "./repro-7963.js";
     import { mkdtemp, rm, writeFile } from "node:fs/promises";
     import { createServer, type Server, type ServerResponse } from "node:http";
     import { tmpdir } from "node:os";
    @@ -701,9 +702,11 @@ describe("createServerMovedWatcher", () => {
     
       it("closes the watcher and polls after a watch error", async () => {
         const harness = await createHarness();
    +    missingReadGate.active = true;
         try {
           harness.watcher.start();
           harness.timers.flush();
    +      await missingReadGate.captured.promise;
     
           harness.fakeWatch.emitError(new Error("EMFILE"));
     
    @@ -711,10 +714,18 @@ describe("createServerMovedWatcher", () => {
           expect(harness.logWarning.mock.calls[0]?.[0]).toContain("EMFILE");
           await writeServerMovedFile(harness.dataDir, movedFile());
           harness.timers.flush();
    +      missingReadGate.release.resolve();
    +      await vi.waitFor(() => {
    +        expect(harness.timers.pendingCount()).toBe(2);
    +      });
    +      console.info("queued timers:", harness.timers.pendingCount());
    +      console.info("delivered moves:", harness.onMove.mock.calls.length);
           await vi.waitFor(() => {
             expect(harness.onMove).toHaveBeenCalledExactlyOnceWith(CONNECT_MOVE);
           });
         } finally {
    +      missingReadGate.active = false;
    +      missingReadGate.release.resolve();
           harness.watcher.stop();
         }
       });
    diff --git a/apps/desktop/test/repro-7963.ts b/apps/desktop/test/repro-7963.ts
    new file mode 100644
    index 0000000000..996733862d
    --- /dev/null
    +++ b/apps/desktop/test/repro-7963.ts
    @@ -0,0 +1,34 @@
    +import { vi } from "vitest";
    +
    +const missingReadGate = vi.hoisted(() => ({
    +  active: false,
    +  captured: Promise.withResolvers<void>(),
    +  release: Promise.withResolvers<void>(),
    +}));
    +
    +export { missingReadGate };
    +
    +vi.mock("node:fs/promises", async (importOriginal) => {
    +  const filesystem = await importOriginal<typeof import("node:fs/promises")>();
    +  return {
    +    ...filesystem,
    +    async readFile(...parameters: Parameters<typeof filesystem.readFile>) {
    +      try {
    +        return await filesystem.readFile(...parameters);
    +      } catch (error) {
    +        if (
    +          missingReadGate.active &&
    +          typeof parameters[0] === "string" &&
    +          parameters[0].endsWith("/server-moved.json") &&
    +          error instanceof Error &&
    +          "code" in error &&
    +          error.code === "ENOENT"
    +        ) {
    +          missingReadGate.captured.resolve();
    +          await missingReadGate.release.promise;
    +        }
    +        throw error;
    +      }
    +    },
    +  };
    +});
  4. Run the same repository test again:
    pnpm exec turbo run test --filter=@bb/desktop -- test/server-moved.test.ts -t 'closes the watcher and polls after a watch error'

    Expected: the existing exactly-once callback assertion passes after the marker is written. Actual: the test times out with zero callbacks despite pending checks. The following diagnostic and failure excerpts are verbatim, with only the task prefix omitted:

    queued timers: 2
    delivered moves: 0
    
    AssertionError: expected "vi.fn()" to be called once with arguments: [ { moveId: 'move-1', …(3) } ]
    
    Number of calls: 0
    
     ❯ test/server-moved.test.ts:724:32
    
    Test Files  1 failed (1)
         Tests  1 failed | 50 skipped (51)

    Both first and second reproduction commands exit 1. The failure is the original move-delivery assertion, not a build, mock-loading, gate, or pending-count error.

5. Root cause

The manual scheduler takes a snapshot of its current callbacks when flush() is called. It neither waits for asynchronous checks nor runs callbacks queued after that snapshot. The watch-error test performs its last flush before entering vi.waitFor.

Inside the watcher, a second check arriving while checking is true only sets recheckRequested. After the first check returns no marker, another debounced check is scheduled:

async function checkLock(): Promise<void> {
  if (checking) {
    recheckRequested = true;
    return;
  }
  ...
  if (recheckRequested && active) {
    recheckRequested = false;
    scheduleCheck();
  }
}
  1. The first flush starts a real read of a missing marker and leaves checking true.
  2. The watch error closes the watch handle and queues a fallback poll. The test writes a valid marker.
  3. The second flush fires the poll while the first read result is still pending. The poll requests a recheck and queues its next recurring poll.
  4. The initial missing-file result is released. checkLock queues the debounced recheck after that second flush.
  5. Two manual callbacks remain. Real-time waiting never drives them, so onMove stays at zero calls.

The underlying problem is test-driver progress, not evidence of a broken real-timer polling algorithm. The actual marker read and validation are delegated through readServerMovedLock and readServerMovedFile. No production change is needed to explain or remove this test failure.

6. Proposed fix and control experiment

Make progress on the test's manual scheduler while waiting for the exactly-once move callback, rather than assuming one snapshot flush drains asynchronous follow-up work. Keep the watch-close, warning, delivery, and cleanup assertions. A permanent test should use the existing scheduler harness; avoid adding sleep delays or new production injection hooks.

For a distinct local control, the following interval was added around the original callback wait after the same gated ordering. This drives only the existing test scheduler and is not a proposed production change:

const timerPump = setInterval(() => harness.timers.flush(), 5);
try {
  await vi.waitFor(() => {
    expect(harness.onMove).toHaveBeenCalledExactlyOnceWith(CONNECT_MOVE);
  });
} finally {
  clearInterval(timerPump);
}
pnpm exec turbo run test --filter=@bb/desktop -- test/server-moved.test.ts

Test Files  1 passed (1)
     Tests  51 passed (51)

The complete file passed in the first checkout with this control. The same instrumentation without scheduler progress fails on the original assertion. These results isolate manual-scheduler starvation from marker parsing, watcher closure, and move confirmation.

7. Linked PR review

PR #7964 · Static review only

PR #7964 is open and GitHub's closing-issue metadata links it to #7963. Its diff moves the manual flush from immediately before the callback wait into that wait's retry callback. This matches the independently verified requirement that newly queued checks continue running until delivery.

Findings: no blocking issue identified in the one-file diff. The proposed location is apps/desktop/test/server-moved.test.ts:713. The watcher implementation, assertion strength, and cleanup remain unchanged. Static verdict: addresses the verified cause. The PR branch was not checked out or executed; only trusted main plus the locally authored read gate and separate interval control were run. Its own verification claims were not treated as proof. No duplicate fix PR was created.

8. Related issues

The issue's complete comments and GitHub cross-reference metadata were checked. No separate duplicate issue was established by this investigation. The existing linked PR is the actionable work item. The classification is Bug / Medium priority / Low effort / desktop: this is a contained intermittent CI defect, not an observed desktop crash or outage.

9. Verification

The same agent repeated the reproduction, not an independent reviewer. A second clean checkout at 4e45c9bc12fbed430f2e804fb827ac46089fc582 was inspected with git status --porcelain before applying the exact patch above. It received its own frozen install, desktop build, and fresh temporary test directories. No application server or reusable port was needed.

git clone https://github.com/get-bb/bb.git bb-7963-second
cd bb-7963-second
git checkout --detach 4e45c9bc12fbed430f2e804fb827ac46089fc582
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=@bb/desktop
git apply /tmp/reproduce-7963.patch
pnpm exec turbo run test --filter=@bb/desktop -- test/server-moved.test.ts -t 'closes the watcher and polls after a watch error'

Second-run result: the same pending-count diagnostics and exactly-once move assertion failure, with zero calls. This supports REPRODUCED / high confidence. No root-cause correction was required. The second clone shared Git object storage only; it had a separate working directory, installation, generated outputs, and test data. A fresh fetch confirmed no newer main change in the investigated files at the time of checking.

10. Appendix and limits

CheckResult
Frozen install, first and second checkoutBoth exit 0.
Desktop Turbo build, first checkoutExit 0; 65 tasks successful. Nonfatal existing CommonJS/import.meta build warnings.
Unmodified focused baseline, first checkoutExit 0; 1 passed, 50 skipped.
Gated reproduction, first and second checkoutBoth exit 1 on the move assertion, with 2 queued callbacks and 0 delivered moves.
Scheduler-driving control, first checkoutExit 0; all 51 tests in the file pass.
Production files changedNone. Instrumentation remains local; no source branch is pushed.

Read-only evidence gathering included git log for the two desktop files, git show at the base commit, git fetch origin main, issue field/comment/cross-reference reads, and gh pr diff 7964 --repo get-bb/bb. Checks used Turbo; full output stayed outside this public repository. The complete reproducible patch and meaningful verbatim output are inline above, following the reports repository's publication policy. Early instrumentation-loading errors were corrected before either reported reproduction; they are not counted as evidence.

Issue and PR prose was treated only as untrusted claims. No instructions or branch code from that material were executed. This report does not estimate natural flake frequency, establish the precise historical CI interleaving, or claim verification of the linked PR branch. No screenshot is appropriate for this nonvisual test defect.