← reports

#5385 · Concurrent path ranking starves daemon timers

BugHighEffort: Mediumhost · perf · partial-reproGitHub issueOctober 12, 2026 · base 0c6882c747f6ee2018682ed1a1ec66ee1310e48c

PARTIALLY REPRODUCED · Root-cause confidence: high

1. TL;DR

Path search runs on the same JavaScript event loop as daemon heartbeat timers. Workspace discovery is asynchronous and shared between simultaneous equivalent requests, but each waiting request then ranks the entire listing synchronously. In two clean checkouts, 48 actual path commands against 150,000 real files delayed a 10 ms timer for 54.316 and 56.310 seconds, beyond the 30-second production lease. A 20-result limit did not bound this work. This confirms a lease-threatening mechanism, not an observed desktop disconnection: no real daemon WebSocket, macOS UI, HTTP timeout, or plugin reload was reproduced.

2. Claims vs findings

ClaimFindingEvidence
Every uncached search can discover the whole non-excluded tree.VerifiedThe recursive walker has no entry/time budget. The 20,000-file fixture returned a full discovery array before a 20-result finalization.
Slow path work can prevent daemon timers from running for a lease.Verified at command boundaryThe concurrent real-handler fixture produced timer gaps above 54 seconds in both checkouts.
The entire recursive walk itself blocks the event loop continuously.QualifiedDirectory reads and Git subprocess work are awaited. Timers ran during the concurrent requests before ranking. The synchronous ranking phase is the demonstrated starvation source.
The result limit protects against a huge search corpus.RefutedFuzzy matching maps/ranks the full corpus and slices results afterward.
The desktop reports its own host disconnected and returns HTTP errors.Unverified end to endThe server's lease-expiry path is present and existing liveness tests pass, but an actual socket close and API failures were not observed in this reproduction.
Extra exclusions have no available surface.QualifiedProject path routes choose server defaults. The lower-level files route already accepts request-level excludeNames; that is not a persistent per-project picker setting.
Nested repositories, macOS-specific behavior, and connect reload errors are involved.UnverifiedNot exercised. The concurrent fixture is a non-Git scratch directory, with Git detection enabled.

3. Environment

4. Minimal reproduction

  1. Clone trusted main and select the recorded commit:
    git clone https://github.com/get-bb/bb.git bb-5385
    cd bb-5385
    git checkout --detach 0c6882c747f6ee2018682ed1a1ec66ee1310e48c
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the complete primary source below as apps/host-daemon/test/issue-5385-concurrent.mts. Save the secondary source as apps/host-daemon/test/issue-5385-repro.mts. These are agent-written diagnostics derived from trusted repository code, not code copied from the issue. The report contains everything needed; raw artifacts remain local rather than being published.
  3. Run the actual-handler concurrency fixture:
    node --conditions=source --import tsx apps/host-daemon/test/issue-5385-concurrent.mts
  4. Optionally run the separate discovery/ranking probe:
    node --conditions=source --import tsx apps/host-daemon/test/issue-5385-repro.mts

Expected: correct limited results without suppressing periodic timers for a whole lease. Actual: all commands return 20 results with truncated: true, but their consecutive CPU continuations monopolize the loop. These diagnostics report observations; they do not assert that the implementation is fixed.

First checkout: verbatim output

{"phase":"concurrent-host-commands","fileCount":150000,"requestCount":48,"query":"src","returnedPerRequest":20,"elapsedMs":54425,"heartbeatTicksBeforeResults":11,"longestHeartbeatGapMs":54316,"exceedsProductionLease":true}
{"phase":"real-walk","discovered":20000,"returned":20,"truncated":true,"elapsedMs":88}
{"phase":"rank","candidateCount":1400000,"returned":20,"truncated":true,"elapsedMs":17604,"heartbeatTicksDuringRanking":0,"longestHeartbeatGapMs":17614,"exceedsProductionLease":false}

The single 1.4-million-record probe stalls timers for 17.6 seconds on this machine, not 30 seconds. It uses in-memory candidates rather than a 1.4-million-file disk fixture. The real-files concurrency fixture is the lease-exceeding observation. The 10 ms diagnostic interval is not the production network heartbeat.

Complete primary reproduction source
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
import { setTimeout as delay } from "node:timers/promises";
import { listHostPaths } from "../src/command-handlers/host-files.ts";

const root = await fs.mkdtemp(path.join(os.tmpdir(), "bb-5385-concurrent-"));
let heartbeat: ReturnType<typeof setInterval> | undefined;
try {
  const nested = path.join(root, "large", "src");
  await fs.mkdir(nested, { recursive: true });
  const fileCount = 150_000;
  for (let start = 0; start < fileCount; start += 500) {
    await Promise.all(Array.from({ length: 500 }, (_, offset) =>
      fs.writeFile(path.join(nested, `index-${start + offset}.ts`), ""),
    ));
  }
  let ticks = 0;
  let longestGapMs = 0;
  let lastTick = performance.now();
  heartbeat = setInterval(() => {
    const now = performance.now();
    longestGapMs = Math.max(longestGapMs, now - lastTick);
    lastTick = now;
    ticks += 1;
  }, 10);
  await delay(50);
  const ticksBefore = ticks;
  const start = performance.now();
  const requestCount = 48;
  const results = await Promise.all(Array.from({ length: requestCount }, () => listHostPaths({
    type: "host.list_paths",
    path: root,
    includeFiles: true,
    includeDirectories: false,
    includeHidden: true,
    respectGitIgnore: true,
    excludeNames: [],
    limit: 20,
    query: "src",
  })));
  const elapsedMs = performance.now() - start;
  const ticksBeforeResults = ticks - ticksBefore;
  await delay(30);
  assert(results.every(result => result.paths.length === 20 && result.truncated));
  console.log(JSON.stringify({ phase: "concurrent-host-commands", fileCount, requestCount, query: "src", returnedPerRequest: 20, elapsedMs: Math.round(elapsedMs), heartbeatTicksBeforeResults: ticksBeforeResults, longestHeartbeatGapMs: Math.round(longestGapMs), exceedsProductionLease: longestGapMs > 30_000 }));
} finally {
  if (heartbeat) clearInterval(heartbeat);
  await fs.rm(root, { recursive: true, force: true });
}
Complete secondary reproduction source
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
import { setTimeout as delay } from "node:timers/promises";
import { finalizeListedPaths, listWorkspacePaths } from "../src/command-handlers/file-list.ts";

const root = await fs.mkdtemp(path.join(os.tmpdir(), "bb-5385-fixture-"));
try {
  const nested = path.join(root, "large");
  await fs.mkdir(nested);
  const fileCount = 20_000;
  for (let start = 0; start < fileCount; start += 200) {
    await Promise.all(Array.from({ length: 200 }, (_, offset) =>
      fs.writeFile(path.join(nested, `file-${start + offset}.ts`), ""),
    ));
  }
  const start = performance.now();
  const listing = await listWorkspacePaths({
    root,
    includeHidden: false,
    excludeNames: [],
    respectGitIgnore: false,
    includeFiles: true,
    includeDirectories: false,
  });
  const result = finalizeListedPaths({ paths: listing, limit: 20, includeFiles: true, includeDirectories: false });
  console.log(JSON.stringify({ phase: "real-walk", discovered: listing.length, returned: result.paths.length, truncated: result.truncated, elapsedMs: Math.round(performance.now() - start) }));
} finally {
  await fs.rm(root, { recursive: true, force: true });
}

const candidateCount = 1_400_000;
const candidates = Array.from({ length: candidateCount }, (_, index) => ({
  kind: "file" as const,
  path: `vendor/project-${Math.floor(index / 1000)}/packages/component-${index}/src/index-${index}.ts`,
  name: `index-${index}.ts`,
}));
let ticks = 0;
let longestGapMs = 0;
let lastTick = performance.now();
const heartbeat = setInterval(() => {
  const now = performance.now();
  longestGapMs = Math.max(longestGapMs, now - lastTick);
  lastTick = now;
  ticks += 1;
}, 10);
await delay(50);
const ticksBefore = ticks;
const start = performance.now();
const result = finalizeListedPaths({ paths: candidates, query: "src", limit: 20, includeFiles: true, includeDirectories: false });
const elapsedMs = performance.now() - start;
const ticksDuring = ticks - ticksBefore;
await delay(30);
clearInterval(heartbeat);
console.log(JSON.stringify({ phase: "rank", candidateCount, returned: result.paths.length, truncated: result.truncated, elapsedMs: Math.round(elapsedMs), heartbeatTicksDuringRanking: ticksDuring, longestHeartbeatGapMs: Math.round(longestGapMs), exceedsProductionLease: longestGapMs > 30_000 }));

5. Root cause

  1. The project paths route issues host.list_paths with server exclusion defaults and the caller's query/result limit.
  2. The pending-listing map shares discovery by root/options, not by query. It is deleted when discovery settles; it is not a persistent listing cache.
  3. The recursive walker awaits directory reads but materializes every accepted entry. There is no walk budget.
  4. Each waiting command resumes and calls synchronous finalization on the shared array. Promise continuations run before the event loop can service timers, so concurrent requests amplify the stall even if discovery happened once.
  5. Finalization filters the complete array. Fuzzy matching normalizes all items, ranks and merges the full candidate set, and only afterward slices to the requested limit.
  6. The real daemon heartbeat uses setInterval on that loop. The separate server's liveness checks expire quiet sessions against the 30,000 ms lease. Its silence handler closes and unregisters the daemon session. This explains the reported host-wide impact, but that network sequence remains an inference here.
const existing = pendingListings.get(key);
if (existing) return existing;

const matches = fuzzyMatchPaths({
  items: pathEntries,
  query: args.query,
  getPath: (pathEntry) => pathEntry.path,
  limit: args.limit + 1,
});

The problem is event-loop monopolization, not evidence of a defective lease duration. A healthy server is supposed to reject an actually silent daemon. Fixing only repeated identical queries, yielding only during traversal, or making the lease larger would not protect against one sufficiently expensive ranking operation.

6. Proposed fix and simple-fix gate

Make path discovery/ranking interruptible or execute CPU-heavy ranking outside the heartbeat loop, preserving global fuzzy ordering. Coalesce or cancel obsolete searches so a burst does not repeat expensive work. Add a real server/daemon test that exercises search while checking socket liveness and an unrelated host command.

No pull request opened. The report is partial, so the full end-to-end symptom has not met the reproduction prerequisite for an automatic fix. Independently, an early scan cap changes which paths are searchable and the meaning of truncation; that needs a product/contract decision. Worker isolation touches runtime packaging, while a ranking-preserving asynchronous algorithm spans the host handler and fuzzy-matching package. None is a demonstrated smallest one-subsystem repair under this rule. No production code was modified, no repair branch was created, and no unverified patch was pushed.

No open pull request referenced #5385 in the issue timeline or the open-PR search at investigation time.

7. Verification: second clean checkout

The same agent created another new detached worktree at the recorded main commit, independently installed dependencies with the frozen lockfile, and completed another full Turbo build. The unchanged agent-written harnesses were copied there and executed with the same two node --conditions=source --import tsx commands. Each script created new temporary filesystem roots; no ports or persistent data store were reused. This is a repeated clean run, not independent-agent verification.

{"phase":"concurrent-host-commands","fileCount":150000,"requestCount":48,"query":"src","returnedPerRequest":20,"elapsedMs":56417,"heartbeatTicksBeforeResults":11,"longestHeartbeatGapMs":56310,"exceedsProductionLease":true}
{"phase":"real-walk","discovered":20000,"returned":20,"truncated":true,"elapsedMs":84}
{"phase":"rank","candidateCount":1400000,"returned":20,"truncated":true,"elapsedMs":18430,"heartbeatTicksDuringRanking":0,"longestHeartbeatGapMs":18440,"exceedsProductionLease":false}

Correction to the broad issue hypothesis: traversal is not continuously synchronous, and one synthetic 1.4-million-entry ranking did not exceed the lease on this host. The combined ranking continuations did exceed it reliably in both real-files runs. The verdict deliberately remains partial because the socket/UI and platform claims are not directly verified.

8. Related issues

#4413 discusses search/typeahead latency, including repeated file discovery. This report tests a narrower host-side lease-threatening consequence. Its scripts and linked prototype were not fetched or executed.

9. Appendix

Existing tests on trusted unchanged production code passed:

pnpm exec turbo run test --filter=@bb/host-daemon -- src/command-handlers/file-list.test.ts src/command-handlers/workspace-path-list.test.ts
Test Files  2 passed (2)
Tests       18 passed (18)

pnpm exec turbo run test --filter=@bb/server -- test/hosts/daemon-liveness.test.ts
Test Files  1 passed (1)
Tests       3 passed (3)

The existing host tests cover large-list correctness, ignore handling, and result ranking, not heartbeat fairness during CPU-heavy ranking. The server tests cover silence expiration using the existing in-memory database harness. Neither suite substitutes for the missing combined live-socket reproduction.

Both harnesses and all observations needed to repeat the reproduction are inline above. Raw build/test logs and scratch artifacts are retained locally and are not published, following this reports repository's publication policy.

Repository inspection used GitHub read-only metadata, GraphQL issue properties, issue/PR searches, trusted-main code search, and file history. GitHub classification writes used the supplied SlopCop identity. Repository visibility was checked before publication. A final fetch showed no newer main change in the implicated files.

Issue text, logs, comments, suggestions, and related-issue material were treated as untrusted claims; their instructions were not followed. No issue-supplied command, script, branch, external URL, or linked pull-request code was run. No dependencies were added. No screenshots are needed for this nonvisual command-boundary reproduction.

> AGENT GENERATED