#7698 · Local Git events redundantly resolve default-branch refs
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
The host daemon performs unnecessary Git subprocess work after local Git metadata changes, even when the default branch was already learned from a shared-ref snapshot. A real temporary repository, with only HEAD detached and all refs unchanged, triggers one fresh default-branch resolution. Git tracing records four subprocesses for the event: the needed local status read plus three redundant default-branch subprocesses. This does not change the displayed default branch; it adds avoidable work per local-event batch. The same agent repeated the regression in a second clean checkout and obtained the same expected failure.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| A local Git event rereads the default branch. | Verified | Real Workspace + WatchManager; one getDefaultBranch call and three matching subprocesses after HEAD-only detachment. |
| The default branch need not be recomputed when only HEAD or index changes. | Verified for the tested HEAD-only change | Complete for-each-ref output is identical before and after detachment; initial and final defaultBranch are main. |
| Shared-ref events already provide the default branch. | Verified in trusted source | The initial/shared-ref path reads SharedGitRefsSnapshot; reportCurrentBranch uses its defaultBranch when supplied. |
| Every resolution always runs rev-parse and for-each-ref, and sometimes symbolic-ref. | Qualified | The measured no-origin-HEAD repository runs rev-parse, symbolic-ref, then for-each-ref. A successful origin/HEAD symbolic lookup can return before any for-each-ref. The exact subprocess mix depends on repository state. |
| The extra cost is 2–4 Git subprocesses. | Three directly measured; range supported by source | ensureGitRepo + origin HEAD lookup + optional one or two fallback branch queries. No cross-platform latency benchmark was run. |
| No issue or PR covers this. | Not true at investigation time | Open PR #7705 explicitly closes #7698. No duplicate fix PR is created. |
3. Environment
- Trusted origin/main:
1320c88e8abdd3f145bc9a5c305eace269fb2f28, checked again after both runs; unchanged. - Linux 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Git 2.39.5; Vitest 4.1.12.
- Two separate checkouts at the same trusted commit, each using a frozen-lockfile install and a full Turbo build. The first full build hit a missing-SDK-output ordering error; retrying unchanged source completed all 74 tasks. The second build completed all 74 tasks.
- No running bb instance, providers, browser, network listener, or production/user data was used. Each test creates and deletes its own temporary Git repository and trace file. Only the HostWatcher event source is replaced with a callback capture; real Workspace, Git commands, and WatchManager processing run unchanged.
4. Minimal reproduction
- Use a clean checkout of the trusted target repository at the recorded commit. Install and build using its frozen lockfile:
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach 1320c88e8abdd3f145bc9a5c305eace269fb2f28 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
If the documented initial missing-SDK-output build error occurs, repeat the same build command without editing source. - Save the complete regression source below as
apps/host-daemon/src/watch-manager.issue-7698.test.ts. - Run the targeted regression:
pnpm exec turbo run test --filter=@bb/host-daemon -- watch-manager.issue-7698
- The test initializes a repository with a main branch and one commit, waits for initial watcher metadata, detaches HEAD without changing any refs, and supplies a single workspace-git-changed event to the production manager. Trace recording begins only after Git setup and the real HEAD change, so setup commands are excluded.
Expected: metadata changes to detached HEAD with default branch main; one local status subprocess; no default-branch calls and no ref-reader subprocesses.
Actual: correct metadata but one default-branch call and three extra subprocesses. Actual stdout and failure excerpt, with only the Turbo prefix removed:
{
"refsUnchanged": true,
"metadata": {
"branchName": null,
"defaultBranch": "main"
},
"defaultBranchReads": 1,
"gitCommands": [
[
"--no-optional-locks",
"status",
"--porcelain=v2",
"--branch",
"-z",
"--untracked-files=normal"
],
[
"rev-parse",
"--is-inside-work-tree",
"--is-bare-repository",
"--git-dir",
"--absolute-git-dir",
"--git-common-dir"
],
[
"symbolic-ref",
"--quiet",
"refs/remotes/origin/HEAD"
],
[
"for-each-ref",
"--format=%(refname)",
"refs/heads/main",
"refs/heads/master"
]
]
}
AssertionError: expected [ [ 'for-each-ref', …(3) ] ] to have a length of +0 but got 1
Test Files 1 failed (1)
Tests 1 failed (1)
Complete regression source
The public report embeds the full test so no private log or external test download is needed. Raw logs remain local, in accordance with the reports repository's publication rules.
import { execFileSync } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { WatchWorkspaceArgs } from "@bb/host-watcher";
import { provisionWorkspace } from "@bb/host-workspace";
import { expect, it, vi } from "vitest";
import { WatchManager } from "./watch-manager.js";
it("reuses known default refs for a HEAD-only change without spawning ref readers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "bb-7698-git-"));
const tracePath = path.join(root, "git-trace.jsonl");
const previousTrace = process.env.GIT_TRACE2_EVENT;
let watch: WatchWorkspaceArgs | undefined;
let manager: WatchManager | undefined;
const git = (...args: string[]) =>
execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
try {
git("init", "--quiet", "--initial-branch=main");
await writeFile(path.join(root, "sample.txt"), "initial\n");
git("add", "sample.txt");
git(
"-c",
"user.name=Reproduction",
"-c",
"user.email=repro@invalid.test",
"-c",
"core.hooksPath=/dev/null",
"-c",
"commit.gpgSign=false",
"commit",
"--quiet",
"-m",
"initial",
);
const refsBefore = git(
"for-each-ref",
"--format=%(refname) %(objectname) %(symref)",
);
const workspace = await provisionWorkspace({ path: root });
const getDefaultBranch = vi.spyOn(workspace, "getDefaultBranch");
const onWorkspaceMetadataChanged = vi.fn();
const onWorkspaceStatusWatchError = vi.fn();
manager = new WatchManager({
hostWatcher: {
watchWorkspace(args) {
watch = args;
return () => undefined;
},
watchThreadStorage: () => () => undefined,
},
provisionWorkspace: async () => workspace,
onWorkspaceMetadataChanged,
onWorkspaceStatusWatchError,
});
await manager.replaceWatchSet({
generation: 1,
workspaceTargets: [
{
environmentId: "repro-7698",
workspaceContext: { workspacePath: root },
mergeBaseBranch: null,
},
],
threadStorageTargets: [],
});
expect(watch).toBeDefined();
watch!.onReady?.();
await vi.waitFor(() =>
expect(onWorkspaceMetadataChanged).toHaveBeenCalledTimes(1),
);
expect(
onWorkspaceMetadataChanged.mock.calls[0]?.[0].workspace,
).toMatchObject({
branchName: "main",
defaultBranch: "main",
});
getDefaultBranch.mockClear();
git("checkout", "--quiet", "--detach", "HEAD");
const refsAfter = git(
"for-each-ref",
"--format=%(refname) %(objectname) %(symref)",
);
expect(refsAfter).toBe(refsBefore);
process.env.GIT_TRACE2_EVENT = tracePath;
watch!.onChange({
kind: "workspace-status-changed",
environmentId: "repro-7698",
changeKinds: ["workspace-git-changed"],
changedPaths: [path.join(root, ".git", "HEAD")],
});
await vi.waitFor(() =>
expect(onWorkspaceMetadataChanged).toHaveBeenCalledTimes(2),
);
expect(
onWorkspaceMetadataChanged.mock.calls[1]?.[0].workspace,
).toMatchObject({
branchName: null,
defaultBranch: "main",
});
expect(onWorkspaceStatusWatchError).not.toHaveBeenCalled();
const commands = (await readFile(tracePath, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line) as { event: string; argv?: string[] })
.filter((event) => event.event === "start")
.map((event) => event.argv!.slice(1));
console.log(
JSON.stringify(
{
refsUnchanged: refsAfter === refsBefore,
metadata: { branchName: null, defaultBranch: "main" },
defaultBranchReads: getDefaultBranch.mock.calls.length,
gitCommands: commands,
},
null,
2,
),
);
expect(commands.some((args) => args.includes("status"))).toBe(true);
expect(commands.filter((args) => args[0] === "for-each-ref")).toHaveLength(
0,
);
expect(getDefaultBranch).not.toHaveBeenCalled();
} finally {
if (previousTrace === undefined) delete process.env.GIT_TRACE2_EVENT;
else process.env.GIT_TRACE2_EVENT = previousTrace;
await manager?.shutdown();
vi.restoreAllMocks();
await rm(root, { recursive: true, force: true });
}
});
5. Root cause
Initial watcher processing resolves local state and shared refs together. However, later local-only events do not supply a shared snapshot. reportCurrentBranch treats an absent per-event snapshot as a reason to call getDefaultBranch again, even though the watch already knows the default branch:
sharedRefs === undefined ? entry.workspace.getDefaultBranch() : sharedRefs.defaultBranch
Workspace.getDefaultBranch delegates to readDefaultBranch. readDefaultBranch and readRepoDefaultBranch validate the repository and resolve origin/HEAD or local fallback refs. Origin HEAD and preferred-local-branch readers explain the measured symbolic-ref and for-each-ref subprocesses. The additional calls occur before metadata deduplication, so unchanged metadata does not prevent them.
Shared-ref snapshots already derive the default branch from refs. Watcher classification distinguishes HEAD/index metadata from shared ref paths (packed-refs, refs/heads, refs/remotes). The test verifies unchanged refs rather than pretending HEAD movement can change the ref-derived default branch.
One wording correction matters: a local event does not necessarily spawn a standalone current-branch query. Local-state snapshots obtain branch metadata from git status. The demonstrated waste is the separate default-branch resolution, not the necessary status read.
6. Proposed fix
Remember the last resolved default-branch value in the existing workspace-watch state and reuse it for local-only events. Refresh it from shared-ref snapshots, retaining a lookup fallback only until a value has been resolved. Keep null (resolved but absent) distinct from undefined (not resolved yet); do not reuse only the displayed fallback, which can be the current branch. Preserve detached-HEAD handling, metadata deduplication, and invalidation when workspace provisioning changes.
Use this regression as the real-Git resource guard, and preserve coverage for shared-ref changes, no-default-branch repositories, and detached HEAD. No production fix was attempted here because an open linked PR already owns the change.
7. Linked PR review
PR #7705 — static review only
GitHub metadata reports the PR OPEN and its closing-issue references include #7698. The inspected head is cf5d49272816470af008458f07d584abd4bbf286. Its diff adds a separate lastResolvedDefaultBranch field in watch state, consumes shared snapshots, and reuses the resolved value on local-only updates. It also changes an existing test to supply a shared-ref event for default-branch changes.
Assessment: the diff targets the verified root cause and preserves the important distinction between a null resolved value and the displayed branch fallback. No blocking finding is established by this static inspection. Limit: no PR branch was checked out or executed; the regression and baseline tests in this report run only the trusted main commit, not the PR. This is not a runtime approval of the proposed patch.
8. Related issues and provenance
PR #6018 is the earlier watcher-reporting change referenced by the report; its metadata was read only. No other matching issue was returned by the targeted default-branch search. Issue content and linked PR material were treated as untrusted claims; no issue-supplied code, scripts, instructions, or PR code were run.
9. Verification — second clean run
The same agent created a new detached temporary worktree at 1320c88e8abdd3f145bc9a5c305eace269fb2f28, verified it was clean after the frozen install and full build, then copied only the agent-authored regression into it. A new temporary Git repository and trace file were created by the test; no ports or instance data directories were needed. The command was again:
pnpm exec turbo run test --filter=@bb/host-daemon -- watch-manager.issue-7698
The regression executed (not a cached test result), exited 1 at the same expected zero-ref-read assertion, and recorded identical four-command trace data. Second-run output:
{
"refsUnchanged": true,
"metadata": {
"branchName": null,
"defaultBranch": "main"
},
"defaultBranchReads": 1,
"gitCommands": [
[
"--no-optional-locks",
"status",
"--porcelain=v2",
"--branch",
"-z",
"--untracked-files=normal"
],
[
"rev-parse",
"--is-inside-work-tree",
"--is-bare-repository",
"--git-dir",
"--absolute-git-dir",
"--git-common-dir"
],
[
"symbolic-ref",
"--quiet",
"refs/remotes/origin/HEAD"
],
[
"for-each-ref",
"--format=%(refname)",
"refs/heads/main",
"refs/heads/master"
]
]
}
AssertionError: expected [ [ 'for-each-ref', …(3) ] ] to have a length of +0 but got 1
Test Files 1 failed (1)
Tests 1 failed (1)
Report correction: the exact origin/HEAD/for-each-ref subprocess mix is repository-dependent, rather than the universal order suggested by the issue. The confirmed bug and measured three-spawn overhead are unchanged. This is a repeated check by the same agent, not independent verification.
10. Appendix — baseline and limits
pnpm exec turbo run test --filter=@bb/host-daemon -- watch-manager.test.ts Test Files 1 passed (1) Tests 24 passed (24)
The existing watcher suite passes while the new resource regression fails; the existing coverage does not enforce absence of this repeated ref lookup. No after-fix pass is claimed. The host's native filesystem event delivery was not retested, index-only and operating-system timing variants were not separately benchmarked, and no GUI screenshots apply to this process-count defect.
GitHub reads used repository/issue/PR metadata and the linked PR diff only. Classification and the final reproduction label use the supplied SlopCop identity wrapper. No duplicate fix branch or PR is pushed.