Repository navigation
[codex] add dev auto multi-stack runner - #10
Closed
SawyerHood wants to merge 1 commit into
Closed
SawyerHood wants to merge 1 commit into
SawyerHood wants to merge 1 commit into
Conversation
ymichael
added a commit
that referenced
this pull request
Oct 30, 2026
## Human comments ## What was wrong Several cache owners wrote a server reply or the thread-detail bootstrap straight into the React Query cache with `setQueryData` while a fetch of the same key could still be in flight. React Query writes fetch results without checking whether they're older than what's cached (query-core `query.ts`), so the older fetch landed last and put stale data back. Effects included: an environment or host status that stayed stale after opening a thread, a plugin settings form resetting its draft to the old value, a cancelled plugin install flipping back to running, new plugin update jobs dropping out of the list, an `idle` app update phase switching off the progress poll, and the AI service selection flickering back. These are items #2–#10 from the direct cache write audit (@thread:thr_fjr5x8dzaz). #1 (thread tabs) is fixed separately in #6611. ## What changed Two fixes, depending on whether the data has a version field: - **Environment and Host keep the newer copy by `updatedAt`** (#2, #3, #10). The bootstrap ingest (`thread-detail-cache-owner.ts`), the rename reply (`applyEnvironmentUpdateResult`), and the `useEnvironment`/`useHosts` fetches all compare `updatedAt`. The fetch-side check is what catches a fetch that started before the write and lands after it. To make it testable, those fetches now live in `environmentQueryOptions` and `hostsQueryOptions`. Host `status` comes from live daemon sessions and a disconnect doesn't change `updatedAt`, so on a tie the cached copy wins over the bootstrap. The bootstrap only fills an empty cache or replaces strictly older data. Rename replies and fetch results still win ties. - **`setQueryDataOverInFlightFetch`** (`cache-effect-utils.ts`) for data with no version (#4–#9): it writes the value, and if a fetch of the key is in flight it cancels that fetch (the cache keeps the written value) and refetches. With nothing in flight it's a plain write. Used by `applyPluginSettingsView`, `applyPluginInstallJob`, `applyPluginUpdateJob`, `hydrateAppUpdateStatus`, `hydrateSystemVersionCache` and `writeCachedAiServices`, so every caller gets the fix. Where the audit suggested an unconditional cancel-write-invalidate (#7) or a cancel before the write (#8, #9), this helper refetches only when a fetch was actually in flight. That avoids an extra request on every write. Forced version and app-update checks update the server's cache, so the trailing unforced refetch returns the forced result. No wire, CLI or plugin API changes. Not covered here: audit items #11 (plugin safe mode) and #12 (prompt history), both low risk. Also not covered: a lint rule restricting direct `setQueryData` calls to the helper, which would stop new call sites from bringing the race back. ## How you verified - New tests use real `QueryClient`/`QueryObserver` instances: start a fetch that resolves late with older data, do the write, let the fetch land, then check that the newer value survives (and, for the helper, that the trailing refetch runs). - `thread-detail-cache-owner.test.ts` (new): late environment and host-list fetches after a bootstrap, an older bootstrap over a newer cache, and the equal-`updatedAt` host status case. - `environment-workspace-cache-owner.test.ts`: a late environment fetch after a rename, and an older rename reply over a newer cache. - `in-flight-fetch-writes.test.ts` (new): one row per cache-owner write for #4–#9, plus helper tests for the no-fetch case (no extra request) and a fetch of an unobserved query. - With each source change reverted, every race test failed on the stale data and passed once the fix was restored. - `pnpm exec turbo run typecheck lint test --filter=@bb/app`: passed (647 files, 6515 tests; 0 lint errors, no new warnings). After rebasing onto `0472409243` I re-ran the three changed test files (21 tests passed). 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Nov 5, 2026
ymichael
added a commit
that referenced
this pull request
Nov 5, 2026
## Human comments ## What was wrong Perf audit finding #10 (thread-storage file list). Two separate costs: **1. Every unqueried listing walked the whole tree.** The thread-storage panel asks for the first 1,000 files with no query (`apps/server/src/routes/threads/data.ts` → `host.list_files`, `limit: 1000`). On the daemon, `listHostFiles`/`listHostPaths` always called `listWorkspacePaths`, which walks the whole tree (11–17k files in real thread-storage dirs). `finalizeListedPaths` then keeps only `limit + 1` entries. The full listing is cached only when the walk took ≥500 ms, so most refetches while an agent writes pay for the full walk again. **2. Every storage write refetched the lists of every thread in the environment.** When a file changed in a thread's storage, the daemon sent `environment-change` with `change: "thread-storage-changed"` and only the environment id (`apps/host-daemon/src/app.ts`), although its watcher already knew the thread. The server broadcast that to every connected client. The app then refetched the storage queries of **every cached thread in that environment** (`dirtyThreadStorageQueriesForEnvironment`). So one agent writing reports or screenshots made every open thread in the same environment re-list its own storage, on every client. ## What changed **Bounded unqueried listings (daemon only).** When a listing has no query, the walk stops once it has `limit + 1` paths. The walk is depth-first in `readdir` order, so the bounded walk returns the same prefix in the same order as the full one, and `truncated` is unchanged. Queried listings still walk, cache and rank the full tree. The change is daemon-local: there are no wire changes, no `HOST_DAEMON_PROTOCOL_VERSION` bump and no plugin SDK change. The same path serves every unqueried `host.list_files`/`host.list_paths` caller (workspace, project, environment, skills), and each gets identical results. The one part of finding #10 left out is always caching the full listing with watcher invalidation. **Thread-targeted storage notifications.** - **Daemon** (`HOST_DAEMON_PROTOCOL_VERSION` 261 → 262): sends a new `thread-storage-change { threadId }` message. `thread-storage-changed` is removed from the daemon's `environment-change` kinds. The thread-storage watch target drops `environmentId`, because this message was its only use. - **Server:** `notifyDaemonThreadStorageChange` checks that the thread's environment belongs to the sending host and isn't destroyed. It then calls `hub.notifyThread(threadId, ["storage-changed"])`. `storage-changed` is detail-only, like `history-compacted`, so it goes only to that thread's `thread-detail` subscribers and not to the thread list. It doesn't re-resolve watch targets. - **App:** a `storage-changed` thread rule (debounced) refetches that thread's storage files, paths and previews. The environment rule, `collectCachedThreadIdsForEnvironment` and the `getCachedThreadIdsForEnvironment` context are deleted. A released thread-detail watch now catches up by re-marking that thread's storage, not the whole environment's. - **Domain / plugin SDK:** `storage-changed` is added to `THREAD_CHANGE_KINDS` and `thread-storage-changed` is removed from `ENVIRONMENT_CHANGE_KINDS`. These unions are part of the plugin SDK's realtime types (`ChangedMessage`), so the SDK goes 0.6.124 → 0.6.125. In-repo, the git plugin listed the old kind only to keep its caches, and the github-pr-status test listed it as a no-op. Both are updated. **Why the protocol bump and SDK change can't be avoided:** the server can't tell from the environment id which thread's storage changed, so the daemon message needs the thread id. Clients can only be told which thread changed through the realtime change message type, and the plugin SDK publishes that type. ## How you verified ### Bounded listings The benchmark calls `listHostFiles` with the panel's exact command (`limit: 1000`, `includeHidden: false`, `respectGitIgnore: false`, default excludes) on the six largest real dirs in `~/.bb/thread-storage`. Each call runs in a fresh process, 5 runs per dir. Main and branch use the same checkout with only the daemon files swapped. Medians: | thread storage | files walked on main | main wall / CPU (ms) | branch wall / CPU (ms) | | --- | ---: | ---: | ---: | | thr_cbwjth4yt7 | 11,596 | 317.6 / 194.9 | 9.1 / 15.2 | | thr_n6cyn6sk25 | 16,894 | 233.9 / 226.8 | 9.8 / 16.1 | | thr_7csui6fdj4 | 16,394 | 245.0 / 219.8 | 12.6 / 18.2 | | thr_gtbhvapit2 | 12,569 | 71.1 / 94.7 | 13.3 / 19.4 | | thr_272ubxihy7 (active, being written) | 10,985 | 123.5 / 122.6 | 47.2 / 53.9 | | thr_y6xhxw8t8w | 4,229 | 20.7 / 34.4 | 12.3 / 17.4 | Parity: the response hash (`files` + `truncated`) matches main for every static dir. thr_272ubxihy7 is a live thread and its hash changes between runs on either build. Frozen copies of it and thr_cbwjth4yt7 give identical hashes on main and branch (`8e315bfdd95a`, `d4f45e09ef0b`). Tests: a new case in `workspace-path-list.test.ts` checks that an unqueried `host.list_paths` at a limit returns exactly the full walk's first entries with `truncated: true`, reads fewer directories than the full walk, and returns `truncated: false` when the limit equals the tree size. Locally `workspace-path-list.test.ts` and `file-list.test.ts` pass (32 tests), and `@bb/host-daemon` typecheck passes. CI runs the full suites. ### Thread-targeted notifications **Real running servers, main vs branch.** I ran source servers from origin/main and from this branch with `pnpm start` on fresh data dirs, not a copy of `~/.bb`. Each had one project and two threads in one environment: A, where files are written, and B, the viewer. Three headless Chrome instances each held one foreground page on the real app: A with the right panel open, B with the right panel open, and home. I wrote 20 files into A's thread storage, one per second, and counted `/thread-storage/files` requests and `storage-changed` WebSocket frames per page. | page | main: storage list requests | main: frames | branch: storage list requests | branch: frames | | --- | ---: | ---: | ---: | ---: | | A (written to, panel open) | 20 | 20 | 20 | 40 | | B (same environment, panel open) | **20** | 20 | **0** | **0** | | home (no thread open) | 0 | **20** | 0 | **0** | - On main, B re-listed its own unchanged storage on every write to A, and every connected client received every change. - On the branch, only A refetches. A's page has two sockets subscribed to its thread detail: the app's own and the SDK realtime client plugins use. So it receives two frames per write, but still makes one request. **Tests:** - `internal-environment-change.test.ts`: `thread-storage-change` notifies only the changed thread with `storage-changed`, ignores the same message from another host, and never sends an environment change. - `realtime-cache-effects.test.ts`: a `storage-changed` change refetches the changed thread's storage preview and not a sibling thread's in the same environment. - Contract tests cover the new message and confirm the old environment kind is rejected. - Updated: watch-manager, watch-interests, freeze-fence, daemon-message-fence and contract fixtures. **Commands:** - `pnpm exec turbo run typecheck --filter='...[origin/main]'`: 117/117 - `turbo run lint` on the same filter: 57/57 - Targeted vitest runs for host-daemon, server, host-daemon-contract, domain, app, git and github-pr-status - `check-plugin-sdk-version.mjs` CI runs the full suites. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
pushed a commit
that referenced
this pull request
Nov 25, 2026
…lability read (#8187) ## Human comments ## What was wrong A nested bb whose Account Pooler proxies to a parent pool decides per turn whether it can route through the parent, using `ParentAvailability` in `plugins/account-pool/src/parent-pool.ts`. `load()` gives the parent's `/availability` 2 s, and on any error or non-OK status returns `UNAVAILABLE_POOL`. `get()` caches that result for the full 30 s TTL, the same as a good answer. So one slow read from a busy parent takes the child off the pool for 30 s, and every turn that starts in that window runs with no pool credentials. On a child with no Claude login of its own, Claude Code answers `Not logged in · Please run /login` and Provider Retry skips the turn as not retryable. On one child this happened three times in a day, each time the parent's host was under heavy load. ## What changed - `plugins/account-pool/src/parent-pool.ts`: `ParentAvailability` remembers the last good availability. - A failed read keeps serving it, and the next read is tried after 5 s instead of 30 s. - Once reads have failed for 60 s in a row, the parent is reported unavailable and that answer is cached for the normal TTL, as before. A parent that has never answered is reported unavailable, and the read is retried after 5 s. - The read timeout goes from 2 s to 5 s. - `plugins/account-pool/src/parent-pool.test.ts`: three cases, all of which fail on `main`: - one failed read keeps the last good value and retries after 5 s; - a parent that stays down is reported unavailable after 60 s, then cached for the TTL; - a failed first read is retried after 5 s. - No wire, CLI or doc changes. ## How you verified - New tests on `main`'s `parent-pool.ts`: the 3 new tests fail with `expected { claude: false, codex: false } to deeply equal { claude: true, codex: false }`, and the other 13 pass. With the change: 16/16. - After the final commit: `pnpm exec turbo run typecheck lint test --filter=bb-plugin-account-pool --force` passed 10/10 tasks, with 14 test files and 402 tests passing. Lint reported 3 warnings, all in `app.tsx`, which this PR does not touch. `pnpm exec turbo run lint:type-aware --filter=bb-plugin-account-pool --force` passed 7/7 tasks with 0 warnings. `pnpm exec turbo run prepare:bundled --filter=bb-plugin-account-pool` passed 7/7 tasks. `oxfmt --check` passes on both files. - Standalone reproduction with real HTTP and the real clock. `ParentAvailability` uses the real `fetch` and the shipped TTL and timeouts against a local HTTP parent, and one `get()` per second stands in for a turn start. `main` and this branch ran side by side. One slow answer (request #2 answers in 8 s, then normal), on `main`: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 answering in 8s [ 32.2s] child: warn could not read parent availability: The operation was aborted due to timeout [ 32.2s] child: turn start -> NOT ROUTED (turn runs with no login) after waiting 2003ms [ 62.3s] parent: request #3 -> 200 {claude:true} [ 62.3s] child: turn start -> ROUTED (claude via parent pool) summary: 43 turn starts routed, 30 not routed, 3 parent requests ``` With the change: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 answering in 8s [ 35.2s] child: warn could not read parent availability: The operation was aborted due to timeout [ 35.2s] child: turn start -> ROUTED (claude via parent pool) after waiting 5003ms [ 40.2s] parent: request #3 -> 200 {claude:true} [ 70.4s] parent: request #4 -> 200 {claude:true} summary: 70 turn starts routed, 0 not routed, 4 parent requests ``` A parent that stays down (503 from 25 s on), on `main`: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 -> 503 (down) [ 30.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 30.2s] child: turn start -> NOT ROUTED (turn runs with no login) [ 60.4s] parent: request #3 -> 503 (down) [ 60.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.5s] parent: request #4 -> 503 (down) [ 90.5s] child: warn could not read parent availability: parent availability returned HTTP 503 [120.7s] parent: request #5 -> 503 (down) [120.7s] child: warn could not read parent availability: parent availability returned HTTP 503 summary: 30 turn starts routed, 100 not routed, 5 parent requests ``` With the change, the child keeps routing for 60 s after the first failure, then reports the parent unavailable and goes back to reading every 30 s: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 -> 503 (down) [ 30.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 35.2s] parent: request #3 -> 503 (down) [ 35.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 40.2s] parent: request #4 -> 503 (down) [ 40.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 45.3s] parent: request #5 -> 503 (down) [ 45.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 50.3s] parent: request #6 -> 503 (down) [ 50.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 55.3s] parent: request #7 -> 503 (down) [ 55.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 60.3s] parent: request #8 -> 503 (down) [ 60.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 65.3s] parent: request #9 -> 503 (down) [ 65.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 70.3s] parent: request #10 -> 503 (down) [ 70.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 75.3s] parent: request #11 -> 503 (down) [ 75.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 80.3s] parent: request #12 -> 503 (down) [ 80.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 85.4s] parent: request #13 -> 503 (down) [ 85.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.4s] parent: request #14 -> 503 (down) [ 90.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.4s] child: turn start -> NOT ROUTED (turn runs with no login) [120.5s] parent: request #15 -> 503 (down) [120.5s] child: warn could not read parent availability: parent availability returned HTTP 503 summary: 90 turn starts routed, 40 not routed, 15 parent requests ``` <details><summary>repro.mts (run from the repo root as <code>node_modules/.bin/tsx repro.mts $PWD/plugins/account-pool/src/parent-pool.ts slow-once|down</code>)</summary> ```ts import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; const [modulePath, scenario] = process.argv.slice(2) as [string, "slow-once" | "down"]; const { ParentAvailability } = await import(modulePath); const TOKEN = "vqMIj4xUiI3PyvKS2SllSKHsOfxLF_sAZwzNAAvV9TQ"; const started = Date.now(); const t = () => ((Date.now() - started) / 1000).toFixed(1).padStart(5); let request = 0; const server = createServer((req, res) => { request += 1; const n = request; const elapsed = (Date.now() - started) / 1000; if (req.headers["x-bb-account-pool-token"] !== TOKEN) { res.writeHead(401).end(); return; } const answer = () => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ claude: true, codex: false })); }; if (scenario === "slow-once" && n === 2) { console.log(`[${t()}s] parent: request #${n} answering in 8s`); setTimeout(() => { if (!res.destroyed) answer(); }, 8_000); return; } if (scenario === "down" && elapsed > 25) { console.log(`[${t()}s] parent: request #${n} -> 503 (down)`); res.writeHead(503).end(); return; } console.log(`[${t()}s] parent: request #${n} -> 200 {claude:true}`); answer(); }); await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); const { port } = server.address() as AddressInfo; const availability = new ParentAvailability({ parent: { baseUrl: `http://127.0.0.1:${port}/api/v1/plugins/account-pool/http`, token: TOKEN }, fetch, now: Date.now, onError: (error: unknown) => console.log(`[${t()}s] child: warn could not read parent availability: ${error instanceof Error ? error.message : String(error)}`), }); const durationS = scenario === "slow-once" ? 75 : 130; let last: string | null = null; let routed = 0; let unrouted = 0; while ((Date.now() - started) / 1000 < durationS) { const before = Date.now(); const value = await availability.get(); const waited = Date.now() - before; if (value.claude) routed += 1; else unrouted += 1; const state = value.claude ? "ROUTED (claude via parent pool)" : "NOT ROUTED (turn runs with no login)"; if (state !== last || waited > 500) { console.log(`[${t()}s] child: turn start -> ${state}${waited > 500 ? ` after waiting ${waited}ms` : ""}`); last = state; } await new Promise((r) => setTimeout(r, 1_000)); } console.log(`summary: ${routed} turn starts routed, ${unrouted} not routed, ${request} parent requests`); server.close(); process.exit(0); ``` </details> - **Not checked:** an isolated nested bb against a slow parent bb end to end. The reproduction drives the same class the server constructs, with the same options except `onError`. Fixes #8188 > 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.
Summary
Adds
pnpm dev:autofor running isolated development stacks from one checkout. The new scripts package helpers deterministically allocate coherent slot-based port tuples, probe loopback port availability, coordinate active reservations through an atomic directory lock, prune stale PID-owned reservations, and write a sourceabledev-auto.envper stack.The command wrapper reserves a stack, prints the selected app/server/daemon/dev-env URLs plus CLI guidance, spawns the existing Turbo dev pipeline with stack-specific environment, scrubs leaked
BB_HOST_IDandBB_HOST_ENROLL_KEY, synthesizesBB_HOST_NAMEwhen absent, forwards shutdown signals, and releases the reservation on exit.User impact
pnpm devbehavior is unchanged.pnpm dev:autostarts from slot 0 when available, keeps each stack under its ownBB_DATA_DIR, and allows separate local server, app, host daemon, dev-env helper, database, daemon auth, host identity, logs, runtime material, and supervisor PID files.Validation
pnpm exec turbo run typecheck --filter=@bb/scriptspnpm exec turbo run test --filter=@bb/scriptspnpm exec turbo run build --filter=@bb/scriptspnpm exec turbo run typecheck --filter=@bb/scripts --filter=@bb/config --filter=@bb/dev-env --filter=@bb/server --filter=@bb/host-daemon --filter=@bb/apppnpm exec prettier --check package.json packages/scripts/package.json packages/scripts/src/commands/run-dev-auto.ts packages/scripts/src/lib/dev-auto-ports.ts packages/scripts/src/lib/dev-auto-registry.ts packages/scripts/test/dev-auto-ports.test.ts packages/scripts/test/dev-auto-registry.test.ts packages/scripts/test/run-dev-auto.test.tsLightweight smoke: ran
run-dev-auto.tswithBB_DATA_DIR=/tmp/bb-dev-auto-smoke-codexand a restrictedPATHso it allocated a stack, printed the banner, wrotedev-auto.env, failed the intentionalpnpmspawn, and released the registry reservation. The smoke selected slot 1 because slot 0 ports were occupied on this machine, and the registry was empty after exit.Deviations / notes
pnpm dev:auto:clean, per the plan default.