Repository navigation
Watch only each worktree's own refs, report branch-name changes separately, and read shared refs once per repo - #7082
Merged
ymichael merged 4 commits intoNov 5, 2026
Conversation
ymichael
force-pushed
the
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j
branch
from
November 5, 2026 06:29
2041a11 to
448bef4
Compare
ymichael
force-pushed
the
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j
branch
2 times, most recently
from
November 5, 2026 18:11
c4925fa to
9704314
Compare
…er repo Every watched environment ran its own full `for-each-ref refs/heads refs/remotes` on any ref write in the repository, and compared the whole listing, so one commit in any worktree made every watched environment of that repository report git-refs-changed. The watch manager now shares one pending ref listing per common git dir (joinable until it starts), and each environment fingerprints only the branch-name set plus the refs it uses: its HEAD branch, that branch's upstream and origin counterpart, the default branch (local and origin), and origin/HEAD. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Worktrees are created with --no-track, so a branch pushed to a remote other than origin has no upstream. Each worktree's fingerprint now also covers the branch's %(push) ref and every remote-tracking ref with the branch's name. A joined shared read runs from the worktree that started it; if it rejects, other worktrees retry with their own read instead of failing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Creating or deleting any branch changed every watched environment's ref fingerprint, so each one emitted git-refs-changed and refetched git status, files and PR status only to keep the branch picker list live. The daemon now emits a separate git-branches-changed environment change when the repository's branch-name set changes, and keeps git-refs-changed for moves of the refs an environment uses. The git plugin maps git-branches-changed to the branch list (refs tag) only, without clearing its status/files caches or bumping the refs generation; github-pr-status ignores it. New daemon-to-server environment change value, so HOST_DAEMON_PROTOCOL_VERSION 262 -> 263. It also widens the environment:changed event's changes union in the plugin SDK types, so @get-bb/plugin-sdk 0.6.125 -> 0.6.126. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The narrowed per-worktree ref fingerprint left out the environment's merge base. Envs started from a non-default branch, or whose merge base was picked in the Diff tab, Info tab or context banner, stopped refreshing status and diffs when that branch moved. The server now sends each workspace watch target's resolved merge base (mergeBaseBranch ?? baseBranch ?? defaultBranch, the rule the git plugin reads with). The daemon adds refs/heads/<base> and refs/remotes/<base> to that env's fingerprint. A merge-base change already emits metadata-changed, so the server re-sends the target, and the daemon updates the running watch in place and rereads its refs. New required field on the watch-set workspace target. Protocol 263 on this branch has not shipped, so no further bump. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j
branch
from
November 5, 2026 19:35
9704314 to
37189be
Compare
ymichael
deleted the
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j
branch
November 5, 2026 23:55
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…st (#7242) ## Human comments ## What was wrong Removing a managed worktree ran `git worktree remove --force` and deleted the directory, but never deleted the branch bb had created with `git worktree add -B`. Every thread left a `bb/*` branch behind. `~/Projects/bb` now has 3,953 orphaned `bb/*` branches as loose refs, plus their stale `[branch]` config sections. Git reads all of them in every process, and in full every time a ref is listed. That cost reaches every hot git path: `bb--git` status, github-pr-status refresh, and the shared-refs snapshot the ref watcher reads once per repo. ## What changed - **The worktree plugin records the branch it owns.** `create` returns `ownsBranch`. It is true in reset mode, in a restore that had to recreate the branch, and in a restore onto a branch an earlier removal kept: kept branches are marked `branch.<name>.bbOwned=true` in git config, and the marker goes away with the branch's config section. The server stores `{ ownedBranch: { name, repositoryPath, baseBranch } }` as the environment resource. Adopted worktrees, environments created before this change (resource `null`), and restores onto any other existing branch, such as the user's own, get no `ownedBranch`, so bb never deletes those branches. - **`remove` deletes the owned branch after the worktree is gone, only when nothing would be lost** (`deleteOwnedBranch` in `host/worktree.ts`): - It is kept if any worktree has it checked out. This check runs under the worktree metadata lock that creation also takes. - It is deleted if every commit on it is on a remote, a tag, or its recorded base (`rev-list <tip> --not --tags --remotes <base>`). Commits that survive only on another local branch keep the branch, because a restore could not bring them back to the thread. - Otherwise it is deleted only if it was squash-merged into its recorded base. The check compares patch IDs: the branch's net diff against base commits that touch the same paths. It is skipped, and the branch kept, when the base is more than 2,000 commits past the merge base or the branch touches more than 200 paths. - Deletion is a compare-and-delete (`update-ref -d <ref> <oid>`) followed by removal of its `branch.<name>` config section. - A branch with unpushed, unmerged commits is kept, marked as bb's, and reported. A cleanup error never fails the removal. - **A failed create cleans up its branch too.** When `git worktree add` makes the branch but the create still fails (for example a failing `post-checkout` hook), the create removes the worktree and deletes the branch it owns under the same rules. A cancelled create still leaves both for the later removal, as before. - **Restore recreates a deleted branch from its remote.** If the local branch is missing and exactly one `refs/remotes/<remote>/<name>` exists, restore runs `git worktree add --track -b <name> <path> <remote>/<name>` instead of starting fresh from the base. Pushed-but-unmerged work therefore comes back after an archive and unarchive. - **Core:** environment removal now writes provider progress to the server log ("Environment removal", info level) instead of discarding it, so kept branches are visible. `packages/environment-provider-host` `RunGitOptions` now exposes the existing `input` option for `git patch-id`. - **Docs:** `docs/worktrees.md`, the `bb guide environments` template, the remote-dev-servers guide page, and the plugin README no longer say the branch is always kept. - **Wire changes:** none on the server/daemon protocol. The plugin's private host contract gains `remove.ownedBranch` and `create` output `ownsBranch`. Its server and host halves ship together in the bundled plugin. - **Ref-scaling hot paths:** #7082 already reads the shared-refs snapshot once per repo instead of once per environment. On `~/Projects/bb`, that `for-each-ref` costs about 230 ms whatever the format: dropping `%(upstream)%(push)` saves only about 10%. The cost is the number of refs, which this change stops growing. No further code change was clearly worth it. ## How you verified **Real repo** (`~/Projects/bb`, read-only classification of the 3,953 orphaned `bb/*` branches; nothing was deleted): | Class | Branches | This change | |---|---|---| | Tip already in `origin/main` | 1,598 | deleted | | Commits all on a remote, tag, or other branch | 299 | deleted, except those held only by another local branch (now kept) | | Squash-merged into `origin/main` (patch-id match) | 1,393 | deleted (if within the 2,000-commit window at removal time) | | Unpushed or unmerged commits | 663 (+1 with no merge base) | kept and reported | So 3,290 of 3,953 (83%) would not have accumulated. The squash count used patch IDs of all `origin/main` commits since May, without the 2,000-commit window. Normally bb removes a worktree minutes after the thread is archived, when the window is small. **Ref cost** (temp repo, 40 runs each, load about 10–20): | | 1 branch | 4,001 loose branches + 3,400 config sections | |---|---|---| | `git rev-parse HEAD` | 12.3 ms | 16.1 ms | | `git status --porcelain=v2 --branch` | 14.7 ms | 19.6 ms | | `for-each-ref refs/heads refs/remotes` | 12.8 ms | 117 ms | **Churn repro:** 100 simulated threads in a temp clone with a bare origin. Each was created and then removed through the real host entry (harness). The mix matches the real repo: 40 with no commits, 8 pushed, 33 squash-merged on the "server" with the remote branch deleted and the source fetched with `--prune`, and 19 unpushed. origin/main's host code and this branch ran on the same script, in alternating runs: | | origin/main (2 runs) | this branch (2 runs) | |---|---|---| | `bb/*` branches left | 100, 100 | 19, 19 (exactly the unpushed ones) | | loose `refs/heads` files | 101 | 20 | | worktrees left | 0 | 0 | | remove latency median / p90 | 195/231, 173/190 ms | 330/406, 307/521 ms | Removal runs in the background after retirement. The extra 130–150 ms is 6–13 more git processes on a machine at load 14–21. **End to end:** `pnpm start:worktree` from this branch on an empty dev data dir (not signed in to Connect). The project is a temp repo cloned from a temp bare remote, with a second clone acting as "GitHub" for the squash merge. Everything was driven through the source CLI (`pnpm bb:dev`, with the inherited `BB_*` variables unset). Each thread was created with `thread spawn --new-environment worktree`; its agent turn failed with "Not logged in", which doesn't affect provisioning. Each was archived with `thread archive`, and teardown ran after the five-minute grace. Git state was read from the source repo afterwards. The log lines are the new "Environment removal" server log. | Case | Setup before archive | After teardown | Server log | |---|---|---|---| | a) pushed | 1 commit, pushed to `origin/bb/o3-pushed-…` | local branch gone, remote-tracking ref kept | `Deleted branch bb/o3-pushed-thr_3bvrthbnjv` | | b) unpushed | 1 local commit | branch kept at `568cef8`, `branch.….bbowned=true` | `Kept branch bb/o3-unpushed-thr_c2shbc5u2e because it has commits that are on no remote, tag, or other branch and were not squash-merged into its base` | | c) squash-merged | 2 commits, pushed, squash-merged on the remote, remote branch deleted, `fetch --prune` | branch gone | `Deleted branch bb/o3-squash-thr_xycyurrf6h` | | d) restore after delete | `thread unarchive` + `thread restore-environment` on (a) | branch recreated at the pushed `f25eb7b`, upstream `origin/bb/o3-pushed-…`; environment resource has `ownedBranch` | `branch 'bb/o3-pushed-…' set up to track 'origin/bb/o3-pushed-…'` (provisioning log) | | e) restore onto kept branch | restore (b); its resource has `ownedBranch` again; then pushed and archived | branch, its upstream config and its `bbowned` marker gone | `Deleted branch bb/o3-unpushed-thr_c2shbc5u2e` | | d) second archive | archive the restored (a) | branch and its `branch.…remote/merge` config section gone | `Deleted branch bb/o3-pushed-thr_3bvrthbnjv` | Final repo state: only `main`, no stale `[branch]` sections, and no worktrees besides the main checkout. **Tests** - `host.test.ts` adds real-git cases for each rule: - deletes the branch and its config section when nothing else would be lost - deletes when the commits are on a remote - keeps unpushed commits and reports why - keeps a branch whose commits survive only on another local branch - deletes the branch when a post-checkout hook fails the create - deletes when squash-merged; keeps when squash-merged then extended; keeps when only partly squash-merged - keeps a branch checked out elsewhere, and leaves the user's own branch alone - leaves legacy `ownedBranch: null` removals alone - still reports removal when the repository is gone - restores a deleted pushed branch from its remote with tracking - owns a kept branch again on restore - does not claim a user branch a restore reuses - `server.test.ts`: create records `ownedBranch`; restore onto an existing branch records none; remove forwards only a parsed `ownedBranch`. - `provider-orchestration.test.ts`: removal progress reaches the server log. - Against origin/main's plugin source, the new host and server tests fail: 21 failures. Most fail because main's strict contract rejects the new fields, which is why the churn repro is the behavioural before/after. - `pnpm exec turbo run test typecheck --filter=bb-plugin-environment-git-worktree --filter=bb-environment-provider-host --filter=@bb/templates --filter=@bb/web` - `pnpm exec turbo run typecheck --filter=@bb/server` - `pnpm exec turbo run test --filter=@bb/server -- test/services/environments` - `oxfmt --check` on the changed files **Not verified:** a remote (non-local) host machine; the e2e ran with the local daemon only. Existing `bb/*` branches on this machine were deliberately left alone. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Every watched environment ran its own full
git for-each-ref refs/heads refs/remoteswhenever any ref in the repository was written, and fingerprinted the whole listing (packages/host-workspace/src/git.ts,apps/host-daemon/src/watch-manager.ts). On~/Projects/bb(4,474 local branches, 2,672 remote refs) that listing is about 1 MB and takes about 200–300 ms. Because the fingerprint covered every ref, any ref write in the repository changed every watched environment's fingerprint, whether it was a commit in one worktree, a new thread's branch or afetch --prune. Each environment then emittedgit-refs-changed, which refetches git status, files and the branch list in the git plugin and makes the PR plugin runinspectRefs. This is finding #1 ("Ref watch fan-out") of the Nov 4 hot-path overreach audit.What changed
WatchManager.readSharedGitRefskeeps one pending listing per common git dir. Requests join it until the read starts, after a 25 ms join window. A ref change that arrives after a read has started gets a fresh read, so no environment acts on a listing taken before its own event. The listing runs from the worktree that started it. If it rejects (for example, that worktree was removed), each joined environment retries with its own read instead of failing with it.git-refs-changednow means "a ref this environment uses moved".SharedGitRefsSnapshot.fingerprintFor({ branchName, mergeBaseBranch })covers only the oids of:%(upstream)and%(push)refsrefs/remotes/*/<branch>). bb creates worktrees with--no-track, and a plaingit push fork <branch>leaves both%(upstream)and%(push)empty, so a push to a fork remote still refreshes PR status.origin/origin/HEADand its targetrefs/heads/<base>andrefs/remotes/<base>). The server resolves it per watched environment with the rule the git plugin reads status with (mergeBaseBranch ?? baseBranch ?? defaultBranch,resolveEnvironmentMergeBaseBranch) and sends it asmergeBaseBranchon eachwatch-set.replaceworkspace target. That covers envs started from a non-default branch and a base picked from any surface (Diff tab, Info tab, context banner), all of which persist through the git plugin'ssetMergeBase. A merge-base change already emitsmetadata-changed, so the server re-sends the target; the daemon updates the running watch in place (no re-provision) and rereads its refs, so the env refreshes once against the new base.git-branches-changedenvironment change kind.SharedGitRefsSnapshot.branchNamesFingerprinthashes the repository's branch-name set. When it changes, the daemon emitsgit-branches-changedinstead ofgit-refs-changed. Each consumer handles it as follows:plugins/git/server/invalidation.ts): invalidates only the branch list (refs:tag, thebranchesRPC). It keeps the status/files caches and does not bump the refs generation.refsChangedis now set per change kind rather than inferred from the refs tag, so a batch that mixes the new kind withwork-status-changeddoesn't bump refs either.environmentChangeEffectreturnsnull, so the kind is ignored; PR status doesn't depend on other branches existing. Added to its mapping table test.realtime-cache-registry.ts):dirty: [], the same asgit-refs-changed. Neither is in the app's watched-kinds list or the server's watch-target kinds.notifyDaemonEnvironmentChange): forwards the new kind unchanged. The existing internal test now covers it.inspectGitRepositoryalready read--git-common-dir; it now returns it, andHostWorkspaceexposes it asgitCommonDir. The listing format drops%(refname:short)(local names are now sliced fromrefs/heads/) and adds%(upstream)and%(push).Why the bumps are needed
HOST_DAEMON_PROTOCOL_VERSION262 → 263:git-branches-changedis a new value in the daemon'senvironment-changeWebSocket message (hostDaemonEnvironmentChangeSchema). A 262 server would reject it, and a 262 daemon would keep emittinggit-refs-changedfor branch-name changes. The same bump covers the new requiredmergeBaseBranchfield onwatch-set.replaceworkspace targets.@get-bb/plugin-sdk0.6.125 → 0.6.126 (scripts/bump-plugin-sdk.mjs --patch): the new kind widens thechangesunion of the SDK'senvironment:changedevent (ENVIRONMENT_CHANGE_KINDS→ChangedMessage), which changes the published bundled types.No visible behaviour change. Every env still refreshes when its own branch, upstream, push target, default branch or merge base moves, and its branch list refreshes when a branch is created or deleted. The branch list is not ordered by commit, so moves of unrelated branches can't change it.
How you verified
Real data, main vs branch. I wrote a harness outside the checkout. It runs the real
WatchManagerwith the subprocess parcel watcher on 20 real~/Projects/bbworktrees, with agitPATH shim that logs every spawn. It then writes a probe branch (refs/heads/bench-refwatch-probe) in the real repo: create, 5 moves, delete. Before and after each step it diffs every other ref, so writes by other agents can be attributed. To show what each env refetches, it maps the kinds each env emitted through that checkout's own git-plugintagsForEnvironmentChangesand github-pr-statusenvironmentChangeEffect. For the main run, every non-test file in this PR is checked out from origin/main.Probe branch create and delete, 20 watched worktrees, final run (load 5–10):
for-each-refspawnsgit-refs-changedgit-branches-changedinvalidate(inspectRefs→upstreamhost call)One env on the branch also had an unrelated
work-status-changedduring the delete step (its own files changed), and refetched status and files for that.Probe branch moves: main spawned 20
for-each-refper move and all 20 envs emittedgit-refs-changed(more when other agents' writes overlapped). The branch spawned 1 per move and 0 envs emitted anything. Earlier runs across load 5–45 gave the same counts:for-each-refat watch startup: main 20–28, branch 11–17, because provisioning is serial so only part of it joinsHow often name changes happen on
~/Projects/bb. These now trigger only a branch-list refetch instead of a full refresh of every env:Costs:
%(push)adds about 18 ms (190 ms against 172 ms at low load).Tests
packages/host-workspace/test/host-workspace.test.ts, for both files and reftable:branchNamesFingerprintbut not themainenv's fingerprint.mainenv's fingerprint unchanged.refs/remotes/fork/<branch>(no config), a renamed%(push)destination, or the default branch changes it.main, moving its merge base changes the fingerprint for a local base (feature) and a remote one (fork/feature). This fails if the merge base is left out of the watched set.apps/host-daemon/src/watch-manager.test.ts:git-branches-changed, and an own-ref move emits onlygit-refs-changed.watch-set.replacekeeps the watch running (no re-provision), refreshes that env once, and later base moves reach it. This fails without the in-place update.plugins/git/server/invalidation.test.ts:git-branches-changed→ refs tag only, caches kept, no refs-generation bump, also when mixed withwork-status-changed.plugins/github-pr-status/server.test.ts:git-branches-changed→ no effect.packages/host-daemon-contract/test/contract.test.ts: protocol 263 (262 no longer compatible), and the new kind parses inenvironment-change.apps/server/test/internal/internal-environment-change.test.ts: the server forwards the new kind to clients.apps/server/test/app/watch-interests.test.ts: workspace targets carry the resolved merge base (null, thenbaseBranch, then asetMergeBase-style override, then back tobaseBranchwhen cleared), re-sent on eachmetadata-changed.pnpm start:worktreedev server with a scratch repo and 4 worktree threads, watching the client WebSocket's environment events:origin/feature/beta: only the env started fromfeature/betagetsgit-refs-changed(before this commit, none did).origin/feature/alpha: A getsmetadata-changed+git-refs-changed, and its watch isn't restarted. Movingorigin/feature/alphaafterwards reaches A only.feature/alphaagain reaches no env.pnpm exec turbo run typecheckfor@bb/host-daemon-contract,@bb/host-workspace,@bb/host-daemon,@bb/server,@bb/app,bb-environment-provider-hostand the git and github-pr-status plugins: all pass.vitest runfor those packages: all pass. CI runs the full suites.🤖 Generated with Claude Code