Skip to content

Cut database and disk work when bot item views read linked workers - #47765

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/bot-items-linked-worker-read-cost
Nov 23, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/bot-items-linked-worker-read-cost

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Each time a bot's item list shows its linked workers, Orca walks every worker's follow-up chain in the database and checks folders on disk. The database lookups were rebuilt from scratch on every step, which also made a lot of garbage for the app to clean up. Now they are built once and reused. The folder checks now happen once per folder per read instead of twice per worker. A background pass that never used those folder checks no longer does them at all.

What Changed

  • SQL. The three lookups each lineage step runs (dispatch_contexts by follow_up_of_dispatch_id, worker_terminal_resources by owner_dispatch_id, and the formerly-owned resource lookup) used SELECT *. SyncDatabase never caches a wildcard statement, so each step prepared the statement again on the main thread and made new garbage. They now select the existing DISPATCH_CONTEXT_COLUMN_LIST / WORKER_TERMINAL_RESOURCE_COLUMN_LIST, which already back the other hot getters. Those lists fail compilation if they miss a row-type column, so the rows are unchanged, and the stale-wildcard rule in isStatementCacheable stays as it is.
  • Folder checks, once per path per item-view read. readLocalWorkspace keeps its exact check: gone only when the repo exists and the worktree doesn't (existsSync, same order, same short-circuit). workspaceReader takes an optional per-batch memo that only readLinkedWorkers passes, so an item view asks each path once. The work-record reader, which can close a bot work row, still checks every time.
  • The usage-limit pass skips workspace reads. It only uses each worker's state, so it calls readLinkedWorkers(refs, { pullRequests: false }) and no longer checks folders or reads PRs.

Why

A beachball capture from an affected build showed, in 107 s:

  • Database: about 38k native prepares each for the first two statements and 15k for the third.
  • Garbage collection: 636 GC pauses, 4.5 s in total.
  • Disk: 28k existsSync calls from these two lines, 1.8 s of sync fs.

In the worst stall window, 57% of stall samples were under readLinkedWorkers. Explicit projections fix the cause, uncacheable statements, and fit the pattern the other hot getters already follow. For the folder checks, deduping keeps today's behaviour exactly. Making them async changes what a slow or stalled disk means for these reads, and that's a separate design question (see Risk).

Linked Issue

N/A (internal perf report)

Visual Proof

N/A, no UI change: same item views, less main-thread work behind them.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

No committed test: the column lists are already compile-checked against the row types and used by the other getters, and the folder check keeps the base condition.

Measured on Linux with a scratch bench (not committed). It ran the real BotItemLinkJoin.readLinkedWorkers against a real migrated orchestration DB:

  • 150 linked workers, each an 8-step follow-up chain whose terminal moves along the chain.
  • Half of the worktrees deleted.
  • 40 view passes after one warm-up.
  • Only the live worker-status read and the workspace row read were stubbed.
before after
native SQLite prepare calls 138,000 (48,000 + 48,000 + 42,000) 0
main-thread existsSync 12,000 (2 per worker per view) 6,040 (once per path per view)
median / p90 view pass 73.0 / 113.6 ms 29.6 / 30.7 ms
GC time 460 ms 4 ms

Also checked in a Linux test build with a real bot:

  • The bot added an item, started two real workers, linked both, and continued one with a follow-up.
  • The item view shows both workers, the follow-up chain as one.
  • After one worktree was deleted, the view still renders.
  • A work row for the deleted worktree closes as gone, and the other row stays live with its workspace read.
  • No errors in the log.

Performance

Less work per item view. Native prepares for these statements drop from one per lineage step to one per process. Per-view existsSync from these lines is halved, and the usage-limit pass does none. No new timers, listeners or retained state: the path memo lives for one read pass.

Benchmark: head=bfeac3c84ffb80d9f24c1a0e428814be3d9c62a0 gate=PASS prepares 138000→0, existsSync 12000→6040, median pass 73.0→29.6 ms, GC 460→4 ms (150 linked workers × 8-step chains, 40 passes; listeners: none, main-process read path only)

Risk

Level: Low.

  • SQL: same rows, now from cached statements.
  • Folder check: same condition as before, asked once per path within one item-view read. Inside that read the checks run together before any await, and that read never closes a work row; the reader that can close rows checks fresh.
  • Usage-limit pass: it no longer reads PR state, which it never used.
  • Back out: a plain revert.

Known follow-up, not in this PR: the remaining folder checks are still sync on the main thread, and an unreadable worktree (EACCES/EIO) still counts as gone, as it does today. Changing either needs a decision on what a slow, unreadable or stalled disk should mean for showing and closing bot work. For example, treating unreadable as present currently sends it into a full workspace read that can repeat git remote setup.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Cross-platform: the folder check is unchanged. WSL UNC paths and non-local repos still skip it. SSH and remote workers don't reach this path (readRemoteWorkspace).

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

Bot workspace readers now share cached path-existence checks through BotWorkspaceReads. Linked-worker reads can skip workspace and pull-request reads, and usage-limit waits use that option. Follow-up dispatch and worker-terminal resource queries now select explicit column lists.

Merge Risk: Low · up to d5cd3

Linked-worker reads now share per-pass path checks, which reduces repeated filesystem probes and does not add a performance regression. A worktree that is unreadable because of a permission or I/O error can still be classified as deleted, which can close its work row. This behavior was already present and is a narrow edge case. The PR description also overstates the async probing, since the final commit kept synchronous checks.

Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title names the main change: reducing database and disk work when bot item views read linked workers. The changeset does this through explicit SQL column lists, deduped per-path existence checks, …
Description check Passed The description is detailed and covers the template's core sections: ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and the checklist. It explains the SQL projection …
Full details: Title check

Explanation

The title names the main change: reducing database and disk work when bot item views read linked workers. The changeset does this through explicit SQL column lists, deduped per-path existence checks, and skipping workspace/PR reads in the usage-limit pass. The title is specific and matches the primary objective, though it does not mention the SQL or usage-limit parts.

Full details: Description check

Explanation

The description is detailed and covers the template's core sections: ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Performance, Risk, and the checklist. It explains the SQL projection change, the per-batch folder-check memo, and the usage-limit pass change, and gives a measured benchmark. The Linked Issue is marked N/A (internal perf report), which the template does not allow for outside contributors but is acceptable for a maintainer-internal report. The AI Disclosure and Review sections are present but empty. The Performance section is filled in. Testing lists manual and automated checkboxes as checked, with an explanation for no committed test. The Risk section names the riskiest part and gives a back-out path. The description is mostly complete with some gaps in optional or conditional sections.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 738478ea-4eca-471c-9a8a-c4e2ffca93fc
Commits

Reviewing files that changed from the base of the PR and between bfcae05 and 589f451.

Files selected for processing: 8

  • config/main-blocking-helper-baseline.txt
  • config/main-sync-fs-baseline.txt
  • src/main/bots/bot-items-link-join.ts
  • src/main/bots/bot-work-runtime.ts
  • src/main/bots/bot-workspace-reads.ts
  • src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts
  • src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts
  • src/main/workspaces/catalog/local-worktree-path-presence.ts
Files with no reviewable changes: 1

  • config/main-sync-fs-baseline.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment thread src/main/bots/bot-workspace-reads.ts Resolved
…obe queue, skip probes for usage-limit passes
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh reviewer)

No introduced or amplified P0/P1 performance regression found in e57f136e893..4c4905a595b05592664a2ebac204cc7c7fc18fb0. The change removes synchronous filesystem probes from the changed workspace-read path and eliminates repeated compilation of three lineage statements. It does not eliminate lineage query execution or all existing catalog derivation work.

Evidence below distinguishes executed operation-count checks from source inspection. No application latency, CPU, or heap improvement is claimed.

Scope and workload

Reviewed all nine changed files, production callers through BotItemsHost.views, item RPCs, usage-limit reconciliation, standalone bot-work reads, scoped workspace resolution, filesystem admission, and SQLite statement caching.

Reference populations:

  • 750 worktrees across 12 repos; growth check at 7,500 worktrees.
  • 100 workers; growth check at 1,000 workers.
  • Lineage depths varied independently: 1, 10, and 100.
  • Primary item-list refreshes are shared per bot, coalesced while running, and separated by at least 500 ms. Thus sustained notices can produce up to two reads/second per active bot list. CLI/RPC callers have independent request rates; a dozen callers requesting every three seconds would add four requests/second.
  • Owner-list reads include every open item, so the 100-item page size does not cap a complete join. Each item permits 50 links.

Changed work and fleet price

Changed work Trigger, population, and owner Work, bound, and thread Fleet price and disposition
State-only usage-limit join: bot-item-usage-limit-wait.ts:73, bot-items-link-join.ts:104 Host snapshot, changed usage-limit cuts, relevant worker/item changes while stopped, or the existing minute tick. One running reconciliation plus one coalesced rerun. The new option skips workspace and PR construction before admission. Worker reads, reports, and end reasons remain on main. Executed production join with 100/1,000 workers, twice as many unique refs, and duplicate input refs: zero workspace reads, one worker batch, one reason batch, and 100/1,000 report reads. Full joins still performed exactly 100/1,000 workspace reads. Improvement; meaningful full reads remain enabled by default.
Shared workspace-read scope: bot-items-link-join.ts:92, new bot-workspace-reads.ts One scope per full linked-worker read. PR work remains deduplicated by newest Dispatch; paths are additionally deduplicated across workers. O(unique refs) join promises; O(unique paths + owner repos) probe results. Scope lifetime is the request. Main pays allocations and promise bookkeeping. For 750 worktrees/12 repos: 762 stats instead of up to 1,500 existence checks. At 7,500 worktrees with repos held at 12: 7,512. Scaling repos independently to 120 gives 7,620. Necessary freshness work with fewer duplicate probes.
Async deletion proof: bot-work-runtime.ts:156, bot-workspace-reads.ts:67 Each local worker workspace requested by an item view or standalone bot-work read. Repository checked before worktree; missing repository, permission failure, and timeout cannot prove deletion. Native stat runs through asynchronous filesystem I/O; main handles completion. At two full reads/second, the 750-worktree case admits up to 1,524 stats/second, shared across at most two active native probes. This is request-driven work, not a new poll. No synchronous filesystem call remains in this changed function.
Probe queue/deadline: bot-workspace-reads.ts:21 First distinct eligible path in each batch. Two pass probes in flight, with the existing global semaphore limiting actual stats to two across callers. One two-second pass deadline. Queue storage grows with requested distinct paths and drains monotonically. Executed at 750/7,500 paths. Hung repositories started only two stats; one available repository followed by hung worktrees started three. Deadline expiry drained the remainder without new stats. Twelve simultaneous owners still started only two native stats.
Standalone reads without a scope: bot-workspace-reads.ts:75 Existing bot-work list, conversation PR, and turn-note callers. At most two sequential probes per workspace, each with the helper’s two-second timeout. These callers do not receive batch deduplication or the combined pass deadline. 100/1,000 distinct workspace checks can still require 200/2,000 stats. A two-probe check can consume two timeout windows. Main no longer blocks on those filesystem calls; this is not a bound on the entire enclosing request.
Cached follow-up query: worker-follow-up-lineage.ts:42 Every reachable lineage step, including linked-worker reads and other existing lineage consumers. Same indexed .get() execution and row projection; explicit columns make its fixed SQL cacheable. SQLite still executes synchronously on main. Query count remains proportional to visited lineage nodes. Compilation becomes one cached statement rather than one compilation per call, subject to existing cache eviction/schema invalidation. Improvement.
Cached owner/former-owner queries: worker-terminal-resource-store.ts:115 and :153 Resource lookup during lineage resolution and existing terminal-resource consumers. Same predicates and output columns. Owner lookup uses its unique index. Former-owner lookup uses the prior-owner primary key and resource primary key; ordering examines matches for that Dispatch. Together with the follow-up getter, executed 2,250/22,500 calls at N/10N: base compiled 2,250/22,500 statements each pass; target compiled 3 on the first pass, 0 on the second. Statement cache remains bounded at 256.
Exported presence type: local-worktree-path-presence.ts:11 Compile-time dependency only. No runtime work. Zero runtime cost.
Two ratchet baseline edits Static audit execution only. No application work or scheduling. The changed read path was traced independently of these allowances. Zero runtime cost; baseline reductions are consistent with removing the blocking helper/fs reachability.

Probe timeout bookkeeping is also population-sized: the helper creates a timeout signal for each distinct probe invocation in addition to the pass signal. An expired pass with 7,500 queued paths created 7,501 timeout signals in the deterministic harness, although only two stats started. This bookkeeping ends with the request/deadlines; it creates no recurring idle loop.

Existing costs retained by the span

These are pre-existing amplification observations, not introduced/amplified P0/P1 findings against this diff.

  • Usage-limit reconciliation still constructs unused reports and end reasons. At bot-items-link-join.ts:81 and :107, the state-only call still performs one reason query and one task/report read per distinct local task. Its caller consumes worker state and Dispatch identity (bot-item-usage-limit-wait.ts:91). Executed counts were 100/1,000 report reads per pass. With average report length B, this retains O(100B)/O(1,000B) report processing on main per pass. The new option removes workspace work but leaves this existing waste.
  • Scoped workspace resolution rebuilds a global lineage adjacency map per workspace. scoped-worktree-row-resolution.ts:119 calls getConnectedWorktreeLineageIds; its resolved-worktree-lineage.ts:84 enumerates every lineage entry. Executing 100 singleton workspace lookups against 750 unrelated edges visited 75,000 entries/read, or 150,000/second at two reads/second. At 1,000 lookups and 7,500 edges, this became 7.5 million/read, or 15 million/second. The code and its reachability predate the span.
  • Batch caching does not cover every related-repository derivation. Owner-repository reads use the existing scoped map, but connected related repos are scanned/stamped through scoped-worktree-row-resolution.ts:145 per lookup. For M requested workspaces with K related owners each, that remains M×K related-owner calls before underlying scan-cache reuse. The new wrapper preserves this behavior.
  • Statement caching does not bound lineage history. Executing the production lineage algorithm with 100 workers at depth 10 produced 1,000 owner, 1,000 former-owner, and 1,000 follow-up lookups. At two reads/second that is 6,000 executions/second of the changed getters. At 1,000 workers/depth 10 it is 60,000/second. Repeated refs within the same batch reused the lineage cache; a later request rebuilds it. These execution counts are unchanged.

Consequently, the patch removes specific blocking costs without establishing that accumulated-history item views are now stall-free.

Six scan questions

Question Disposition
1. Work before the skip gate? Reviewed. State-only PR/workspace admission now happens before construction; executed zero-workspace control passed. Existing unused reports/reasons remain, quantified above.
2. Ownership multiplies/recreates work? Reviewed. One workspace scope per join, one PR read per newest Dispatch, one report per task, one probe per exact path. UI list reads share a bot owner; reconciliation coalesces passes. Separate RPCs retain separate freshness scopes.
3. Thread and storage layer? Reviewed. Changed filesystem I/O leaves main. SQLite execution and JS derivations remain on main. Real in-memory SQLite verified compilation counts and indexed query plans; query execution counts do not decrease.
4. Growth and forward progress? Reviewed. Probe maps/queues scale with requested distinct paths, not process lifetime; queue cursor advances through timeout failures. Lineage cycles have a visited set. History-dependent SQL execution and catalog rescans remain as described above.
5. Execution host effects? Reviewed structurally and with guard controls. SSH-owned repos and WSL UNC worktrees admitted zero local probes. Slow native mounts share the global width of two. No new subprocess or per-item SSH call was added. Live Windows/WSL/Linux behavior was not measured.
6. Obsolete work stops/releases budget? Reviewed with cancellation limits. Expired queued probes start no further native I/O and pass queues drain. Already-started stat calls cannot be cancelled; up to two retain semaphore permits until native completion. Late completion released both permits, and a successor then completed. Hiding/closing does not cancel an already-admitted RPC; that behavior is unchanged.

Touched regression classes

Class Disposition
Expensive work past a gate Matched and disproved as a regression: the added gate removes workspace/PR work; default full reads remain intact.
Sync fs/SQLite on main Matched: sync fs removed from the changed path; SQLite compilation reduced, execution retained and priced.
Re-reading unchanged input Matched: same-batch repeats admitted zero extra stats; a fresh batch re-probed paths, preserving deletion/restoration freshness. Existing cross-request report/history reads remain.
Hot-path rescans / per-row collection derivation Pre-existing amplification found and quantified; scope forwarding does not add it.
Unbounded fan-out/queues Matched and bounded by request population plus deadline. Native filesystem concurrency stayed two at N, 10N, and 12 concurrent owners. No independent retry queue was added.
Per-entity state outlives entity Matched and disproved: new maps/queue belong to one request; no process-wide per-path registry was introduced. Native late completions are limited to two.
Hidden/unobserved work Existing hidden-window refresh deferral remains. Background usage-limit reconciliation remains necessary; its unused report processing predates the span.
Fixed-cadence loops / new steady-idle wakeups No new recurring source. Added timers are request deadlines. Changed mechanisms add 0 recurring wakeups/second after requests settle; existing scheduler cadence is unchanged.
Eager startup imports No new SDK, client, worker, or discovery loop. Scoped catalog code was already imported by the join; the new wrapper adds small module initialization and probe bookkeeping. Cold-start timing was not measured.

Validation limits

Executed read-only, in-memory audit harnesses on this macOS host using Node 26.5.0. Production TypeScript functions were evaluated with counting seams; filesystem outcomes and deadline expiry were controlled. SQLite checks used the production cache wrapper and native in-memory SQLite with the relevant indexes. TypeScript constructor parameter properties were lowered equivalently in memory for the harness.

No files were edited or dependencies installed. No Electron instance, packaged profile, real slow mount, OS-level presentation, or live remote transport was exercised. The operation-count evidence supports the span verdict; it does not establish application frame latency or the absence of remaining main-thread stalls.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready

Problem. On a bot with a long item history, opening its item views could freeze the window. Each view walked every linked worker's follow-up chain. Every step rebuilt three database lookups from scratch, and every worker ran two blocking disk checks.

What users get. The same item views, with far less main-thread work behind them. The lookups are built once per process. The disk checks no longer block the window, and each path is checked once per view.

Fixed during review

  • Audit must-fixes, all confirmed and fixed:
    • The repo is now checked before the worktree again, so a checkout restored mid-check is seen.
    • One view now holds at most two slots of the shared probe queue, with a single deadline for the whole pass, so pruning and chat checks keep their turns.
    • The usage-limit pass no longer reads workspaces or PRs it never used.
  • A comment overstated what an unmounted drive proves; it's corrected.

Accepted, not changed. A probe stuck on a stalled disk holds its queue slot until the disk answers. That's how the shared queue works for every caller, and before this change the same stall froze the whole window. When the pass deadline passes, the rest of that view reads "unverifiable": a deleted worktree may show its PR state for that one view, and nothing is closed.

Verified

  • Benchmark: head=4c4905a595b05592664a2ebac204cc7c7fc18fb0 gate=PASS. On the same Linux harness, base → head: native prepares 138,000 → 0, main-thread existsSync 12,000 → 0, median view pass 73.0 → 31.7 ms, GC 460 → 10 ms. The workload was 150 linked workers, each an 8-step follow-up chain, over 40 passes. Listeners: none; the main-process read path only.
  • Regression audit, blinded, on the final head: SAFE.
  • Perf scan, fresh reviewer, on the final head: clean (comment above).
  • Fresh reviewer, final batch: clean.
  • QA on Linux at 4c4905a:
    • A real bot added an item, started two real workers, linked them, and continued one with a follow-up.
    • The item view shows both workers, the follow-up chain as one worker.
    • After one worker's worktree was deleted, the view still renders and the other worker is unchanged.
    • The list and show reads return OK, and a work row for the deleted worktree closes as gone.
    • No errors in the log.

Before deleting a worktree:
02-item-workers-before-crop.png

After deleting worker A's worktree:
04-item-workers-after-crop.png

Seen, not changed by this PR: linking workers to an item with bot item link leaves the item at Planned. Only starting a worker with --item moves it to In progress.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8479d28e-ac8d-4e70-8370-4fbd70bdd59e
Commits

Reviewing files that changed from the base of the PR and between b2c40f9 and d5cd373.

Files selected for processing: 3

  • src/main/bots/bot-items-link-join.ts
  • src/main/bots/bot-work-runtime.ts
  • src/main/bots/bot-workspace-reads.ts
Files skipped from review as they are similar to previous changes: 1

  • src/main/bots/bot-items-link-join.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment thread src/main/bots/bot-work-runtime.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh reviewer, final head)

Verdict: clean for this diff. The change removes workspace reads from usage-limit reconciliation, deduplicates filesystem probes within each view batch, and avoids repeated compilation of three SQLite statements. It does not eliminate synchronous filesystem or SQLite execution from item views.

Reviewed e57f136e893..d5cd373ebc4292b336e66cc8ee4f716917dfdbd6. All six audited files matched the target commit. No files were edited.

Findings

No introduced performance regression was found.

The following pre-existing amplification remains:

  • Usage-limit reconciliation still reads unused reports and dock reasons. bot-items-link-join.ts:81 and line 107 execute with pullRequests: false; the caller consumes worker state. The diagnostic observed 100/1,000 report reads for 100/1,000 distinct local Tasks despite zero workspace reads. At two reconciliation passes/s, that is 200/2,000 report reads/s, associated report parsing, and two dock-reason batch queries/s on Electron main. This work predates the span.
  • Cross-repo workspace lineage repeats related-repo scanning and stamping. scoped-worktree-row-resolution.ts:146 shares the primary owner read, but its related-repo loop does not consult that shared map. For 750 linked workspaces in one connected component split evenly across two repos, one batch requests 750 related-repo scans and stamps 281,250 related rows. With 7,500 workspaces and the same two-repo shape, those counts become 7,500 and 28,125,000. Underlying scan caching may avoid Git execution; it does not remove the stamping loop. This is unchanged by the diff.

Work accounting

Let:

  • L = distinct linked Dispatch references; D = lineage records visited.
  • U = distinct resolved local workers; W = distinct checked workspace paths; R = distinct checked repo roots.
  • F = admitted calls/s; M = independent callers. Per-call prices below multiply by F × M.

The reference fleet has 100+ agents, 750+ worktrees and roughly 12 repos. Historical linked workers can exceed the live-agent population.

Changed work Trigger, population and bound Thread and fleet price
Skip workspace/PR reads during usage-limit reconciliation — bot-item-usage-limit-wait.ts:71, bot-items-link-join.ts:104 Existing status-snapshot/cut changes, worker/item changes while cuts or retry debt exist, and the existing minute tick. One reconciliation runs at a time; concurrent triggers coalesce. Workspace requests fall from at most U to zero. Main-process admission/projection; downstream catalog and filesystem work is avoided. For 100/1,000 distinct local workers, measured workspace calls were 100→0 / 1,000→0. No new trigger or timer.
Batch workspace-read owner — bot-workspace-reads.ts:12 One object and one additional Map per nonempty successful join. Existing repo-read sharing remains in worktrees; the new exists map holds at most one Boolean per distinct probed path. Main. Fixed additional container allocation per call; path entries grow with required distinct paths, not process lifetime. Owner lasts until the join settles.
Memoize existence probes — bot-work-runtime.ts:163, bot-workspace-reads.ts:17 Full item views, once per resolved local worker. Only locally owned, non-WSL paths reach these probes. Probe count falls from at most 2U to at most R + W, with further savings when paths coincide. Both positive and negative answers are cached. Synchronous filesystem work on main remains. At 750 distinct paths across 12 roots: 1,500→762 probes/batch; at two batches/s: 3,000→1,524 probes/s. Scaling paths alone to 7,500 gives ≤7,512 probes; roots alone to 120 gives ≤870; both give ≤7,620. For all workers sharing one root/path pair, measured probes were 2 at every tested population.
Pass through the existing scoped catalog cache — bot-work-runtime.ts:172 Full views pass reads.worktrees to the same workspace resolver. Standalone reads without a batch retain their previous behavior. Main projections plus existing catalog I/O. No additional catalog request, subprocess, remote call or broader lookup is introduced.
Cache follow-up query compilation — worker-follow-up-lineage.ts:34 Existing lineage walks and follow-up/start callers. One fixed, parameterized 611-byte SQL shape projects 33 columns. Query executions remain proportional to visited lineage records. Synchronous SQLite on the connection-owning thread—Electron main for the bot route. Indexed lookup remains unchanged. Repeated compilation becomes one cold compilation while resident in the existing 256-entry LRU.
Cache current-owner query compilation — worker-terminal-resource-store.ts:107 Existing lineage, observation, start/stop, release and ownership callers. One fixed 506-byte shape projects 26 columns; unique-owner index bounds matches to one row. Same thread and query count as base; compilation is reused. No write, WAL traffic, migration or lock-policy change.
Cache former-owner query compilation — worker-terminal-resource-store.ts:147 Existing owner-miss fallback and release callers. One fixed 681-byte shape. Indexed prior-owner lookup visits matching resources, orders them by update time, and returns one. Matching-history population remains the existing bound. Same synchronous SQLite execution and candidate sort as base; compilation is reused. No new history scan or JSON expansion.

For a forward lineage of 100 records with no owned resources, the actual resolver performed 100 owner, 100 former-owner and 100 follow-up calls. At 1,000 records, each became 1,000. Reading every reference with the shared lineage cache did not multiply those counts by L.

At two such passes/s, the three changed shapes still execute 600/6,000 queries/s at those populations. The improvement removes repeated preparation, not those executions. Shared-cache eviction or DDL can require recompilation; “three compilations” is a measured stable-workload result, not a universal lifetime guarantee.

Verification evidence

Read-only, in-memory diagnostics ran on this Mac using Node 26.5.0 and Python SQLite 3.54.1.

Diagnostic Observed result
Actual SyncDatabase/statement implementation, target query shapes versus wildcard controls matching the base diff; two unchanged passes At N=100: 600 executions in each variant, 600→3 native compilations. At N=1,000: 6,000 executions, 6,000→3 compilations.
Actual existsOnce, including negative answers Distinct paths: 112 / 1,120 / 762 / 7,620 probes for populations 100/1,000/750/7,500 with 12/120/12/120 roots. Shared root/path pair: 2 probes in every case.
Cache freshness A negative answer stayed stable within its batch; a new batch observed the changed answer. Unbatched calls checked every time.
Actual join with synthetic worker/database seams pullRequests: false produced zero workspace reads and retained all 100/1,000 worker results. Reports still loaded, as noted above.
Query plans at 100 and 1,000 rows Both projections used the same follow-up, unique-owner and prior-owner/primary-key indexes. Former-owner ordering retained its existing temporary B-tree. Returned projected row values matched the wildcard controls.
Statement freshness/schema control Reused statements observed an intervening update. An additive schema change preserved the explicit 33-field result.
Lineage width/order Forward and reverse reference order at 100/1,000 records returned the newest Dispatch and populated exactly 100/1,000 cache entries.

These establish operation counts and lookup structure. They are not packaged Electron timing measurements or full application tests.

Six-question disposition

Question Disposition
1. Unused work before the skip gate? Reviewed. The new gate precedes workerPr, eliminating its entire workspace path. Empty refs still return early. Unused report/reason reads remain pre-existing.
2. Ownership multiplies work? Reviewed. PR promises remain deduplicated by resolved Dispatch, reports by Task, repo reads by the existing scoped owner, and probes now by path. Independent RPCs retain independent batches; the diff adds no mounted-consumer multiplier.
3. Which thread/storage pays? Reviewed. Bot lineage SQLite and local existence checks still execute synchronously on main. Compilation counts improve; execution count, row decoding, locking and remaining filesystem latency are unchanged.
4. Growth and forward progress? Reviewed. New path state is bounded by distinct batch paths. Statement storage remains capped at 256. Lineage traversal retains its seen-set/cache progress. No cutoff, cursor, retry or output truncation is added.
5. Execution-host differences? Reviewed statically. Existing local-host and WSL guards remain before filesystem checks. Server workers still exit the PR path before workspace I/O. No new per-item SSH request or Windows subprocess. Windows/WSL/Linux/SSH execution was not measured.
6. Obsolete work stops/releases budget? Reviewed structurally. New maps have call-local ownership and no registry/listener reference after settlement. No timer or cancellation mechanism changes. Existing in-flight catalog reads remain uncancelled; the diff adds no new admission or persistent owner.

Regression-class dispositions

Touched class Disposition
Sync filesystem/SQLite on main Matched; reduced, not removed. Probe and compilation counts above establish the change.
Re-reading unchanged input Matched and improved within a batch. Repeated path probes collapse to one, including negative results. Cross-call reads remain.
Hot-path rescans No introduced amplification. Lineage traversal scope is unchanged; SQL plans remain indexed. Existing related-repo repetition is reported above.
Unbounded fan-out/queues No introduced fan-out. Existing Promise.all(unique.map(...)) and per-Dispatch promise sharing remain; the new gate removes downstream work.
Per-entity state outlives its entity Matched and disproved structurally for new state. Path entries belong to one batch; statement retention remains capped. No teardown callback or global path cache is added.
Hidden/unobserved work Improved. Background reconciliation now performs zero workspace/PR reads. Existing unused report reads remain.
Expensive work newly reachable past a gate No matching expansion. The added gate narrows reachability; existing callers retain the default full view.
Fixed polling / new steady-idle wakeups No added source. New idle wakeups are 0/s on main, renderer and daemon. Existing subscription and minute-tick cadence are unchanged.
Eager startup imports No new heavy dependency graph. The new 28-line module imports the scoped catalog module already value-imported by the base join. It adds no startup I/O or resource creation.

Limits

No Electron event-loop trace, slow-disk profile, heap/GC measurement, native-host run, or large migrated-profile benchmark was captured. Actual milliseconds of improvement and remaining stall duration are therefore unmeasured. The count reductions above do not establish that large item views are stall-free.

@brennanb2025 brennanb2025 changed the title Speed up bot item views with many linked workers Cut database and disk work when bot item views read linked workers Nov 23, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready (final head d5cd373)

Problem. On a bot with a long item history, opening its item views could freeze the window. Each view walked every linked worker's follow-up chain. Every step rebuilt three database lookups from scratch and made garbage, and every worker ran two blocking folder checks.

What users get. The same item views with far less main-thread work behind them. The lookups are built once per process, each folder is checked once per view instead of twice per worker, and the background usage-limit pass no longer checks folders at all.

How review shaped it.

  • SQL caching: clean in every pass.
  • Folder checks, async try: an async version went through four review passes. Each one surfaced a new P1: network-mount stalls, the shared probe queue, timing races that could wrongly close a work row, and the pass deadline cutting off large views.
  • Folder checks, what shipped: the coordinator chose to keep today's exact sync check and dedupe it per read pass instead. That keeps the base semantics, with no new failure modes.
  • Usage-limit pass: it now skips workspace reads, which came out of the audit.
  • Review thread: the one open thread was answered and resolved.

Known follow-up, not in this PR: the remaining folder checks are still sync on the main thread. Making them async needs a decision on what a slow, unreadable or stalled disk should mean for showing and closing bot work.

Verified on d5cd373

  • Benchmark: head=d5cd373ebc4292b336e66cc8ee4f716917dfdbd6 gate=PASS. Same Linux bench, base → head:
    • prepares 138,000 → 0
    • existsSync 12,000 → 6,040
    • median view pass 73.0 → 29.7 ms
    • GC 460 → 9 ms
    • The bench ran 150 linked workers, each an 8-step follow-up chain, over 40 passes. Listeners: none; the main-process read path only.
  • Regression audit, blinded: SAFE.
  • Perf scan, fresh reviewer: clean (comment above).
  • Fresh reviewer: clean.
  • CI: green.
  • QA on Linux:
    • A real bot added an item, started two real workers, linked them, and continued one with a follow-up.
    • The item view shows both workers, the follow-up chain as one.
    • With one worktree deleted, the view renders, the deleted worker's work row closes as gone, and the other stays live with its workspace read.
    • No errors in the log.

r3-crop.png

Seen, not changed by this PR: linking workers to an item with bot item link leaves the item at Planned; only starting a worker with --item moves it to In progress.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh reviewer, final head)

No performance regression introduced or amplified by this diff was found. The change reduces statement compilation and duplicate filesystem probes. It does not eliminate synchronous lineage reads or filesystem checks from item views.

Reviewed 15830ffd7e7af5cf1a592e1b55b3483f136bffc4..bfeac3c84ffb80d9f24c1a0e428814be3d9c62a0, using target-head code and the requested perf-scan/perf skills. No files were edited. The existing pnpm-lock.yaml modification was excluded.

Changed work and fleet pricing

Counts below are source-derived, not runtime measurements.

Definitions: U distinct linked Dispatch refs; K distinct resolved workers; W distinct eligible local worktree paths; R distinct eligible repository paths; D lineage records visited. Each independent view request owns its own batch. Multiply per-request counts by request frequency and independent consumers.

Changed work Trigger, population and bound Thread paying; reference-fleet price
Disable PR reads for usage-limit reconciliation, bot-item-usage-limit-wait.ts:73 Status-cut changes, startup snapshot, item/Dispatch changes while a cut or failed pass exists, and qualifying existing minute ticks. The gate runs before workerPr. Owning main/server event loop. Workspace lookups fall from up to K to 0 per pass; filesystem probes fall from up to 2K to 0. At 100/1,000 local workers, this removes up to 100/1,000 workspace calls and 200/2,000 probes per pass.
Conditional PR promise, bot-items-link-join.ts:108 One promise per distinct resolved worker, shared across refs resolving to that worker. Ordinary views retain the default PR behavior. Main/server JS. State-only reads retain O(U + K) bookkeeping but avoid workspace construction. No additional RPC, GitHub request, or subprocess.
Batch-scoped path cache, bot-work-runtime.ts:91 Ordinary item-view batches. Each exact repository/worktree key is checked once before any workspace await. Both true and false are cached: false ?? check() preserves false. Synchronous filesystem calls remain on main. Healthy local paths cost at most R + W probes, previously 2K. For 100 workers on 100 paths across 12 repositories: 200 → 112 probes/batch. At two such reads/s: 400 → 224 probes/s per independent reader.
Path-cache storage and lifetime, bot-items-link-join.ts:92 One new boolean map per batch; no process-lifetime registry. Entries are bounded by paths actually requested. Main heap: up to R + W entries. Covering 750 worktrees/12 repositories gives 762 entries/probes; combined 10× gives 7,620. Scaling only worktrees gives 7,512; only repositories gives 870. Released with the batch’s reader closure.
Cache follow-up statement, worker-follow-up-lineage.ts:42 Every existing follow-up lookup during lineage resolution, including item reads and existing follow-up/report consumers. Parameters and predicate are unchanged. Synchronous SQLite on the DB owner. Same executions and returned columns; compilation changes from once/call to once/cache residency. Follow-up lookup has an existing unique partial index.
Cache owner/former-owner statements, worker-terminal-resource-store.ts:115, 153 Existing lineage and ownership consumers. Former-owner lookup still occurs only after an owner miss in the lineage walk. Synchronous SQLite. Owner lookup uses its unique index; former-owner lookup uses the prior-owner index and resource primary key. Sorting still depends on resources matching that Dispatch, not every resource. No new write, transaction, index maintenance, or lock acquisition.

For the lineage-walk portion of a workload with 100 independent chains:

  • One Dispatch per chain, each owning its resource: 200 executions of the changed statements per batch, unchanged; cold compilation 200 → 2, warm compilation 0 while resident.
  • Ten Dispatches per chain, with the final Dispatch owning the transferred resource: 2,900 executions, unchanged; compilation 2,900 → 3 cold.
  • At 1,000 chains, those counts become 2,000 and 29,000 executions. The SQL-cache benefit remains two or three statement shapes.

These are not total item-read query counts; downstream worker projection performs additional existing reads. SyncDatabase bounds its cache to 256 statements, clears it before schema-changing exec, and may recompile after eviction. Cached statements retain no result snapshot.

Pre-existing amplification retained by this change

These observations are outside the span’s regression verdict, as specified by perf-scan.

  • Usage-limit reconciliation reads all linked Dispatch refs, including closed items, before filtering items to working/waiting. See bot-items-reads.ts:50 and bot-item-usage-limit-wait.ts:70–99. With 10,000 historical linked refs, a qualifying pass still submits 10,000 refs to worker resolution; at 100,000, it submits 100,000. At qualifying rate f, that is 10,000f/100,000f refs/s on the orchestration owner. The new PR gate removes workspace work, not this history-dependent admission.
  • State-only reads still fetch task results, parse reports, and read dock reasons before the consumer uses worker state. bot-items-link-join.ts:111 retains one report read/parse per distinct local task. At 100/1,000 tasks, that is 100/1,000 report reads per pass, with parsing proportional to their aggregate result bytes.
  • Ordinary views still synchronously probe each distinct eligible path on every independent batch. They also retain the existing managed-workspace resolution and repository-scan machinery. Sharing path checks does not cache complete workspace results or share work across requests.

Six scan questions

Question Disposition
1. Work before skip gate? Reviewed. The new PR gate precedes workspace construction. Empty refs still return early. Reports, reasons and lineage work remain before the state-only consumer’s narrower use, as noted above.
2. Ownership multiplying work? Reviewed. Existing refs, workers and tasks retain their deduplication. Filesystem checks now share batch ownership. Independent requests still repeat work; no new owner, subscription, or consumer multiplier was added.
3. Thread and storage layer? Reviewed structurally. Both SQLite and existsSync remain synchronous on their owning event loop. Explicit projections enable the existing statement cache without widening results or changing lookup predicates. Latency, CPU and contention were not measured.
4. Growth and forward progress? Reviewed. Path storage grows with distinct paths in one batch. Lineage traversal has cycle detection and a batch lineage cache, but work still grows with lineage/history size. Existing usage-limit passes serialize and coalesce triggers; failure waits for a later trigger instead of retrying in a tight loop.
5. Execution host effects? Reviewed in source. SSH-owned repositories and WSL UNC paths still skip local deletion probes. Server workers still return before workspace PR resolution. Existing remote routing is unchanged. No Windows/WSL/Linux or live SSH measurements were performed.
6. Obsolete work and release? Reviewed structurally. New maps are batch-local; no persistent listener, timer, queue or handle was added. Existing in-flight requests are not newly cancellable. The existing repository scan has a five-second result fallback, which does not itself prove underlying I/O termination.

Regression-class dispositions

All recurring classes were screened. The classes intersecting this diff or its immediate production path are:

Class Disposition
Sync filesystem/SQLite on main Matched; reduced probes and compilation, unchanged synchronous execution placement. No introduced amplification.
Re-reading unchanged input Matched; exact path checks deduplicated within a batch, including negative answers. Cross-batch repetition remains pre-existing.
Expensive code past a gate Checked; this gate tightens admission. Default item-view behavior is preserved.
Hot-path rescans / collection fanout Matched in lineage and workspace resolution; execution populations are unchanged, with fewer path probes.
Per-instance / hidden-owner work Checked; no new mounted owner or subscription. Background usage-limit reconciliation loses workspace work.
Unbounded fanout / queues Existing Promise.all(unique.map(...)) remains. This change adds no admissions and reduces work admitted beneath it.
Per-entity state outliving its owner Matched new cache; scoped to its batch. Statement retention stays under the existing 256-entry database cache.
Eager startup imports Checked; the column-list module is already imported by DB lookup/store modules. No SDK, adapter or additional startup I/O.
Fixed-cadence polling No matching addition or loosened cadence.
New steady-idle wakeups Source delta: 0/s on main, renderer and daemon. No scheduling source was added; idle CPU was not measured.

Store identity churn, broad selectors, streaming rewrites, new publications/snapshots, whole-file writes and per-item subprocess additions have no matching changed code.

Verification and limits

The five-file oxlint performance audit completed successfully and emitted five warnings on unchanged lines: four await-in-loop warnings and one map-spread warning. Serialization in usage-limit reconciliation preserves its existing one-pass-at-a-time behavior; the warnings do not establish an introduced regression.

The named bot-items-link-join.test.ts and bot-item-usage-limit-wait.test.ts checks did not start: the read-only sandbox prevented tc-gate from opening its admission files. Existing assertions were inspected, not counted as passing. The diff adds no deterministic fleet-scale contract for these changes.

No packaged app, large migrated profile, event-loop trace, query-plan execution, or N/10N runtime workload was exercised. Thus clean means no source-proven introduced P0/P1, not measured proof that the reported stalls are resolved.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready (final head bfeac3c)

Problem. On a bot with a long item history, opening its item views could freeze the window. Each view walked every linked worker's follow-up chain. Every step rebuilt three database lookups from scratch and made garbage, and every worker ran two blocking folder checks.

What users get. The same item views with far less main-thread work behind them:

  • The lookups are built once per process.
  • An item view checks each folder once instead of twice per worker.
  • The background usage-limit pass no longer checks folders at all.

How review shaped it

  • SQL caching: clean in every pass.
  • Async folder checks: tried, but each round surfaced a new P1: network-mount stalls, the shared probe queue, timing races that could wrongly close a work row, and the probe deadline cutting off large views. The coordinator chose to keep today's exact sync check and dedupe it per item-view pass instead.
  • The work-record path, which can close rows, still checks fresh every time.
  • Main was merged in.
  • Two automated review threads, both answered:
    • A stale cached repo answer: the memo is now limited to item views, where 'gone' never closes anything.
    • Counting EACCES/EIO as present: reverted, because that sends unreadable worktrees into a full workspace read that can repeat git remote setup, work today's check never does.

Known follow-up, not in this PR. The remaining folder checks are still sync on the main thread, and an unreadable worktree still counts as gone, as it does today. Changing either needs a decision on what a slow, unreadable or stalled disk means for bot work.

Verified on bfeac3c

  • Benchmark: head=bfeac3c84ffb80d9f24c1a0e428814be3d9c62a0 gate=PASS. Same Linux bench, base → head:
    • prepares 138,000 → 0
    • sync fs 12,000 → 6,040
    • median view pass 73.0 → 29.6 ms
    • GC 460 → 4 ms
    • The bench ran 150 linked workers × 8-step follow-up chains, over 40 passes. Listeners: none; the main-process read path only.
  • Regression audit, blinded and scoped: SAFE.
  • Perf scan, fresh reviewer: clean (comment above).
  • Fresh reviewer: clean.
  • Gate and CI: green.
  • QA on Linux with a real bot:
    • The bot created an item, started two real workers, linked them, and continued one with a follow-up.
    • The item view shows both workers, the follow-up chain as one, with no errors.
    • With one worktree deleted, only that worker's work row closes as gone, and the other stays live with its workspace read.
    • No errors in the log.

r5-crop.png

Seen, not changed by this PR: linking workers with bot item link leaves the item at Planned; only starting a worker with --item moves it to In progress.

@brennanb2025
brennanb2025 merged commit 26aff60 into main Nov 23, 2026
56 of 57 checks passed
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