You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(journal): a window of a chat's newest turns reads only the sends it can hold - #47878
When a bot does something on someone's behalf (sends a request, posts in Slack, adds an item), Orca first checks who the bot's current turn is working for. To check, it reads the chat's most recent turns. That read also looked through every message the chat had ever sent to find the few in those recent turns. So the longer a chat ran, the slower every one of those actions got. Now it looks only at the messages in those recent turns, plus any still waiting for an answer.
What Changed
readJournalDomainOperationWindow with latestTurns and no other anchor (the read behind whom a bot's turn acts for) used to load every current send in the chat (sendHeads(scope)): each one with three position lookups and JSON extraction, before keeping the few the window holds.
It now reads, each by an existing index:
every send still handed over and unanswered (pending, or unknown and not recovered: journal_submission_recovery, whose condition is the code's own definition of unanswered), wherever it sits, since those widen the window as before;
the sends placed in the window (placedSends). Those lookups list the window's visible non-tool rows through a new partial index, journal_items_send_place, whose condition is the same row filter the send position lookups use, so a turn's tool calls and diffs are never listed.
When a send the window must hold (one still unanswered, or one sharing a provider id or queued card with it) sits further back than the newest turns, it pins the window back to it, often to the start of the chat. The window then takes the single whole read it took before, which is cheaper than reading that long stretch by index. Sends recovered in doubt after a crash are never unanswered, so they are read only when the window holds them.
Sends sharing a provider id or queued card are held together. That family is now walked once, through a map from each id to its sends; before, it was rescanned on every pass, which was quadratic for a long chain. The indexed path also has a fixed bound: every lookup it runs (the unsettled sends, the sends placed in the window, and their families) lists at most 65 sends (RECENT_FAMILY_CAP + 1), in index order. A full lookup takes the whole read, decided before the window's start is computed when it is the unsettled sends. Before placing sends, it counts the window's rows a send can sit on, stopping at 1025, and takes the whole read past 1024 (RECENT_ROW_CAP), so a turn that wrote thousands of rows is never listed. Lookups run one at a time and stop at the first full one. It takes the whole read as soon as a family runs older than the window or past that cap, or the window must widen, so it never walks a long stretch or a large family. This reuses the read path a window through anchored turns already takes. Windows anchored any other way (operation ids, item ids, turn ids, the latest ended turn, a sequence or time) keep the whole read. The new index is CREATE INDEX IF NOT EXISTS, with no schema version change. It is built once per profile journal database after upgrade, on the journal writer worker before the journal is ready (off the main thread). Measured: 29 ms at 100k rows, 350 ms at 1M rows (warm cache).
Why
Every bot request, Slack post, reaction, Linear or Google write and item add reads whom the bot's newest turn acts for. In a long-lived bot chat that read grew with every send the chat had ever made, and it is about to gain another caller (bot item add, #47789). Bounding the shared read fixes all callers at once. Bounding each caller separately would leave the others slow.
N/A: no user-visible change; reads return the same window.
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
journal-domain-operation-window.performance.test.ts gains a perf contract over the newest 8 turns:
a 50-turn chat and a 500-turn chat examine the same number of rows, and return those 9 turns (with the margin turn) and their sends. With the change reverted, 527 rows against 77;
with every older send recovered in doubt (41 and 491 of them), the two still examine the same rows. With the broader unsettled index, 1054 against 154;
an old unanswered send is kept, and the read then costs the whole read plus the 1 row that found it (2000 vs 1999). Without the fallback, 3998;
a chain of sends linked alternately by provider id and queued card is held in linear work: 798 and 7998 field reads at 100 and 1000 sends, against 29702 and 2997002 with the old loop;
a family running back through the whole chat costs a fixed number of rows over the whole read, at 50 and at 500 sends (31 with the newest send unanswered, 46 with it answered), and returns the same sends. Without the early stop, 198 and 1998;
one queued card shared by every send costs a fixed number of rows over the whole read at 200 and 500 sends (67 with the newest send unanswered, 110 with it answered). Without the cap, 201 and 501;
one answering turn named by every send, and unsettled sends piled up before the newest turns, each cost a fixed 74 and 65 rows over the whole read at 200 and 500 sends. Without the lookup limits, 218/518 and 190/490;
a newest turn that wrote 2000 messages runs no placement lookups and returns the same nine sends as a window with none. Without the row cap, it runs all three;
the budgets are exact: 72 rows at 50 and at 500 turns; with an old unanswered send, 2000 rows against the whole read's 1999 (that send decides the whole read before any send family is read), and 74 for a window of its anchors alone, which that send never pins back (529 before);
a last turn with 1000 tool calls reads the same sends as one with none, and every stretch a send read lists keys on journal_items_send_place (checked with EXPLAIN QUERY PLAN on the statements the read runs). With the old row index, that check fails.
pnpm check:changed passes (macOS).
Performance
Fixes a read that grew with chat history. For a fixed newest turn, the rows examined are now constant in the number of earlier settled or recovered sends (50 vs 500 turns: equal). When an unanswered send pins the window far back, the read is the whole read it was before, plus the index read that found that send. Within the window, the send lookups list only the window's visible non-tool rows, so a tool-heavy turn adds nothing. One index build per profile journal database after upgrade, on the writer worker and linear in its rows (29 ms per 100k rows measured); about 38 bytes per indexed row afterwards.
Risk
Level: Medium
This is a core journal read with many callers (bot acting-turn reads, first submitted prompt, fork reads, memory sources, accepted-unopened). The risk is a window that misses a send the whole read would have kept. That would change which turn a reading attributes to whom. The bounded path keeps every send placed in the window or sharing a provider id or queued card with one, and every unsettled send, which is the set the whole read keeps. Revert is a plain revert.
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
Cross-platform, SSH, mobile: shared journal SQL only. Backwards compatible: one added partial index (IF NOT EXISTS), no data change; older builds ignore it.
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)
… it can hold
Reading whom a bot's newest turn acts for opens a window of the chat's
newest turns. That window read every saved send in the chat to find the
ones it holds, so every bot request, Slack post and item add cost more the
longer the chat ran. It now reads the sends placed in the window and the
ones still unanswered, each by an existing index, as a window through
anchored turns already does. Other windows keep the whole read.
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.
No actionable comments were generated in the recent review.
Walkthrough
Newest-turn-only operation windows use indexed send selection and start with pending sends and unrecovered unknown sends. Bounded windows use operation sends, while other windows use all send heads. If a relevant send predates the earliest anchor in a recent window, the reader loads all send heads. Performance tests compare work and results across chat sizes, tool-call counts, recovered sends, and an unanswered send.
Merge Risk: Low · up to bf9f3
This speeds up reads of a chat's newest turns by looking up only the sends the window can hold. Remaining concerns are minor: the performance test could assert exact row counts, and an old pending send outside the window can still trigger the slower full read. Merging looks low risk; the author should consider tightening the test and the fallback check.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title states the main change: a window of a chat's newest turns now reads only the sends it can hold. This matches the raw summary and the objectives, which describe bounding send lookups for late…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description follows the repository template and covers ELI5, What Changed, Why, Testing, Performance, and Risk with a Medium level. Those sections give a reviewer the mechanism, the tradeoffs, and…
Full details: Title check
Explanation
The title states the main change: a window of a chat's newest turns now reads only the sends it can hold. This matches the raw summary and the objectives, which describe bounding send lookups for latestTurns-only windows via the new journal_items_send_place index. The title is specific and scoped. It is a single sentence of 15 words and uses the conventional perf(journal) prefix.
Full details: Description check
Explanation
The description follows the repository template and covers ELI5, What Changed, Why, Testing, Performance, and Risk with a Medium level. Those sections give a reviewer the mechanism, the tradeoffs, and the rollback path. The Linked Issue section names only an internal bot item and a follow-up issue (#47789), not a public GitHub issue, so it does not fully meet the template rule that an actual issue must be linked. The Visual Proof section is marked N/A with a reason. The AI Disclosure section is empty. The Testing section checks the manual-testing box while the description also says manual testing was not reported in the objectives, so the checkboxes conflict. The 'Fixes #' line is left blank. The description is mostly complete, so the check passes, but the linked-issue gap and the conflicting manual-testing claim should be fixed before merge.
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.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.
…recovered sends stay unread
- Only sends still unanswered (pending, or unknown and not recovered) seed the
newest-turns window, by the index that keeps exactly those.
- An unanswered send older than the newest turns pins the window back to it;
the window then takes the single whole read it took before.
- The perf contract also holds with old recovered sends, and with an old
unanswered send costs no more than the whole read.
- The window's send lookups read only rows a send can sit on, by a new partial
index over visible rows that are not tool calls or diffs (created like the
other window indexes: IF NOT EXISTS, no version change).
- An unanswered send older than the newest turns by the head it was sent at
also pins the window to the whole read.
- The perf contract holds with 1,000 tool calls in the newest turn.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
Verdict: clean for this diff. No remaining introduced P0/P1 performance finding. The earlier P1 is fixed: non-recent reads do zero fallback-position work, and recent reads use a short-circuiting predicate without building a positions array. The normal newest-turn path replaces the full saved-send scan with indexed window reads. The new index has a real, history-sized upgrade cost; it runs on the writer worker, normally during profile startup, once for the shared profile database, before journal readiness.
Comparison: 4667e7b60c3..bf9f3a802d4c4180e5a4f6c37670775e1b518e97. Checkout HEAD was verified as the requested head. All three changed production files and the performance contract were read, along with production consumers, storage owners, migration routing and write paths. perf-surface-detect 4667e7b60c3..bf9f3a802d4c4180e5a4f6c37670775e1b518e97 -C /Users/brennanbenson/.cache/orca-jobs/pr47878 returned []. This is the detector's literal result: its path rules miss this migration/index file and these journal hot paths. Manual coverage below includes both.
Earlier finding: verified fixed
At src/main/native-chat/agent-session-journal/journal-domain-operation-window.ts:119, recent && reachesBefore(...) gates the entire fallback check. The helper at journal-operation-window-sends.ts:183 first compares the already-computed earliest position, then uses nested .some() calls. Each send has at most three positions. It allocates no history-sized result and stops at the first qualifying position. For non-recent reads, neither helper invocation nor its argument evaluation happens.
Standalone diagnostics imported the actual production implementations and SQLite wrapper, populated the production schema, and compared base, the earlier defective implementation (9c62ea0bf697fce0cc53439c565103bf00e54744), and this head on the same workload. Base snapshots were checked against git show 4667e7b60c3:<path> after resolving imports. The earlier domain implementation uses the same otherwise-unchanged send/index plumbing; the inter-head diff is the fallback replacement and its helper.
This head: unused callbacks / values / fallback predicate visits
Output control
10,000 sends
Item-ID, operation-ID without bounded turns, sequence and time; each run separately
10,000 / 40,000 per read
0 / 0 / 0
Same send IDs and item counts as base
100,000 sends
Same four controls
100,000 / 400,000 per read
0 / 0 / 0
Same send IDs and item counts as base
10,000 and 100,000 sends
Newest turn-ID and bounded operation-ID, each separately
Earlier pass demonstrated the defect
0 / 0 / 0
Same send IDs and item counts as base
10,000 and 100,000 sends
Latest eight turns, newest send pending
Not used as the negative control
No array; one outer fallback predicate visit
Nine sends and 28 items at both sizes
The positive pending-send control establishes that the predicate instrumentation can see an admitted check. The older implementation fails the zero-allocation check at N and 10N. At 100 active watches × one admitted read/s × 10,000 sends, the previous finding added 1m callbacks/temporary arrays and up to 4m copied numbers/s; at 100,000 sends, 10m and 40m/s. This head adds zero of that work to non-recent reads. The pre-existing full-send selector read on those paths remains; it is priced below rather than credited to this fix.
These are operation/allocation counts, not inferred UI latency, CPU milliseconds or retained heap measurements. The committed performance contract counts examined SQL rows and would not itself catch the removed JS-only allocation; the external diagnostic does. No source fix was made by this review.
Production trigger and owner census
journalSqlReads.operationWindow → reader-pool point request → readJournalSqlPoint → readJournalDomainConsumer → readJournalDomainOperationWindow. SQL, selector JSON extraction and result construction run synchronously on a reader worker, in one WAL read snapshot. Electron hosts readers through its reader utility process; the daemon uses worker threads. The existing pool has four reader slots, with two admitted/unconsumed reads per reader and separate reply-byte credit. This bounds concurrent execution/admitted replies, not total queued demand. There is no worker per saved chat.
The optimized newest-turn consumer is bots/bot-acting-turn-read.ts:13, reached by bot-recipient attribution and the bot-turn answered-request fallback. It starts with eight turns and multiplies the window by four until attribution succeeds or history is complete. It is event/request driven, including background bots; pane visibility is not its admission condition. Unoptimized consumers include bots/bot-run-turn-watch.ts:71, bots/bot-group-latest.ts:34, bot chat/group reads and structured turn context. The run watcher coalesces journal changes with 300 ms trailing delay / 2 s maximum wait, also wakes at turn completion, and disposes its coalescer and subscriptions in finally.
Pricing notation: S = current sends in the addressed chat, C = saved chats/profile, U = pending or unknown/unrecovered current sends, F = distinct related sends reached through shared provider/card keys, W = eligible non-tool placement rows in the held stretches, T = tool/diff rows there, K = held sends, E = backward extensions, J = all stored item rows across the database, P = rows qualifying for the new index. History N=10,000 sends/chat and 10N=100,000; C=300→3,000 is a separate axis. A=100→1,000 active consumers and read rate r are separate again. Worktrees, terminals, refs and remotes do not each own a copy of this journal workload.
New or changed work
Trigger / owner / lifetime
Population, bound and price at N and 10N
Recent-path admission and seed selection (journal-domain-operation-window.ts:90, journal-operation-window-sends.ts:194,208)
Once per operation-window request; reader worker; local values
Fixed number of anchor-property/length checks. Recent reads seed U through journal_submission_recovery; other modes keep their previous seed route. With U=0 and the requested eight-turn shape fixed, S=10k→100k does not increase returned selectors: 54→54, versus base 10k→100k. Total queries 37→37, examined application rows 91→91, output nine sends/28 items. B-tree seek cost still depends on shared database size; this is a fixed result/operation population, not literally constant time.
Unsettled seed and relationship closure (journal-operation-window-sends.ts:221,101)
Once per recent read; reader worker; request-local arrays/maps
U indexed seed rows, each with at most three item-key probes and a fixed number of selector-field extractions (their JSON bytes are priced separately below). Recovery excludes old unknown,recovered=1 rows before materialization: changing all but the newest ten sends to recovered unknown leaves 54 selectors/91 examined rows at both history sizes. Closure queries at most two indexed batches/frontier and admits only fresh message IDs. Depth is bounded by distinct reachable sends; no retry restarts without adding IDs. More pending sends or genuinely shared families increase the required attribution population, not unrelated settled history. For an unchanged snapshot, a provider/card key first loads its entire family; its fresh members can repeat that key on the next frontier, then it is exhausted. Per closure, relationship-row results are bounded by four times the distinct reachable population (two key types, each queried in at most two frontiers), plus initial selectors. Final sorting is O((U+F) log(U+F)); no retained global graph/cache is added.
Anchor reuse and fallback predicate (journal-domain-operation-window.ts:98,119; journal-operation-window-sends.ts:183)
Once/read; reader worker; local values
Anchor resolution still runs once. Non-recent: zero fallback visits at 10k/100k. Recent: earliest-position short circuit, else at most U+F outer visits and three inner position checks/send, O(1) additional result storage. Newest pending control: 1→1 outer visit. If a seed/related send reaches before the newest anchors, one full-send query replaces repeated long indexed discovery. This is an admission decision over relevant seeds, not all S on every read.
Initial indexed window and each backward extension; reader worker; SQLite lists/local results
Four indexed send queries/stretch. Three enumerate 3W placement keys rather than 3(W+T); the fourth uses submitted-sequence range. At T=1k→10k, added tool keys in these three lists stay 0→0. Plans confirm journal_items_send_place plus item/provider/answered-turn/submitted send indexes. Each returned selector still pays up to three keyed item probes, JSON field extraction and ordinal sorting. Window width, rather than old settled history, sets its population.
Extension and accumulated-send handling (journal-domain-operation-window.ts:126,132,142)
Held sends reach before current start; reader worker; local sets/maps
Start strictly decreases and newly queried stretches are disjoint; E is bounded by the finite distinct lower send positions, at most four/send. The existing map rebuild/sort and kept-send scans can revisit the accumulated K each extension: a conservative O(E·K log K) for accumulated sorting, plus kept-send relationship passes. This mechanism already serves bounded operation windows. Recent mode now uses it to retrieve the same attribution closure without first scanning S. It does not impose an arbitrary history cutoff or discard accepted sends. Ordinary measured case needs one indexed stretch at both sizes.
Old-unanswered fallback
Recent read with genuinely unresolved history; reader worker; request-local full snapshot
At S=10k, both base and target keep 10k sends/30k items, approximately 9.18 MB decoded JSON in this synthetic shape. Target selects 10,003 send rows versus base 10,000: three preparatory seed/family rows plus the necessary full read; queries 20,010 versus 20,007. With fixed U=1, added preparation stays constant as S grows. At S=100k both fail at the pre-existing argument-spread limit before output; see limitations. Large U/F is output-dependent and must not be described as constant work.
Final payloads and reply
Once/window result; reader worker, existing clone/reply path to main/consumer
K point reads/decodes for held submission payloads, plus item sizing and payload passes. Normal recent decode bytes 8,493→8,640 only because identifiers lengthen; nine sends/28 items at both sizes. Existing 64 MiB reply limit bounds successful serialized replies, not all intermediate selectors or SQLite visits. turnShape suppresses tool decoding, but its forced visible-position index still visits tool rows in the range: approximately two T-dependent SQL passes remain. This was already present in base and is not removed by the new placement index.
Partial-index construction (database/journal-submission-window-indexes.ts:20)
First writable open of the profile database missing the index; writer worker; persistent
J predicate visits + P index keys, conservatively O(J + P log P) construction CPU; O(P) persistent index storage, WAL and potentially temporary sort storage. Whole database, including inactive chats and epochs, participates. J=100k→1m and P=10k→100k were measured below. Fleet J/P arithmetic and upgrade routing are also below.
Partial-index maintenance
Qualifying item insert/update/hide/delete; writer worker; persistent entry per qualifying row
One added B-tree entry per eligible row; key/predicate-changing updates can delete+insert, each O(log P). Tools/diffs have zero entries, though predicate/DDL maintenance remains SQLite work. At 100→1,000 qualifying metadata writes/s, up to 200→2,000 entry mutations/s (delete+insert case), not P-row rewrites. Stable message-tail/payload updates change no indexed/predicate columns (journal-domain-text-snapshot.ts, journal-text-tail.ts); there is no new per-delta full-history write, transaction/fsync cadence or checkpoint loop. Necessary write cost for the selective read index.
Added performance contract
Explicit test invocation only
Fixture work scales with declared turns/tools; no shipped runtime cost. Source-inspected controls cover 50/500 turns, 0/1,000 tools, recovered history and an old unanswered send. Not run as tests in this review.
Fleet rate example, holding A=100 and r=1 read/s after existing admission/coalescing: normal latest-eight reads now return 5,400 send-selector rows/s, against 1m/s at S=10k or 10m/s at S=100k in base. At A=1,000, multiply each by ten. Increasing C from 300 to 3,000 with A fixed adds no addressed-chat selector population, but increases B-tree size and index-upgrade work. These are workload prices, not measured fleet traffic or CPU budgets. No new idle scheduling source exists: attributable main/renderer/daemon wakeups stay 0→0/s by source inspection; this is not a whole-app idle trace.
Payload bytes are a separate axis from history length. sendHeads reads payload_json for two guarded JSON selector expressions (queued card and answered turn); a fixed field count does not bound the size of their input. With 54 selector results and average submission JSON of 1 KiB→10 KiB, selected JSON input totals approximately 54 KiB→540 KiB/read, before repeated SQLite inspections or cache reuse. At 100 reads/s that is 5.27→52.7 MiB/s of modeled selected payload input, not measured physical I/O. Base selects S such payloads instead. Selected submission decoding additionally follows K and its actual byte sum. Placement lists hold three W-sized key populations (key width scales their bytes), and request-local selector/maps hold O(U+F+K) objects; the reply byte cap is not a cap on those intermediate allocations. No retained-heap byte claim is made.
New partial index: upgrade timing, storage and execution point
migrateJournalDomainSchema invokes ensureJournalSubmissionWindowIndexes at database/journal-domain-migrations.ts:29, even when user_version already equals 2. The new partial index is additive, with CREATE INDEX IF NOT EXISTS; it is not tied to opening each chat or incrementing the schema version.
Production route:
For an existing saved-chat profile, runtime/agent-session/records/local-agent-session-record-store-startup-open.ts:34 starts the shared store open alongside other startup work. Profiles without saved chats defer it.
database/journal-sql-database.ts:72 creates a JournalSqlOwner and awaits its ready message. That owner starts the journal writer worker.
journal-sql-worker-entry.ts:71 initializes/opens the profile's agent-session-domain.db. database/journal-domain-database.ts:144 synchronously calls the migration. Existing-database initialization opens the destination for older-write absorption first; that open can build the index. The steady-state open then sees it already present.
Only afterward does the writer announce ready and the shared reader pool become available. The database holds all chats/epochs, so there is one index build per profile database, not C builds. Remote journals pay on their owning host; there is no per-item SSH round trip.
Answer: off Electron main, on the writer worker; normally at startup for a large existing saved-chat profile, before journal readiness. If shared-store creation was deferred, first initialization pays then. It is not a first-open migration for each chat. Main can continue unrelated startup work, but saved-chat restoration and first journal use wait for this synchronous construction. A slower machine or disk can lengthen that wait.
This pass measured the exact new CREATE INDEX IF NOT EXISTS against the actual production journal_items table DDL, file-backed WAL, synchronous=NORMAL, 300 synthetic chat IDs, 90% excluded tool rows/10% eligible rows and approximately 1 KiB payloads. An existing populated file was checkpointed, closed and reopened without the index. The other three submission indexes predate this diff and are outside the isolated DDL timing. Host: Darwin arm64, Node v26.5.0, SQLite 3.54.1. No Electron or real account/profile was used.
Existing item rows / qualifying keys
Existing DB bytes
CREATE duration
Added logical index bytes
WAL bytes after CREATE
Repeating existing-index CREATE
100,000 / 10,000
140,492,800
29.30 ms
364,544
370,832
0.0122 ms
1,000,000 / 100,000
1,405,648,896
350.11 ms
3,784,704
3,811,032
0.0142 ms
Single runs with a warm OS cache, not physical cold-storage bounds or total application startup times. Reopening does not evict filesystem cache. Close/checkpoint time is outside CREATE timing; wal_autocheckpoint=0 isolated the build's WAL. Total journal bytes are not exact read bytes: construction evaluates columns/predicate for every table row, but need not read/parse every overflow payload/blob. The new index expression itself extracts no JSON.
Fleet model: C=300 chats × S=10k sends × ten items/send gives J=30m rows; with three eligible rows/send, P=9m keys. Increasing history alone tenfold gives J=300m/P=90m; increasing chats alone to 3,000 gives the same totals. At the measured short-key density (~38 B/key), the new logical index alone is approximately 0.34 GB→3.4 GB, plus WAL/checkpoint traffic and possible sort space. Real longer IDs widen keys. This model's 30% eligible proportion differs from the isolated timing's 10%; no millisecond extrapolation from those runs is claimed. On a tens-of-GB existing journal this is a full-table upgrade pass, not a tiny schema lookup.
Construction acquires SQLite's write transaction and may wait up to the existing 5,000 ms busy timeout on a competing writer. Normal ownership is one writer/profile, with readers starting afterward. Atomic successful publication means later opens do schema checks rather than rebuilding. An interrupted/failed build may retry the entire pass on a later open; there is no incremental migration cursor. The initialization absorption open and later steady open can also retry a failed first attempt. No new retry timer/loop is added. This is necessary, proportional one-time index materialization, with measured persistent output; it is not dismissed as a small history-independent cost and is not a confirmed repeated-waste regression.
All six scan questions
Question
Disposition and evidence
1. Unused work before the skip gate?
Reviewed; earlier P1 fixed. Negative controls at N/10N perform zero fallback work and fail on the earlier implementation. Positive pending control admits one predicate visit. Recent seed filtering occurs in the recovery index before history selector construction; payloads decode only for held sends.
2. Ownership multiplies/recreates work?
Reviewed with bounds. One shared profile writer/four reader slots, request-scoped selectors, no new watcher/effect/client or per-mounted-chat I/O. A×r multiplies requests; inactive C increases database size, not per-request send count. Existing event consumers and teardown were traced.
3. Which thread/storage layer pays?
Reviewed with routing, plans, counts and isolated DDL timing. Reader workers pay synchronous reads/JSON/SQL sorting; writer worker pays construction/index maintenance; main receives existing reply objects. Parameterized finite query shapes use the existing 256-entry statement cache. Reviewed lock timeout, WAL, startup-ready dependency and stable text-write bypass. No added main-thread SQLite scan.
4. What grows; does another attempt advance?
Reviewed with independent axes. S, C, U/F, W/T, E, J/P and A/r priced above. New stretches strictly move backward and do not overlap; family closure admits fresh IDs; existing caller widens 8→32→128 until completion. Index success persists; interrupted builds restart rather than resume. No newly introduced cutoff/data truncation. Old full-read/spread limit is explicitly retained below.
5. Execution host changes?
Source-reviewed; runtime evidence is Mac only. Work stays on the journal-owning host. No new process launch, host probe, WSL discovery, filesystem-path branch or per-item network/RPC round trip. Windows/Linux/slow-disk and cold-cache timing were not measured; no Mac timing is asserted for those hosts.
6. Obsolete work stops/releases its budget?
Reviewed with owner/resource bounds. New arrays/maps are request-local; index is intentionally persistent and deletion/updates maintain membership. No new timer, subscription, async queue or retained per-chat registry. Existing watch cleanup and shared reader/database ownership remain. Already-admitted synchronous reads/DDL are not interrupted by closing a pane; no new cancellation contract is claimed. Queue demand can still exceed four-reader throughput; this change reduces ordinary read work and adds no admission source.
Recurring-regression-class screen
Every row of the supplied table was screened. Matching classes have evidence/dispositions below; nonmatches are included to make the screen explicit.
Recurring class
Disposition
No-op store write returns new identities
No matching code. No store action changes.
Whole keyed map/settings selected, one entry used
No matching code. No renderer selector changes.
Per-row derivation over whole collection/write
Matched and disproved for introduced work. Recent selectors 54→54 for S=10k→100k; other modes' S-wide selectors predate this diff. No new fallback traversal on them.
Streaming reprocesses whole message
Matched storage surface; no introduced whole-message stream rewrite. Index excludes tools/diffs; stable text-tail/payload writes do not update its columns. Metadata index maintenance priced above.
Fixed-cadence poll/loop never settles
No new scheduler. Existing watcher is coalesced/event-driven; relationship/window loops have monotone progress.
New steady-idle wakeups
No matching added scheduling. Incremental wakeups/s main 0→0, renderer 0→0, daemon 0→0 by source.
Expensive code newly reachable past a gate
Matched new indexed entry route, disproved as waste. Latest-turn requests now reach targeted send/window queries, priced at 54 selector rows plus 37 total queries instead of 10k/100k selector rows. No suspended feature/environment gate removed. Migration is newly reached on existing DB open and separately measured/priced, not hidden behind the empty detector output.
Hidden/unfocused/unheard owners keep working
Matched background bot consumers; necessary existing work. No new hidden-owner trigger; non-recent fallback work is zero and background newest reads use the same indexed bounds.
Every mounted instance loads active-only data
No matching code. No component/effect or new per-pane I/O.
Subprocess per item/event
No matching code. No added subprocess/host probe.
Sync fs/SQLite on Electron main
Matched SQLite mechanism, actual thread disproves main scan. Reader SQL and writer DDL run on their workers. Main clone/consumer path is existing.
Re-reading unchanged input
Matched read path; no amplified repeated history read. Same request cadence; fresh WAL snapshot is needed for attribution. Ordinary recent selector population shrinks, old recovery rows excluded; non-recent history scan remains pre-existing.
Update published when nothing changed
No matching code. No new sequence/version/notify mutation.
One change published as whole snapshot/N notices
Matched window result, no new publication fanout. Same held output, nine sends/28 items in normal controls; no added publish/emit. Reply sizing remains existing.
Whole-file rewrite/change
No matching rewrite. Added B-tree mutations/WAL are incremental; no whole-journal serialize/write added.
Per-entity state outlives entity
No new registry. Request maps release with request. Persistent index membership follows row update/delete and has one owner/database.
Hot-path rescans
Matched; fixed/improved where changed. Unused S-position allocation removed; three placement lists exclude T by index. Existing accumulated-set scans, final visible-position tool scans and non-recent full-send reads are disclosed, not claimed fixed.
Unbounded fanout/queues
No new asynchronous fanout/admission. Family queries are sequential indexed batches; frontier adds fresh IDs. Existing four-reader/eight-admitted budget does not bound all waiters, but is not loosened by this diff.
Eager startup imports
Matched small SQL-constant module only. It is already imported by the migration graph; added value exports are SQL strings, no new SDK, adapter, native resource or initialization side effect. Module count does not grow. Actual index startup work is accounted above.
Pre-existing costs and validation limits
Non-recent full-send reads: turn-ID/item-ID/operation-ID without bounded turns/time/sequence still select S=10k→100k sends even for two or three output sends. At 100 active watches × one read/s this is 1m→10m selector rows/s plus up to three item-key probes/row and JSON selector extraction on reader workers, before the small output. The PR neither introduces nor fixes that baseline cost; its earlier extra unused allocation is gone.
Tool scanning in final item reads: the existing readOperationWindowItems forces the visible-position index, so turnShape still filters T rows inside SQLite during size/payload passes. At T=1k→10k and 100 reads/s, roughly 200k→2m tool-row visits/s remain across those two passes, while zero tool payloads decode in these fixtures. Placement discovery now excludes them. Application scope.work.rows does not count internal SQLite visits; it cannot establish whole-read independence from T.
Old unanswered send / large argument spread: both base and this head successfully return full output at 10k sends. At 100k, both throw RangeError: Maximum call stack size exceeded in the existing Math.min(...reach) style window-growth code (journal-domain-operation-window.ts:138). This is a reproduced baseline limit, not a new regression or a passing 10N full-history control. Do not treat this diff as proving arbitrary complete-history reads work. Shared-family/extension bounds were source-reviewed, not benchmarked with pathological graphs.
Measurements are standalone diagnostic evidence, not an author-reported test pass or a full application benchmark. No full suite, typecheck, build, install, Electron/GUI operation or GitHub write was run. An attempted tc-gate launch could not create its shared queue/slot under the sandbox; no gated test ran. The standalone performance diagnostics subsequently ran outside the test runner. No packaged startup/frame trace, retained-heap measurement, OS-cold tens-of-GB profile or live Windows/Linux/remote-host measurement was obtained. No interaction-stall or fleet CPU timing is inferred from counts.
Reproduction artifacts: perf5-measure.cts, perf5-controls.cts, perf5-previous-domain-operation-window.ts, perf-evidence-5.jsonl, perf-controls-evidence-5.jsonl under /Users/brennanbenson/orca-qa/pr-47878. Earlier base snapshots are perf4-base-*.ts in that directory; their bodies were verified against the pinned base. Diagnostics use production SQL/schema/read functions with synthetic data, count query results and fallback operations, inspect plans, and compare send IDs/item counts; they do not assert full semantic equivalence of every payload. Temporary benchmark databases were removed by the diagnostic after closing. Checkout code remained untouched, with only the pre-existing M pnpm-lock.yaml in status.
Problem. Every bot request, Slack post, reaction, Linear or Google write and item add first reads whom the bot's newest turn acts for. That read loaded every send the chat had ever made, so in a long-lived bot chat it grew with history.
Change (no visible UI). A read of the newest turns now loads only the sends placed in those turns, found by index, plus any send still waiting for an answer. If such a send sits before the newest turns, the read takes the whole read it took before. A new partial index (journal_items_send_place, CREATE INDEX IF NOT EXISTS, no schema version change) keeps tool-call and diff rows out of that lookup.
Fixed during review
Sends recovered in doubt after a crash were read on every call: they now use the index whose condition matches "unanswered".
An old unanswered send made the indexed path walk a long stretch several times: such a read now falls back to the single whole read.
A turn's tool calls were listed three times to find its sends: the new partial index leaves them out.
A pending send whose opener row is hidden, or a related send whose opener is old, now also takes the fallback.
Fallback positions were built on reads that never use them: only a newest-turns read checks, and it builds no array.
The tool-row perf check now reads the query plans of the statements the read runs, and fails with the old row index.
Deferred (cost only, no result change)
A pending send in the margin turn takes the whole read where a bounded read would do (already so before this PR).
The tool-row check depends on SQLite's EXPLAIN QUERY PLAN wording; a rewording fails it loudly.
On main, before this PR: a whole-history read of a chat with about 100k sends overflows the stack in the window-growth Math.min(...). Not introduced or fixed here; tracked as a follow-up.
Verified
Perf contract (journal-domain-operation-window.performance.test.ts): 50 and 500 turns examine equal rows (527 vs 77 reverted); recovered history adds none (1054 vs 154 with the broader index); an old unanswered send costs the whole read plus 2 rows (3998 without the fallback); 1000 tool calls change nothing, and the check fails with the old index.
Index build, measured: 29 ms at 100k rows and 350 ms at 1M rows (warm cache), once per profile journal database, on the journal writer worker.
Regression audit SAFE on bf9f3a802d. Claude and Codex reviews clean on bf9f3a802d. Perf scan clean on bf9f3a802d. pnpm check:changed passes. remote-check (Linux, related tests) passes. CI green.
QA: tests. This is a read path with no UI, and the perf contract drives it end to end on the real schema.
Findings: no introduced P0/P1 performance regression found in the inspected span. Verdict: clean for the source/count/SQLite-plan audit below. The pass-11 unbounded placement-key producer is now admitted behind a bounded index count, and subsequent lookups stop at the first overflow. This is not a measured application-latency or cold-upgrade performance pass.
Pinned comparison: 4667e7b60c3..e93201ef9b70b74119ef20327dd260ed9f34f9db. Checkout HEAD was verified. Ran the requested perf-surface-detect command: [], so the footer intentionally has an empty surfaces=. The detector matches path/line patterns; its empty result does not exempt these journal SQL, JS-retention and startup-index changes from review. Covered all four changed production files, their changed performance contract, the production consumers, read transaction/worker owners, migration/startup callers and indexed-write consumers. Read the supplied perf-scan method and companion scenario guide, including all six questions and every recurring regression class, and the supplied pass-4 through pass-11 findings.
Evidence and scope
Fresh evidence: target-source census, comparison with the pinned base, and EXPLAIN QUERY PLAN/VM inspection using the checkout's actual SQLite wrapper and full production schema. Plans and complete VM programs are in perf12-explain.jsonl; the inspection script is perf12-explain.cts. Host: macOS arm64, Node v26.5.0, SQLite 3.54.1. This inspection creates only an in-memory database; no user journal is opened or modified. Limited SQL shapes came from the prior captured production statements, checked against the current query builders; the new count and index-build statements were taken from current source. These are fresh plan observations, not populated-workload timings.
Source-proven counts: the bounds, new-head prefix prices and fallback reasoning below. They do not depend on claiming that scope.work.rows measures SQLite work: it does not count subquery keys, skipped index entries or temporary B-tree inserts.
Prior-run corroboration, not fresh head execution:perf11-evidence.jsonl, perf11-controls-evidence.jsonl, perf11-closure-evidence.jsonl, perf11-long-window-evidence.jsonl, and perf11-index-evidence.jsonl. Their scripts and relevant construction/instrumentation were inspected. Their output parity/counts corroborate unchanged branches; they must not be relabelled as measurements of this head. In particular, pass-11's eager four-placement-query totals are obsolete.
Not executed: a fresh populated production-function comparison or committed test. Admission through TC_GATE_POOL=test tc-gate node ... failed before execution: the sandbox denies the shared ~/.cache/tc-gate/test-admit and test-slot-0 files. I did not relocate or bypass the gate. No full suite, typecheck, install, app launch, build, GUI action or GitHub operation was run. No production source was edited. An unrelated pnpm-lock.yaml modification appeared during review; I did not alter or revert it.
No unresolved introduced count-amplification candidate remains after source/VM inspection. Fresh output-hash execution, packaged-app latency, heap/CPU profiling and cold large-profile startup timings remain evidence limitations, not claimed passes.
Production trigger, owners and fleet price
readNewestBotActingTurn (src/main/bots/bot-acting-turn-read.ts:19) requests eight newest turns, then 32, 128, etc. until attribution can decide or the window is complete. It is reached by bot request attribution (src/main/runtime/rpc/methods/orchestration/messaging/bot-recipient.ts:317) and report-only completion attribution (src/main/bots/bot-turn-answered-requests.ts:26). The route is journalSqlReads.operationWindow → reader point request → readJournalSqlProjection → readJournalDomainConsumer → readJournalDomainOperationWindow. SQL, JSON selector extraction and JS closure run synchronously on a journal reader worker, in one WAL read snapshot. Four existing readers share the physical profile database. Main awaits/receives the answer; this diff does not move SQLite onto Electron main or add a reader.
Use S=10,000 saved sends per addressed chat at N and S=100,000 at 10N; family/unsettled populations F/U=1,000→10,000 where relevant. Use C=300 saved chats, A=100 active consumers, r=1 admitted read/s each as an explicit workload, not measured traffic. Request demand is A×r. Raising only C to 3,000 does not multiply one chat's range query, although it enlarges the shared DB/index. Raising only A to 1,000 multiplies the read demand below by ten. Raising only history/family/turn width tenfold must not increase classifier row/key counts. A bot call can issue several windows; multiply by the windows actually requested, not every saved chat. Geometric widening advances toward completion rather than retrying the same request.
The representative ordinary nine-send/27-item workload has 54 preliminary selector materializations at either S: 36 across four placement lookups and 18 across two relationship lookups; the empty seed lookup returns zero. The new count visits 27 eligible index rows; three key producers enumerate 27 each. Thus at A×r=100/s the price is 5,400 selector materializations, at most 16,200 selector-position point probes, 2,700 count-row visits and 8,100 placement-key insertions/s, independent of S=10k→100k. Base's whole-selector read alone materializes 1,000,000→10,000,000 selectors/s, with up to three position probes each. Required items, nine submission payloads and context/output work are additional and common. Prior pass-11 ordinary whole-output hashes matched base, with 90 examined rows at both history sizes; current source adds the count and retains those query/output shapes. The current-head numbers in this paragraph are derived counts, not a fresh timed run.
Changed-work census and bounds
Line numbers below refer to the target ref. Define C_f=64, C_r=1024; W is eligible non-tool/non-diff window rows, K the retained sends, R the required output rows, B the bytes of the admitted selector payloads. Index seeks still have normal B-tree depth/page-cache costs; “constant” below means bounded records, keys, allocations and temporary-key insertions, not physically constant latency or bytes per arbitrarily large message.
Changed work / trigger
Owner, work and N→10N bound
Disposition
Newest-only admission and raw seed, every operation-window call (journal-domain-operation-window.ts:98; journal-operation-window-sends.ts:266–299)
Request-local on reader. Only latest-turn-only anchors enter the optimization. Recovery partial index returns at most 65 pending/unknown-unrecovered selectors, unsorted. At U=1k→10k: 65→65, ≤195 position probes. Overflow returns null before operations/anchors/earliest use a partial seed; whole S sends determine those values instead.
No discarded U-sized seed/anchor construction. Other anchor modes still select all S once, as base did; removed pass-4 traversal is absent.
Early old-seed decision (journal-operation-window-held-sends.ts:15–24)
≤64 raw seeds, each with ≤3 positions and one submitted sequence. Ordinary retained old seed returns null before family SQL or graph. One old pending seed costs one selector and zero family lookups at either S. With anchorsOnly, an excluded older seed does not by itself force fallback; selective retention remains authoritative.
Gate precedes unnecessary expansion, while preserving excluded-seed semantics.
Bounded seed-family walk (journal-operation-window-sends.ts:166–218)
With ≤64 seeds, most=initial+64≤128; every lookup has LIMIT≤129 and no ordinal ORDER BY. New IDs alone enter the next frontier. Size/older checks return null before another round, return-array sort or partial retention graph. Successful seed+family population ≤128 at both N and 10N. A two-member-edge first old relation stops the walk rather than visiting F=1k→10k.
No history/family-size traversal merely to choose fallback. The cap is 64 additional sends per walk, not a claim that every query has LIMIT 65 or total population 64.
Before any item-key producer, a coroutine counts an indexed range with LIMIT 1025. At W=2,027→20,027 (prior long-predecessor control), count visits 1,025→1,025, followed by zero placement queries and zero key-B-tree inserts. If count succeeds, W≤1024 in the same WAL snapshot.
Pass-11 fix bounds the producer, not just its consumer. No race can grow W between count and queries within the snapshot.
Four placement lookups (journal-operation-window-sends.ts:84–118,122–131)
Each send result LIMIT 65, no ORDER BY. First three producers each visit ≤1024 keys; total ≤3072 temporary-key insertions. Submitted-sequence lookup is a direct range seek with no item-key list. Lookups run one at a time and a full one returns null immediately. ≤260 selectors conservatively, union≤256 on success; ≤780 position probes. All bounds unchanged at S/F/W tenfold.
No full matching-group sort, no history-sized key list, no later lookup after overflow. Necessary bounded admission overhead.
Family walk for the window's own sends (journal-domain-operation-window.ts:145–153)
Seed closure≤128; successful placement union≤256. Hence most≤128+256+64=448; individual family SQL LIMIT≤449. Initial placed/added sends are tested for older positions before family SQL. New relationships use the same capped walk. Successful final indexed population≤448, regardless of history/family width.
Explicit null goes directly to whole selection; no discarded oversized sort/graph.
Retention graph at preliminary and final/after-margin call sites (journal-operation-window-held-sends.ts:45–90; operation-window.ts:157)
For M input sends: initial/final linear filters, ≤2M adjacency references, ≤M frontier pops; every provider/card bucket is deleted after its first traversal, so ≤2M member visits. Four field reads maximum per send on construction and another four on a retained frontier pop: ≤8M. Preliminary M≤128; final indexed M≤448; whole/fallback M=S. For F=1k→10k fully retained two-key sends: 8,000→80,000 field reads, not F².
Same helper at both call sites; pass-6 quadratic fixed-point loop removed. Additional temporary adjacency storage is ≤2S references on a full read: 20k→200k, not a persistent cache. This buys linear closure for arbitrary supported relationships.
A newest indexed read that widens switches to sendHeads once. It never resumes indexed stretches. Whole-read work may scale with S, K, R and required history bytes. Every retention-loop repeat moves start strictly backward; linear-per-pass closure is not a claim that the entire pre-existing outer loop has a constant pass count.
No new repeated indexed prefix or truncation. Through-anchored-operation reads retain their existing complete unbounded expansion.
Selector/payload/output work (journal-operation-window-sends.ts:231–262,302–310; operation-window.ts:178–190)
Each admitted selector has ≤3 unique-key item-position probes plus JSON extraction and allocation. Limited queries cap rows; they do not cap bytes of one stored submission: price O(B), with JSON work over the admitted payloads. Required K payload point reads and R item reads/decodes remain. Full selectors are S=10k→100k; required outputs can be large.
No claim that a row counter bounds bytes. No new whole-stream payload send/serialization, no change to returned item sizing or reply-credit ownership.
New index build / qualifying item writes (database/journal-submission-window-indexes.ts:20–24)
Once per physical DB upgrade: visit I table rows, sort/insert P qualifying keys; O(I+P log P), O(P) index/scratch keys. Steady qualifying insert/delete: one entry; indexed-key/predicate update: at most delete+insert. Tool/diff rows have zero entries.
Required index construction/maintenance, priced separately below; no per-chat rebuild or history scan per write.
New helper import and performance-contract changes
Small local functions/types only; no SDK, client, native owner, subprocess, listener or timer on import. Contract adds isolated synthetic DB populations and hardcoded row/property budgets; no new CI topology.
Fixed module cost, no multiplied ownership. Contract source inspected; not executed through the unavailable gate.
The family bounds are independently finite even without assuming a small component: each nonempty round admits a fresh ID; before another SQL round the total must be ≤most. There are at most 66 querying rounds per walk and two lookups per round. A tighter bound on result materializations follows from complete successful indexed lookups: a provider/card group can be requested at most twice, first to discover all its members and next from its newly admitted members. Each send belongs to at most two groups. Successful rounds therefore materialize ≤4×most rows; a final overflowing pair adds at most 2×most+1. Across both walks, seed and placement, a conservative bound is 65+260+(6×128+1)+(6×448+1)=3,783 selector rows before fallback or successful classification, at either N or 10N. This is a ceiling, not a measured typical cost. At 100 reads/s it is ≤378,300 selectors/s and ≤1,134,900 position probes/s; at 1,000 reads/s multiply by ten. Successful family-frontier key lists contribute ≤2×128+2×448=1,152 JSON-key insertions across both walks; with placement lists the conservative total is 4,224 temp-key inserts/read. No bound depends on F, S or W past the fallback thresholds. Arbitrarily long key strings/payloads still affect bytes and comparisons; no heap/CPU timing is inferred from these counts.
SQLite work before fallback: exact plan checks
Seed:SEARCH send USING INDEX journal_submission_recovery (session_id=? AND epoch=?). Its partial predicate is exactly current pending or unknown/unrecovered. No residual scan of accepted/recovered history, no sort; outer ResultRow is followed by LIMIT's DecrJumpZero. At most 65 selectors and their point subqueries.
Count: range SEARCH journal_items USING INDEX journal_items_send_place (session_id=? AND epoch=? AND sequence>? AND sequence<?) inside a coroutine. VM address 21 yields a row, address 22 decrements the 1025 limit, address 23 advances the index. No sorter, temporary key list or payload JSON parsing. COUNT(*) aggregates the bounded coroutine, not the entire range.
Placement item/provider/answered: exact seek on the specified submission index, LIST SUBQUERY over journal_items_send_place, then the three unique item-position subqueries. No USE TEMP B-TREE FOR ORDER BY, SorterOpen, SorterInsert or Sort opcode in these limited reads. The LIST still uses OpenEphemeral/IdxInsertbefore the outer LIMIT: for example the item lookup inserts keys at VM address 28 and emits selectors at 131. The admission count, not the outer LIMIT, bounds those inserts to W≤1024. Null or unknown kinds are eligible as before; hidden/tool/diff rows are excluded by the partial predicate/index itself, so an arbitrary tool-call tail adds no placement-key visits.
Submitted placement: direct journal_submission_submitted range seek; no item-key producer or ordinal sort; LIMIT 65.
Provider/card family: index search on provider ID or indexed JSON expression. json_each builds a list from the bounded new frontier; it does not enumerate saved sends. VM emits selectors and decrements LIMIT without sorting all matches. Wide groups stop at the explicit limit; a full result causes null before graph/sort. Capped lookup sequencing also stops the second family lookup if the first fills.
Important qualification to “every query is constant”: the new classification work has the bounds above. The entire operation-window implementation does not have a universal history-independent SQL budget. Its inherited latest-root anchor query (journal-domain-operation-window.ts:275) filters root=1 after scanning journal_items_status_turn, whose partial predicate is only visible/non-null turn ID. An N=10k or 10N=100k tail of non-root turn rows can cost N or 10N skipped entries before eight roots. Likewise inherited marginBefore's user query (:324) seeks the root-position index and filters kind/role until a user message; 10k→100k intervening root non-user records cost 10k→100k visits. Fresh VM inspection shows those residual column tests/Prev loops. At 100 reads/s these shapes demand 1m→10m skipped visits/s. These are pre-existing costs: the pinned whole-read implementation executes the same queries once, at the same anchors/start; this diff adds neither those scans nor a repeat. They are not clean constant-time queries and are not newly introduced blockers. Requested T also grows intentionally when the bot widens 8→32→128. B-tree seeks retain logarithmic dependence on physical DB size. No new prefix scan growing with history, family size or turn width that the corresponding whole read would avoid was found.
Prior findings and fallback correctness
Report / case
Target-head disposition and evidence
Pass 4: unused history-sized fallback-position flatMap on non-recent reads
Addressed. That traversal no longer exists. Non-recent seed is the full selector read, without another recent-position array. Prior turn/item/operation/sequence/time controls had base-equal hashes and row counts; this branch remains unchanged by the new count/lookup sequencing.
Pass 5: comparative-only budgets and excluded old pending seed
Addressed. Contract source has hardcoded counts (including 72, 74/2000/1999, 31/46, 67/110/74/65) and family getter budgets. In anchorsOnly mode, old raw seeds are not automatically classified as held; keptSends decides retention, and a later window relationship can still make the old member required. Current count test also asserts zero placement queries on a crowded window.
Pass 6: quadratic keptSends, including the base after-margin call
Addressed. Both preliminary and final operation-window calls use the bucket/frontier implementation. Each member is pushed once, each bucket consumed/deleted once. Inspected prior direct counts were 8k→80k field reads; predecessor-margin production controls had target membership checks 12,019→120,019 versus base 20,000→200,000, with identical output hashes. Those are prior measurements of this unchanged helper, not a fresh test result.
Pass 7: old seed already determines fallback
Addressed. Earliest/older raw-seed check is before boundedSends. One old held pending seed: one selector, zero family SQL, at N and 10N by source. No keptSends graph is needed before that null result.
Pass 8: first discovered older relation, including accepted window sends; widening
Addressed. Bound check/older predicate is before each next family round and before the return sort. Recent seed and placed-send callers propagate null to full selection. Newest-window widening takes the whole read once. Prior chain control had four preliminary selectors at both family sizes and zero partial sort inputs; current branch is unchanged.
Pass 9: wide group's first lookup; discarded sort/graph
Addressed. Query LIMIT and absence of ordinal ORDER BY are checked in the VM, not inferred from index use alone. Full lookup returns null inside capped before a return-array sort or preliminary graph. Wide pending shared card: source prefix 1 seed +66 family rows = 67→67 for F=1k→10k. Accepted window-owned wide card: ordinary 36 placement rows +9 provider-family rows +74 card rows = 119→119; no nonempty partial-family sort/graph on overflow.
Pass 10: wide provider/answered-turn placement
Addressed, and fewer queries now run. Provider control's prefix is 9 opener +65 provider =74→74, then no answered/submitted lookup; prior eager total 92 is no longer current. An answered-turn overflow after two nine-row lookups costs 83→83. Each is unsorted and has a ≤1024-key producer. The later family walk is skipped on placement null.
Pass 10: unsettled overflow
Addressed.65→65 seed rows for U=1k→10k; both retention modes select all sends before deriving operations/anchors/earliest. Thus old pending/unrecovered positions that precede the first 65 candidates still influence the full read. Recovered unknown rows are excluded by the recovery partial index.
Pass 11: wide turn's key-list materialization and lookups after overflow
Addressed. For the reported W=2,027→20,027 predecessor shape: 1,025→1,025 count visits, 0→0 preliminary placement selectors, 0→0 item-key temp inserts, then whole read. For any admitted W≤1024, three producers total≤3072; at the first full lookup, no subsequent lookup executes. Current VM proves the count limit is inside the producer. The committed crowded-window guard checks skipped placement calls; it does not itself count internal VM visits, hence the independent VM inspection.
All fallback sites were traced, not treated as truncating the limited population:
Raw seed overflow sets recent=false and obtains full sends before anchor construction. This is the only overflow that could hide additional unanswered seeds from earliest; it restores all of them first.
Recent-family rejection restores all sends. Every unanswered seed was already present when there was no overflow, so earliest remains the whole read's unanswered/anchor minimum. Family members then participate in the ordinary final closure/widening.
Crowded placement, full placement lookup, initial/discovered older placed family, or family size overflow all replace the indexed array with sendHeads(scope). Final keptSends still sees complete families. No limited subset is returned as accepted output.
A later indexed widening restores all sends and continues with the strictly earlier start; no newest-only range re-expansion continues. Successful boundedSends restores ordinal order; fallback sendHeads uses the original ordinal order. ReadSend and item projection remain the same.
These establish preservation of full-read membership/order/start reasoning by source. Previous complete-hash comparisons corroborate the unchanged fallback branches. Fresh current-head hashes, including the new crowded case, could not run through the gate; the report does not claim they did. There is no source-visible path where an overflow is silently accepted as a partial family/window.
The new journal_items_send_place index is once per physical agent-session-domain.db, containing all sessions/epochs in that profile/host—not once for each saved chat or journal consumer. migrateJournalDomainSchema (database/journal-domain-migrations.ts:29) invokes ensureJournalSubmissionWindowIndexes even when user_version is already 2. CREATE INDEX IF NOT EXISTS ensures an existing v2 journal receives it; later opens check its existence without rebuilding it. The three submission expression/provider indexes in the same ensure function already exist in the pinned base; charge their builds only if genuinely missing, not as three additional new indexes from this span.
It runs synchronously in the journal writer worker's open, before ready and before the reader pool is constructed: journal-sql-worker-entry.ts:72–102 → initialize/open → journal-domain-database.ts:125–144 → migration. Existing destination initialization may open once for reconciliation and then open the steady writer; only the first successful CREATE builds it. Readers use readonly connections and do not call this migration. JournalSqlDatabase.open awaits writer.opened before constructing readers. A single record-store once-slot shares this owner among startup, chat installation and PR-watch consumers.
Startup answer: for a profile with saved chats, startLocalAgentSessionRecordStoreOpen (runtime/agent-session/records/local-agent-session-record-store-startup-open.ts:34–45) starts the writer alongside other startup work. Thus upgrading an existing populated profile normally pays the build during startup, delaying journal/store readiness and first usable saved-chat reads. It is off Electron main, and does not wait for first open of each chat. If the database is first opened later, that first physical database open pays it. A brand-new domain DB creates the index while empty and thereafter maintains it during import. Separate physical profiles/remote hosts pay for their own DB; opening hundreds of chats in one profile does not rebuild it hundreds of times.
Fresh CREATE INDEX VM inspection shows a table Rewind/Next over all I journal_items, hidden/kind tests, then SorterInsert of the session/epoch/sequence/item-ID/rowid keys, SorterSort and final index insertion. It is not limited to 1025 rows: that cap applies to later read classification only. Work is O(I + P log P) with P qualifying visible non-tool/non-diff rows, O(P) retained index keys and potentially O(P) sort scratch/spill. It does not parse payload JSON; it must still visit table records/pages to test the predicate. Table-file size is not equal to measured disk bytes fetched, and large overflow payload pages need not all be read. It holds the schema/write operation until completion; low free space/slow storage/lock waits can delay or fail open, and a failed incomplete build can retry at the next open. Successful construction persists, so it is not a steady retry/idle loop.
The following are existing pass-11 measurements of the identical new index SQL, inspected here, not freshly rerun: perf11-index.cts/perf11-index-evidence.jsonl, warm standalone macOS arm64 Node v26.5.0/SQLite 3.54.1, 1 KiB JSON payload per row, 10% qualifying rows, on-disk WAL/NORMAL database, checkpoint before build:
Total rows I / qualifying P
DB bytes before build
Build wall time
Index bytes
WAL bytes just after ensure
Second ensure
100,000 / 10,000
155,459,584
45.07 ms
299,008
309,032
0.039 ms
1,000,000 / 100,000
1,555,255,296
247.39 ms
3,117,056
3,143,592
0.027 ms
These establish a real one-time worker/startup dependency, not a main-thread frame stall or cold-fleet timing budget. Do not extrapolate them into a promised seconds-to-start figure.
Fleet operations/storage: C=300×S=10k sends is 3m sends. With an explicit illustrative 10 item rows/send, I=30m; at 10% qualification P=3m, the build visits 30m table records and sorts/inserts 3m keys once. Tenfold history alone gives I=300m/P=30m; tenfold chat count alone gives the same aggregate. At the diagnostic's short key widths, approximately 90–94 MB→0.90–0.94 GB of index storage and a similar index-build WAL volume, plus sort scratch/page overhead. Real long IDs increase those bytes. If qualification is 100%, P=30m→300m and key/storage/sort cost is ten times the 10%-qualification case; partial indexing is not a guarantee of a 10% ratio. A cold tens-of-GB real profile, contention, Windows/Linux/SSH storage and startup milestone duration were not measured.
Steady writes: the writer's full current-item upsert can update index key/predicate columns; charge at most one delete+insert per qualifying update. At 2 such updates/s×100 active chats, ≤200 indexed-row updates/≤400 entry mutations/s; at 1,000 active chats, ≤2,000/4,000. The B-tree entry is compact; no history scan or full index rebuild occurs per write. Ordinary stable text snapshots use journal-domain-text-snapshot.ts and journal-text-tail.ts updates to payload/revision/wire fields, not the new index columns/predicate, so those fast-path stream saves add zero new index entry rewrites. Tool/diff rows add no entries; removal/hiding follows ordinary SQLite index maintenance. Necessary indexed storage grows with retained eligible journal rows, not stream revisions or mounted consumers.
Disposition: necessary proportional once-per-DB index construction and per-row maintenance, with an explicit startup dependency and storage price. No redundant rebuild, new main-thread SQLite call or repeated history scan was found. This does not certify cold large-profile startup latency.
All six scan questions
Question
Disposition
1. Unused work before a skip gate?
Reviewed with source and VM bounds. Old-seed rejection precedes family work; seed, family and placement overflows propagate null before sort/graph; count precedes item-key producers; sequential lookups stop immediately on overflow. Non-recent discarded traversal removed. Ordinary/prefix/upper-bound prices above include producer work.
2. Ownership multiplying/recreating work?
Reviewed. Request-local maps/graphs; existing four-reader pool and one shared physical-profile writer. No new per-row/pane client/effect or per-chat index build. A×r multiplies requests; C affects aggregate storage, not per-chat mounted fan-out.
3. Thread and storage payer?
Reviewed with routing and plans. Reader worker pays read SQL/JSON/JS; writer worker pays DDL/DML. Main awaits/transfers required results. Range/expression/unique indexes and LIMIT placement inspected; no matching-group ordinal sort in limited reads. Existing statement cache bounds prepared statements at 256 per connection; dynamic bounded family limits do not create an unbounded cache. Cold storage/locks unmeasured.
4. Growth and progress?
Reviewed and priced. Classifier records/keys/temp inserts bounded at S/F/U/W tenfold; whole outputs can grow legitimately. Frontier admits fresh IDs, graph deletes buckets, widening goes strictly backward and newest indexed work switches once to full read. T grows geometrically toward complete. Inherited residual anchor/margin scans and non-newest full reads are explicitly labelled pre-existing, not claimed constant.
5. Host effects?
Source reviewed; plan evidence only on macOS arm64. No new process/shell/path/WSL probe, filesystem enumeration, RPC per send or cross-host fan-out. SQLite work runs on the journal's actual host; remote profiles own their own DB rather than desktop multiplying every replica. Windows locks, slow disks and remote-host contention can increase the same costs; no runtime host-performance claim. No new mobile/folder-workspace assumption.
6. Obsolete work stop/release?
Reviewed. Null stops subsequent admission and prevents partial sort/graph; local sets/maps/frontier become unreachable after return/fallback, no global family registry or retained per-chat projection. SQLite requests remain synchronous while running; existing in-flight read cancellation/worker-close/reply-credit behavior is unchanged. No timers/listeners/subprocesses added. Added steady-idle wakeups are 0→0/s on main, renderer and journal workers by scheduling census, not a measured idle-CPU result.
Recurring-regression-class screen
All classes were screened; rows marked “no matching code” are included to make the table audit explicit.
Class
Disposition
No-op store write returns new identities
No matching store-action code. Request-local selector maps do not publish store references.
Whole keyed map/settings selected for one entry
No matching selector/component code.
Per-row derivation over whole collection per write
No mounted-row derivation. Request-local retention matches collection work; linear count/bucket bounds disprove the old nested rescan.
Streaming re-processes whole message
Matched storage/index consumer screen; no new stream payload parsing/serialization. Stable text fast path updates no new indexed columns, so zero added index entry rewrites per such save. Full upserts pay bounded compact DML as priced.
Fixed-cadence loop never settles
No matching new timer/poll/backoff loop. Synchronous frontier advances only with fresh IDs.
New wakeups in steady idle
Disproved by scheduling census: no added timer, IPC cadence or subscription owner; added rate zero per process.
Expensive code newly reachable past gate
Matched newest-only placement/family route. Producer count≤1025, key lists≤1024 each, bounded send-group reads and immediate null disprove the previous unbounded newly reachable classifier. Existing full fallback remains explicit.
Hidden/unfocused/unheard owner keeps working
No new visibility-owned activity. Requested background bot attribution has a consumer; no additional idle/hidden mounted work.
Every mounted instance loads active-only data
No matching component/effect.
Subprocess per item/event
No matching new subprocess or per-send remote call.
Sync fs/SQLite on Electron main
Matched src/main SQLite; actual production routing disproves main execution. Reader and writer worker occupancy/startup dependencies remain priced, not hidden by async naming.
Re-reading unchanged input
Matched classifier→whole fallback. Bounded recovery cost is 65 seed rows, capped groups and bounded keys, not another S/F/W-sized discarded read. No cross-request cache claimed. Inherited non-newest whole selectors remain pre-existing.
Publish when nothing changed
No new notify/revision/publication site.
One change published as snapshot/N notices
Existing operation-window response shape and consumer count unchanged; no new publication fan-out. Required payload output still priced.
Whole-file rewrite per change
No matching whole-file write. New index maintains individual compact entries; it is not rebuilt per item/stream revision.
Per-entity state outlives entity
Matched maps/sets: all new graph/frontier state is local to a read. Index entries follow retained journal rows and SQLite deletion/predicate changes, not a new resource registry.
Hot-path rescans
Matched graph/family/SQL subqueries. Linear bucket traversal at both call sites; bounded frontier/query rows; count gates temp-key population; no subsequent lookup after first overflow. Inherited residual root filters separately priced.
Unbounded fan-out/queues
No new async fan-out/waiter queue. Finite recent frontier and explicit overflow recovery. Existing reader concurrency/admission/transfer ownership unchanged; pool size alone is not used as a work bound.
Eager startup imports
Pure local helper import, no new SDK/adapter/client startup side effect. New DDL is separately traced and priced rather than omitted as an import detail.
Remaining pre-existing costs and validation limits
Non-newest operation/item/turn/time/sequence reads still materialize S current-send selectors even for small output. The real bot-run-turn-watch.ts:71 requests operation-ID windows after changes, using the existing 300 ms quiet-gap / 2 s maximum-wait coalescer, and unsubscribes/disposes when finished. At 100 watches×1 admitted read/s, full selectors alone cost 1m→10m visits/s for S=10k→100k. There is no cross-read memoization in either ref. The PR removes the needless extra pass but does not solve this older full-read mechanism. Inherited root-filter scans and required long-window item sizing/decoding can likewise grow; neither is newly repeated by this optimization. The final retention loop can revisit the selector population when required positions widen start; the helper is now linear per pass, not a proof of a constant number of full passes.
The changed contract includes useful hardcoded work/output checks and crowded-window admission checks, but examined-row counters alone still cannot observe SQLite key/VM work. The independent current VM inspection establishes the missing producer bound. No empirical current-head N/10N output hashes, heap retention, main/renderer frame latency, cold large-profile migration, host-specific I/O or cancellation-under-OS-I/O result is claimed. These limits prohibit calling those unmeasured latency paths validated; they do not leave a known introduced unbounded classifier or redundant history-sized pre-fallback pass unaccounted for.
This supersedes the earlier status comment for bf9f3a802d.
Problem. Before acting, every bot request, Slack post, reaction, Linear or Google write and item add reads whom the bot's newest turn acts for. That read loaded every send the chat had ever made, so in a long-lived bot chat it grew with history.
Change (no visible UI). A read of the newest turns now reads, by index:
the sends still waiting for an answer;
the sends placed in those turns;
the sends linked to either by provider id or queued card.
Every lookup on that path has a fixed bound:
at most 65 sends each, in index order;
at most 1024 window rows counted before any sends are placed;
the lookups run one at a time and stop at the first full one.
The read takes the whole read it took before when a bound is reached, a held send sits before the newest turns, or the window must widen. It returns the same result either way. A new partial index (journal_items_send_place, CREATE INDEX IF NOT EXISTS, no schema version change) keeps tool-call and diff rows out of the placement lookups.
Fixed during review (each found on an earlier head, each now guarded by a test that fails without the fix)
Sends recovered after a crash were read on every call. They now use the index whose condition matches "unanswered".
An old unanswered send made the indexed path walk a long stretch. It now takes the whole read, decided before any send family is read.
A turn's tool calls were listed three times to find its sends. The partial index leaves them out.
Fallback positions were built on reads that never use them.
An anchors-only window fell back for an old pending send it never holds.
Holding a family of linked sends took quadratic work. It is now one walk.
A family walk continued after it had already decided the whole read. It now stops at the first member older than the window.
A wide shared-card family, a wide answered-turn family, a pile of unsettled sends, and a window crowded with rows each did work growing with history before the fallback. The fixed bounds above now cover all four.
A stopped family walk could miss a send the whole read holds (contrived). Any stop now takes the whole read.
Deferred (cost only, no change to results)
A pending send in the margin turn takes the whole read where a bounded read would do (already so before this PR).
A window past the 1024-row cap (most likely on the 32- and 128-turn retries in chats that write many messages) pays the cost the read had before this PR. Follow-up if it shows in profiles.
On main before this PR: a whole-history read of a chat with about 100k sends overflows the stack in the window-growth Math.min(...). This PR neither introduces nor fixes it; it is tracked as a follow-up.
The tool-row plan check depends on SQLite's EXPLAIN QUERY PLAN wording. A rewording fails it loudly.
Verified
Perf contract (journal-domain-operation-window.performance.test.ts, 7 tests). All budgets are exact, and each fails with its fix reverted:
72 rows at 50 and at 500 turns, against 527 vs 77 with the change reverted;
chain families cost a fixed 31 or 46 rows over the whole read;
the shared card costs 67 or 110 rows, the shared answering turn 74, and the unsettled pile 65, each at 200 and 500 sends;
a 2000-message turn runs no placement lookups;
linked sends are held in linear work: 798 and 7998 field reads at 100 and 1000 sends, against 29702 and 2997002 before.
Index build, measured: 29 ms at 100k rows and 350 ms at 1M rows (warm cache). It runs once per profile journal database, on the journal writer worker.
Regression audit SAFE on e93201ef9b. Claude review and Codex audit clean on e93201ef9b. Perf scan clean on e93201ef9b (posted above). pnpm check:changed passes. remote-check (Linux, related tests) passes. CI green.
QA: tests. This read path has no UI, and the perf contract drives it end to end on the real schema.
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
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.
ELI5
When a bot does something on someone's behalf (sends a request, posts in Slack, adds an item), Orca first checks who the bot's current turn is working for. To check, it reads the chat's most recent turns. That read also looked through every message the chat had ever sent to find the few in those recent turns. So the longer a chat ran, the slower every one of those actions got. Now it looks only at the messages in those recent turns, plus any still waiting for an answer.
What Changed
readJournalDomainOperationWindowwithlatestTurnsand no other anchor (the read behind whom a bot's turn acts for) used to load every current send in the chat (sendHeads(scope)): each one with three position lookups and JSON extraction, before keeping the few the window holds.It now reads, each by an existing index:
journal_submission_recovery, whose condition is the code's own definition of unanswered), wherever it sits, since those widen the window as before;placedSends). Those lookups list the window's visible non-tool rows through a new partial index,journal_items_send_place, whose condition is the same row filter the send position lookups use, so a turn's tool calls and diffs are never listed.When a send the window must hold (one still unanswered, or one sharing a provider id or queued card with it) sits further back than the newest turns, it pins the window back to it, often to the start of the chat. The window then takes the single whole read it took before, which is cheaper than reading that long stretch by index. Sends recovered in doubt after a crash are never unanswered, so they are read only when the window holds them.
Sends sharing a provider id or queued card are held together. That family is now walked once, through a map from each id to its sends; before, it was rescanned on every pass, which was quadratic for a long chain. The indexed path also has a fixed bound: every lookup it runs (the unsettled sends, the sends placed in the window, and their families) lists at most 65 sends (
RECENT_FAMILY_CAP+ 1), in index order. A full lookup takes the whole read, decided before the window's start is computed when it is the unsettled sends. Before placing sends, it counts the window's rows a send can sit on, stopping at 1025, and takes the whole read past 1024 (RECENT_ROW_CAP), so a turn that wrote thousands of rows is never listed. Lookups run one at a time and stop at the first full one. It takes the whole read as soon as a family runs older than the window or past that cap, or the window must widen, so it never walks a long stretch or a large family. This reuses the read path a window through anchored turns already takes. Windows anchored any other way (operation ids, item ids, turn ids, the latest ended turn, a sequence or time) keep the whole read. The new index isCREATE INDEX IF NOT EXISTS, with no schema version change. It is built once per profile journal database after upgrade, on the journal writer worker before the journal is ready (off the main thread). Measured: 29 ms at 100k rows, 350 ms at 1M rows (warm cache).Why
Every bot request, Slack post, reaction, Linear or Google write and item add reads whom the bot's newest turn acts for. In a long-lived bot chat that read grew with every send the chat had ever made, and it is about to gain another caller (bot item add, #47789). Bounding the shared read fixes all callers at once. Bounding each caller separately would leave the others slow.
Linked Issue
Internal bot item 486 (prerequisite for #47789).
Visual Proof
N/A: no user-visible change; reads return the same window.
Testing
journal-domain-operation-window.performance.test.tsgains a perf contract over the newest 8 turns:journal_items_send_place(checked withEXPLAIN QUERY PLANon the statements the read runs). With the old row index, that check fails.pnpm check:changedpasses (macOS).Performance
Fixes a read that grew with chat history. For a fixed newest turn, the rows examined are now constant in the number of earlier settled or recovered sends (50 vs 500 turns: equal). When an unanswered send pins the window far back, the read is the whole read it was before, plus the index read that found that send. Within the window, the send lookups list only the window's visible non-tool rows, so a tool-heavy turn adds nothing. One index build per profile journal database after upgrade, on the writer worker and linear in its rows (29 ms per 100k rows measured); about 38 bytes per indexed row afterwards.
Risk
Level: Medium
This is a core journal read with many callers (bot acting-turn reads, first submitted prompt, fork reads, memory sources, accepted-unopened). The risk is a window that misses a send the whole read would have kept. That would change which turn a reading attributes to whom. The bounded path keeps every send placed in the window or sharing a provider id or queued card with one, and every unsettled send, which is the set the whole read keeps. Revert is a plain revert.
AI Disclosure
Review
Agent skill upstream boundary
Notes
Cross-platform, SSH, mobile: shared journal SQL only. Backwards compatible: one added partial index (
IF NOT EXISTS), no data change; older builds ignore it.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)