Skip to content

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 into
mainfrom
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j
Nov 5, 2026
Merged

ymichael merged 4 commits into
mainfrom
bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j

Conversation

@ymichael

@ymichael ymichael commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Every watched environment ran its own full git for-each-ref refs/heads refs/remotes whenever 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 a fetch --prune. Each environment then emitted git-refs-changed, which refetches git status, files and the branch list in the git plugin and makes the PR plugin run inspectRefs. This is finding #1 ("Ref watch fan-out") of the Nov 4 hot-path overreach audit.

What changed

  • One listing per repository. WatchManager.readSharedGitRefs keeps 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-changed now means "a ref this environment uses moved". SharedGitRefsSnapshot.fingerprintFor({ branchName, mergeBaseBranch }) covers only the oids of:
    • the HEAD branch, plus its %(upstream) and %(push) refs
    • every remote-tracking ref named after the branch (refs/remotes/*/<branch>). bb creates worktrees with --no-track, and a plain git push fork <branch> leaves both %(upstream) and %(push) empty, so a push to a fork remote still refreshes PR status.
    • the default branch, local and origin/
    • origin/HEAD and its target
    • the environment's merge-base branch (refs/heads/<base> and refs/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 as mergeBaseBranch on each watch-set.replace workspace 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's setMergeBase. A merge-base change already emits metadata-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.
  • New git-branches-changed environment change kind. SharedGitRefsSnapshot.branchNamesFingerprint hashes the repository's branch-name set. When it changes, the daemon emits git-branches-changed instead of git-refs-changed. Each consumer handles it as follows:
    • git plugin (plugins/git/server/invalidation.ts): invalidates only the branch list (refs: tag, the branches RPC). It keeps the status/files caches and does not bump the refs generation. refsChanged is now set per change kind rather than inferred from the refs tag, so a batch that mixes the new kind with work-status-changed doesn't bump refs either.
    • github-pr-status: environmentChangeEffect returns null, so the kind is ignored; PR status doesn't depend on other branches existing. Added to its mapping table test.
    • App cache registry (realtime-cache-registry.ts): dirty: [], the same as git-refs-changed. Neither is in the app's watched-kinds list or the server's watch-target kinds.
    • Server (notifyDaemonEnvironmentChange): forwards the new kind unchanged. The existing internal test now covers it.
  • Supporting changes. inspectGitRepository already read --git-common-dir; it now returns it, and HostWorkspace exposes it as gitCommonDir. The listing format drops %(refname:short) (local names are now sliced from refs/heads/) and adds %(upstream) and %(push).

Why the bumps are needed

  • HOST_DAEMON_PROTOCOL_VERSION 262 → 263: git-branches-changed is a new value in the daemon's environment-change WebSocket message (hostDaemonEnvironmentChangeSchema). A 262 server would reject it, and a 262 daemon would keep emitting git-refs-changed for branch-name changes. The same bump covers the new required mergeBaseBranch field on watch-set.replace workspace targets.
  • @get-bb/plugin-sdk 0.6.125 → 0.6.126 (scripts/bump-plugin-sdk.mjs --patch): the new kind widens the changes union of the SDK's environment:changed event (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 WatchManager with the subprocess parcel watcher on 20 real ~/Projects/bb worktrees, with a git PATH 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-plugin tagsForEnvironmentChanges and github-pr-status environmentChangeEffect. 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):

main branch
for-each-ref spawns 20 (15.2 s / 19.5 s summed) 1 (0.20 s / 0.24 s)
envs emitting git-refs-changed 20 0
envs emitting git-branches-changed — 20
git plugin refetch per env status + files + branch list, caches cleared branch list only, caches kept
PR plugin per env invalidate (inspectRefs → upstream host call) none

One env on the branch also had an unrelated work-status-changed during the delete step (its own files changed), and refetched status and files for that.

Probe branch moves: main spawned 20 for-each-ref per move and all 20 envs emitted git-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:

  • moves reached 0 envs whenever nothing else moved (16 of 16 such steps)
  • 1 env when a watched worktree switched its own HEAD branch mid-step (verified in its reflog)
  • for-each-ref at watch startup: main 20–28, branch 11–17, because provisioning is serial so only part of it joins

How often name changes happen on ~/Projects/bb. These now trigger only a branch-list refetch instead of a full refresh of every env:

  • Live 29-minute sample: 18 ref-write bursts, 7 of which changed the name set (2 local creates, 5 remote creates, 2 remote prunes).
  • Reflogs, last 7 days: about 105 ref creations a day against 253 moves. That is a lower bound, since deleted refs lose their reflogs.

Costs:

  • A single listing with the new format, 15 interleaved runs: median 259 ms and 0.90 MB, against 286 ms and 1.09 MB for the old format.
  • %(push) adds about 18 ms (190 ms against 172 ms at low load).
  • Each env now keeps a short fingerprint string instead of a ~1 MB copy of the listing.

Tests

  • packages/host-workspace/test/host-workspace.test.ts, for both files and reftable:
    • creating a branch changes branchNamesFingerprint but not the main env's fingerprint.
    • moving an unrelated branch leaves the main env's fingerprint unchanged.
    • moving the env's own branch, its upstream, its refs/remotes/fork/<branch> (no config), a renamed %(push) destination, or the default branch changes it.
    • with an env on 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:
    • a branch-name change emits only git-branches-changed, and an own-ref move emits only git-refs-changed.
    • an env reports its merge base moving and the other env doesn't. Changing a merge base through watch-set.replace keeps the watch running (no re-provision), refreshes that env once, and later base moves reach it. This fails without the in-place update.
    • two worktrees of one repo share one read, and only the one whose refs moved reports.
    • a change that arrives while a shared read is running starts a fresh read. This test fails if a started read can be joined.
    • when the shared read rejects, joined envs fall back to their own read. This test fails without the fallback.
  • plugins/git/server/invalidation.test.ts: git-branches-changed → refs tag only, caches kept, no refs-generation bump, also when mixed with work-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 in environment-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, then baseBranch, then a setMergeBase-style override, then back to baseBranch when cleared), re-sent on each metadata-changed.
  • Live check on a pnpm start:worktree dev server with a scratch repo and 4 worktree threads, watching the client WebSocket's environment events:
    • moving origin/feature/beta: only the env started from feature/beta gets git-refs-changed (before this commit, none did).
    • setting Worktree A's merge base to origin/feature/alpha: A gets metadata-changed + git-refs-changed, and its watch isn't restarted. Moving origin/feature/alpha afterwards reaches A only.
    • after clearing A's merge base, moving feature/alpha again reaches no env.
  • Commands:
    • pnpm exec turbo run typecheck for @bb/host-daemon-contract, @bb/host-workspace, @bb/host-daemon, @bb/server, @bb/app, bb-environment-provider-host and the git and github-pr-status plugins: all pass.
    • Targeted vitest run for those packages: all pass. CI runs the full suites.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j branch from 2041a11 to 448bef4 Compare November 5, 2026 06:29
@ymichael ymichael changed the title Fingerprint only each worktree's own refs and read shared refs once per repo Watch only each worktree's own refs, report branch-name changes separately, and read shared refs once per repo Nov 5, 2026
@ymichael
ymichael force-pushed the bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j branch 2 times, most recently from c4925fa to 9704314 Compare November 5, 2026 18:11
ymichael and others added 4 commits November 5, 2026 11:34
…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
ymichael force-pushed the bb/ref-watcher-re-reads-every-ref-per-worktree-thr_qats8urr6j branch from 9704314 to 37189be Compare November 5, 2026 19:35
@ymichael
ymichael merged commit 584f28d into main Nov 5, 2026
52 checks passed
@ymichael
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant