Skip to content

perf(journal): an operation window through its anchored turns reads only that turn's rows and sends - #47529

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/journal-turn-window
Nov 23, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/journal-turn-window

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When a bot group room needs one old turn of a bot's chat (for example when someone opens a finished turn to see its tool calls), Orca read that turn and everything after it, and also listed every message ever sent in that chat. In a long chat that is a lot of work for one turn. Now the read stops at the next turn and only looks at the messages that belong to that turn, so opening an old turn costs the same however long the chat has gone on since.

Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​190 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​190
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​298 $\color{#cf222e}{\Huge{\mathbf{−}}}$​68 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​230

What Changed

  • The journal's operation-window read gets an opt-in option, throughAnchoredTurns, for readers that need only the anchored operations' own turns:
    • The window ends where the next root turn opens, instead of running to the chat's head.
    • Instead of listing every send the chat ever made, it reads only the anchored operations' sends (by id, every send that carried the operation as a queued card, and the send that consumed the card) and the sends whose opener row, provider row, answering turn row or sent-at position sits inside the window. It then follows every send that shares a provider id or queued card with one it holds (a steer shares its turn's provider id), until no new send turns up, and holds each send once.
    • Each of those reads is pinned to its index (INDEXED BY) and matches on the index key, so it visits only the sends it returns. When the window reaches further back to hold a kept send's rows, the sends placed in that added stretch are read the same way. Three indexes are added at startup with CREATE INDEX IF NOT EXISTS, the way the journal already adds its text-tail table (no schema version change): a send's queued card, its answering turn row, and its provider row.
    • The option takes operation ids alone (other anchors throw), unanswered sends outside the window don't come along, and a window it ends early is not reported complete.
  • Every existing caller returns the same results as before. (The send listing moved to its own file and differs only in whitespace; the row read adds an always-true upper bound on the same index range.)

No visible change. The bot group room starts using the option in #47176.

Why

Opening one turn should cost one turn. The full listing exists so per-turn readings over a window equal those over the whole conversation. A reader that only needs one finished operation's own turn doesn't need sends from elsewhere in the chat, and the indexes to find the ones it does need already exist.

Linked Issue

Part of the fix for #46084 (lands before #47176).

Visual Proof

N/A: no visual or interaction change; this is a journal read used by a later PR.

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 (perf contract) builds a real journal with 10 and with 100 finished turns, each opened by a send that carried a queued card, and opens the first turn by its send id and by its card id. It asserts a fixed 16 rows examined, the window's sends and turn, and that the turn's rows equal the whole-chat read's. Without the bound the same read examines 106 rows at 10 turns and grows with the chat. Each chat is written in one transaction, so the test runs in seconds on every platform. The row tally can't see work inside SQLite, so the index-key match was checked with EXPLAIN QUERY PLAN during review. pnpm check:changed passes.

Performance

Less work for the new option's readers: rows and sends examined stay constant as the chat grows past the turn, instead of growing with every later turn and every send. Callers that don't pass the option do the same work as before. The three new partial indexes are built once at the first startup after upgrade (one pass over current sends) and kept current on each send write, a small per-write cost.

Risk

The risk is a reader with the option missing a send it needs to attribute its own turn. It includes the anchored operations' own sends, their queued-card carriers and every send placed inside the window, and no existing caller uses the option yet. A revert backs the code out; the three indexes would stay in existing journals, unused, and older builds ignore them.

Level: Low

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

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

No actionable comments were generated in the recent review.

Walkthrough

The operation-window reader now supports an optional end bound at the next visible root turn. It selects and merges sends for anchored operations and sends within the bounded interval, then applies the bound to item reads and send filtering. A performance regression test compares examined-row counts for journals with 10 and 100 completed turns and checks the returned window contents.

Merge Risk: Minimal · previous review 3e97d

This adds an opt-in bounded read of journal operation windows. It ends the window at the next root turn and looks up sends through new indexes, instead of listing every send in the chat. Existing callers keep their current behaviour and the new path has a row-count performance test. No concrete merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title follows the conventional commit format and names the main change: an operation window read through its anchored turns reads only that turn's rows and sends. The changeset adds the opt-in thr…
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.
Description check Passed The description follows the template closely and fills in most sections: ELI5, What Changed, Why, Linked Issue (partial reference to #46084), Visual Proof (N/A with reason), Testing (automated test de…
Full details: Title check

Explanation

The title follows the conventional commit format and names the main change: an operation window read through its anchored turns reads only that turn's rows and sends. The changeset adds the opt-in throughAnchoredTurns option, bounds the window at the next root turn, and limits send reads to indexed lookups, so the title matches the primary change. The title is long at 99 characters, but it stays specific and on topic.

Full details: Description check

Explanation

The description follows the template closely and fills in most sections: ELI5, What Changed, Why, Linked Issue (partial reference to #46084), Visual Proof (N/A with reason), Testing (automated test described), Performance (one-line 'None' statement is replaced by a substantive performance explanation), Risk with level Low and revert path, and the checklist. Gaps: the Performance section starts with 'Less work for...' instead of completing the 'None, because' sentence, which is acceptable since the change is not trivial. The 'Linked Issue' section uses 'Part of the fix for #46084' rather than the 'Fixes #' form, which is a minor deviation. The 'AI Disclosure' section is empty, which is a notable omission for an external-facing template. The 'Testing' checkboxes for manual testing are left unchecked without explanation, and the test claims in the description (16 rows examined, 106 rows without the bound) differ from the raw summary's wording only in detail, not in substance. The description's row counts (16 rows) are consistent with the raw summary, but the PR objectives mention 12 rows; this discrepancy should be reconciled. The PR-LoC block is auto-generated and fine.

  • 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

Recent 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: 4fb29206-2ec8-41b4-9b7a-dec0c7ea4027
Commits

Reviewing files that changed from the base of the PR and between 97da565 and 3e97dfe.

Files selected for processing: 3

  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.performance.test.ts
  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.ts
  • src/main/native-chat/agent-session-journal/journal-operation-window-sends.ts

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

@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: 3

Nitpick comments: 1

src/main/native-chat/agent-session-journal/journal-domain-operation-window.performance.test.ts: 1

145-145: Trivial · Maintainability & Code Quality · Quick win

Use a hardcoded work budget for both fixtures.

This equality passes if both reads acquire the same large fixed overhead. Measure the intended implementation, then assert the same literal row budget for both fixtures. Keep the snapshot-content checks.

As per coding guidelines, a perf contract counts operations “against hardcoded values, and never wall time”.

Source: Coding guidelines

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: 7ca7b731-ba7d-4a07-aab4-4dbebd204f0b
Commits

Reviewing files that changed from the base of the PR and between b7fd7ca and 0440581.

Files selected for processing: 5

  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.performance.test.ts
  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.ts
  • src/main/native-chat/agent-session-journal/journal-operation-window-end.ts
  • src/main/native-chat/agent-session-journal/journal-operation-window-rows.ts
  • src/main/native-chat/agent-session-journal/journal-operation-window-sends.ts

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

@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: 6649a055-c2e8-4b0f-b48e-fecd77c27082
Commits

Reviewing files that changed from the base of the PR and between 0440581 and 1e43ead.

Files selected for processing: 5

  • src/main/native-chat/agent-session-journal/database/journal-domain-migrations.ts
  • src/main/native-chat/agent-session-journal/database/journal-submission-window-indexes.ts
  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.performance.test.ts
  • src/main/native-chat/agent-session-journal/journal-domain-operation-window.ts
  • src/main/native-chat/agent-session-journal/journal-operation-window-sends.ts

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

…nly that turn's rows and sends

A reader of one ended operation's own turn (a bot group room opening an old
turn) read every row from that turn to the chat's head and listed every send
the chat ever made. The new throughAnchoredTurns option ends the window where
the next root turn opens and reads only the anchored operations' sends and
those placed inside the window, each found by index, so opening one old turn
costs the same however long the chat has run since.
…rs and answers included

A window through its anchored turns now also reads every send that carried the
operation as a queued card and the sends whose provider row or answering turn
row sits inside it, each through an index created at startup (no schema
version change), and every bounded send read is pinned to its index. The
consuming send's id is no longer split into characters, the option takes
operation ids alone, and a window it ends early is not reported complete.
…queued card with its own, once each

A steer shares its provider id with the send that opened the turn; reading
only the steer let the turn be attributed to it. The bounded read now follows
shared provider ids and queued cards by index until no new send turns up, and
holds each send once.
…e transaction, once per size

Per-step commits on disk timed out on Windows CI.
…pe shared sends in one pass

A send no turn row names (an older import) is placed by position, so its own
turn can be the first one after it: the window then reaches one more turn.
Sends found through a shared provider id or card are deduplicated with a set.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/journal-turn-window branch from 9bb61eb to 3d89d2d Compare November 23, 2026 10:24
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Performance audit: no new P0/P1 blocker found in 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18..3d89d2d94a190b1d1ad79165755807330c757d3d. The opt-in path avoids enumerating unrelated later sends and rows. Index construction is a real first-open cost, not constant-time work; subsequent opens skip rebuilding, and send-write upkeep affects only the written attempt's three index entries.

This is infrastructure for a later caller change. At this head, throughAnchoredTurns is enabled only in the new performance test. Existing production operation-window calls, including src/main/bots/bot-chat-reads.ts:50, retain their prior behavior.

Executed evidence and scale

On macOS arm64, Node 26.5.0 / SQLite 3.54.1, ran isolated in-memory checks through tc-gate, without installing dependencies, building the app, or modifying checkout files. The read harness evaluated the HEAD operation-window, send-selection, end-boundary and row-selection functions after removing TypeScript/import syntax, using the HEAD schema and native SQLite. It supplied lightweight scope, queue lookup, cursor and submission-key adapters. This exercises the changed SQL and control flow, not the complete worker/IPC stack or the repository Vitest test. Payloads were small, finished turns with distinct provider/card identities and one send per turn.

Opening the first finished turn N = 10,000 turns/sends 10N = 100,000 turns/sends
SQL executions, including scalar .get() calls 22 22
Rows returned by those calls, including uncounted sizing/metadata rows 23 23
scope.examined rows 16 16
Decoded JSON bytes 467 467
Returned items / submissions 3 / 2 3 / 2
Missing operation: SQL executions / examined rows 6 / 0 6 / 0

Both direct send ID and queued-card ID produced these counts. The next turn's prompt is intentionally included before that turn's opening row. The unbounded control at 10,000 turns performed 10,009 SQL executions, counted 40,001 examined rows and returned 20,000 items / 10,000 submissions. At 100,000 turns the unbounded control hit the existing spread-argument limit in Math.min(...reach); that expression predates this change. Neither that failure nor the unbounded production reads are introduced by this span.

EXPLAIN QUERY PLAN verified actual third-key equality/range searches, not merely an index name: message ID, queued-card expression, provider item, answered-turn expression, opener item and submitted sequence. In particular, +item_id preserves the answered-expression key search. Each of the three correlated position reads uses the journal-item primary key. Window membership subqueries use the visible-position sequence range; end discovery uses the status-turn sequence range. Temporary ordinal sorting covers matched sends, not every send.

Trigger → population → bound and owner

Changed work Trigger and execution owner Population, repetitions and bound
Admission and anchored-send lookup (journal-domain-operation-window.ts:74; journal-operation-window-sends.ts:29) Each explicitly opted-in point read, on its assigned SQL reader worker Rejects incompatible anchors before selecting sends. Two indexed send queries plus one queue-card lookup per operation ID; operation resolution repeats the queue lookup. IDs are passed through parameterized json_each, not dynamic SQL arity. Work follows requested operations and their matches, not the chat inventory.
End discovery (journal-operation-window-end.ts:6; operation-window lines 107–108) Once per bounded read; twice for position-only placement Indexed next-root-turn lookup. Root filtering can visit intervening non-root turn entries; those lie in the interval being located. No later-root inventory. No next root means the window legitimately ends at the current head.
Window sends and relationship closure (journal-operation-window-sends.ts:60,92) Initial interval, then each newly admitted earlier interval Four indexed membership/range queries per interval; three enumerate only that interval's item IDs. Relationship expansion uses provider/card index lookups and a message-ID map; it terminates when no new send appears. Results are sorted by ordinal. Each returned send head has three keyed position lookups.
Widening and filtering (journal-domain-operation-window.ts:114,155) While a kept send reaches earlier than the current start Start moves strictly backward, and only the added stretch is queried. In-memory sets/arrays are per request. The bound is the selected interval and connected related-send population, not a universal numeric row cap.
Item sizing, projection, shortening and decode (journal-operation-window-rows.ts:28) After the window is resolved Both size and payload queries now use [start,end). Existing expensive projection/shortening remains confined to that interval; tool-output suppression happens in SQL. The existing 64 MiB reply mechanism is a byte guard, not a cap on rows visited. Large legitimate anchored turns still cost their own rows/bytes.
Existing/default send listing Each call without the option The extracted selector retains the existing full-chat work and query shape; adding a maximum-safe-integer item upper bound does not narrow ordinary stored sequences. No new production trigger or increased frequency.
Startup indexes (database/journal-domain-migrations.ts:29; journal-submission-window-indexes.ts:10–19) Writable domain-store open, once per profile owner; built only when absent Three separate table passes over all attempts, testing current=1, then sorting/building three indexes over current attempts. Two explicit JSON expression keys plus the provider generated-column key require current payload processing. This is not one pass over current sends alone. Build cost scales with attempts, current payload bytes and index sorting/storage; successful existing indexes prevent rebuilding.
Index upkeep Attempt insert, indexed payload/current-state update, import, retirement or deletion; SQL writer worker Up to three added entries per current attempt, including null keys. Payload changes recompute keys and can delete/reinsert entries even when a key stays equal. Work is local JSON processing plus ordinary B-tree operations, not a scan over saved sends/chats. No new transaction, timer or subprocess per send.
Performance contract and ratchet baseline changes Test invocation / static checks only New contract uses 10 and 100 turns in one population transaction per chat and closes/removes its fixtures. Baseline annotations do not change app execution. I inspected its assertions; I did not run Vitest in this dependency-free review checkout.

The bounded-read claim is specifically about unrelated later history. Many carriers of the same anchored card, sends sharing provider IDs, sends answered in the anchored turn, widely separated operation anchors, or earlier rows reached by retained sends can enlarge the required result. The closure may revisit relationship matches and the existing in-memory filtering can require multiple passes. This is not a fixed-work guarantee for an arbitrarily large connected component; no unrelated-population scan was found in the new indexed path.

Startup and write pricing

In the full-schema Node harness, creating all three indexes after populating 10,000 / 100,000 current sends took approximately 46 / 859 ms, respectively, in memory. This work executes before the writer announces readiness (journal-sql-worker-entry.ts:77–100; database/journal-sql-database.ts:76–80), so it can delay first post-upgrade journal availability even though it does not run synchronously on Electron main. Disk, WAL and longer payloads can cost more; these numbers are not packaged-app startup measurements.

A separate SQLite VM-step check used the exact new index DDL, 1 KiB bodies, and 10,000 / 100,000 total attempts, half current. First creation used 325,177 / 3,250,177 VM instructions and allocated 458,752 / 4,681,728 bytes across the three indexes. Re-executing the DDL with indexes present used 15 instructions at both sizes. Instrumented elapsed time was 54 / 745 ms for creation and about 0.03 ms for the existing-index case; progress callbacks add measurement overhead. The three indexes are necessary outputs of this one-time migration; this is linear startup/storage cost, not repeated full-history work on opening a turn.

For a keyed single-attempt write, a reduced schema with the existing head index isolated the increment from these three indexes: insert 37 → 77 instructions (+40); same-payload update 40 → 124 (+84), identical increments at N and 10N. These are incremental operation counts, not complete production-send latency or physical WAL-page counts. At an illustrative 100 send-row mutations/s, that is 300 local index-key maintenance operations/s, not 100 scans/s over all attempts. B-tree depth still grows logarithmically with total indexed records and JSON cost follows the written payload's size. Non-indexed field-only writes do not require rebuilding these indexes. No introduced fleet-wide repeated scan or write amplification proportional to saved history was found.

Subscriptions, publication and idle census

The diff adds no subscription, event publication, polling or renderer listener. The changed read uses the existing point-request transport: journal-sql-reads.ts:167 → journal-sql-reader-pool.ts:254 → reader entry's point case at line 169 → ReaderSlot's reply-ID resolver at lines 89–126. There is one worker-port request listener and one owner-side message listener per reader slot, with four ordinary reader slots; one pending requester receives each point result. This result is not broadcast to journal subscribers. There are zero desktop-renderer listeners directly registered for this private operation-window reply, and no new renderer/store publication path. Thus added idle wakeups/frames are 0/s on main, renderer and daemon; at load R reads/s, the existing transport handles R requests and R corresponding results, with no added notification fanout or change-free publication stream. Existing writer readiness remains one startup message, not a recurring publisher.

Six-question and regression-class dispositions

  1. Admission before work: reviewed; option validation precedes send reads, key/range predicates precede payload decoding, and byte projection remains within the selected range.
  2. Ownership multiplication: reviewed; one profile writer and the existing reader pool, no per-tab/worktree worker or subscription added. Increasing 750 worktrees to 7,500, or mounted tabs/terminals, does not multiply a single point read.
  3. Thread/storage cost: reviewed; read SQL stays on reader workers, creation/upkeep on the writer worker. Startup readiness waits for creation. Statement shapes are parameterized and use the existing bounded statement cache. Physical disk contention was not measured.
  4. Growth/progress: reviewed; unrelated-history N/10N counts and plans above, strictly retreating window start, deduplicated relationship discovery; startup and index storage scale with the data indexed. Required large windows/components remain output-sized work, not a global-history guarantee.
  5. Host differences: source reviewed; no shell, path, native discovery or per-item SSH work added. Indexes/read queries run at the owning journal host. Windows/Linux/WSL, live remote transport and slow-disk timings were not executed.
  6. Lifetime/idle: reviewed; new collections are request-local, with no new retained owner, pending queue, timer or listener. Existing worker/reply-credit teardown is unchanged. Synchronous SQLite work already admitted to a reader is not cancellable mid-query; this change adds no new cancellation mechanism or abandoned repeating work.

Touched regression classes: hot-path rescans / rereading history — indexed bounded path verified, default full-history behavior explicitly pre-existing; sync SQLite / startup imports — worker ownership traced, only small local modules added, first-create and existing-index costs measured; SQL preparation / hot-column index amplification — stable parameterized shapes and local write increment verified; snapshot/serialization size — selected interval bounded by anchors, existing byte guard retained; retention/unbounded fanout — request-local sets and unchanged pool/transport, no new long-lived resources. New idle wakeups, periodic polls, no-op publications and renderer selector churn have no matching added code.

Remaining evidence limits: no packaged Electron startup, physical WAL/checkpoint or lock-contention benchmark, large stored-tool-output hydration run, or Windows/Linux/remote-host execution. No claim of constant wall-clock latency or disk footprint is made. The measured bounds establish the targeted unrelated-history improvement; no new excessive repeated production work was identified.

@brennanb2025

brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Status: ready for review (final head db73387)

Problem: opening one old ended turn of a bot group room (#47176) needs a read of that one turn. The journal's operation-window read listed every send the chat ever made and read rows through to the chat's head, so its cost grew with the chat's whole history after that turn.

Change: an opt-in option, throughAnchoredTurns, used with operation ids only. The window ends where the next turn opens. It reads only the anchored operation's sends, their queued-card carriers, the sends placed inside the window, and every send sharing a provider id or card with those. Each read is pinned to an index. Three indexes are created at startup if missing, with no schema version change. Existing callers are unchanged. No visible change.

Fixed during review

  • Claude: the consuming send's id was split into characters (P0). Queued-card carriers and sends answered in the window weren't read. Anchors other than operation ids could cut the turn. complete ignored the new end. Send reads walked every send, including a type-affinity miss on the answering-turn index. The window's walk-back stretch wasn't read. The perf contract compared against itself instead of fixed counts and timed out on Windows CI.
  • Codex audit 1: a steer sharing its turn's provider id was attributed to itself; a queued submission was returned twice.
  • Codex audit 2: a turn placed only by position (older import) was cut at its own row; deduplicating shared sends was quadratic.
  • Codex audit 4: one anchored send naming its turn hid another send's position-placed turn (a shared flag). Each anchored send now sets its own reach.

Verified on db73387 (rebased on main after #47523 merged)

  • Perf contract journal-domain-operation-window.performance.test.ts: a fixed 16 rows at 10 and 100 turns, by send id and card id, matching the whole-chat read. Without the bound it reads 41 at 10 turns and grows with the chat. Two more cases cover position-placed turns, alone and mixed with linked ones. pnpm check:changed passes. CI is green.
  • Claude review: READY.
  • Blinded Codex regression audit: SAFE. It found existing callers unchanged, a constant read cost from 100 to 10,000 turns, and query plans using the intended indexes.
  • Perf scan: clean (7099608666).
  • Linux remote check (Omarchy): REMOTE-CHECK PASS db73387d82e8d04f2cb9d08cedf83dae7eebf17c (38 checks).
  • QA: qa=tests, since no screen changed.

Deferred (P2)

  • The PR body's Testing section doesn't list the two position-placed test cases.
  • No unit tests for the anchor throw, complete: false, or the walk-back stretch; review and audit probes covered them.
  • A read-only journal from a future schema that dropped these indexes would make the bounded read throw. It's hypothetical, and nothing uses the option until Keep finished bot replies visible in group rooms #47176.

Lands before #47176.

One send that named its turn let the window stop before another send's turn
that is placed by position. Each anchored send now sets how far its own turn
may reach, and the window ends past the furthest.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: no introduced P0/P1 blocker found for the opt-in bounded read or the three indexes. Graded against db73387d82e8d04f2cb9d08cedf83dae7eebf17c, using 2284cb2d04f0de86c695f1f5aa584d5c48ee1f18..HEAD.

This is an API prerequisite: no production caller at this head passes throughAnchoredTurns. In particular, src/main/bots/bot-chat-reads.ts:51 still requests the default operation window. The existing room-opening history cost therefore remains until a caller opts in; this span does not newly introduce that cost.

Measured N / 10N evidence

Read-only audit of all nine changed paths, the production callers, worker ownership, storage writes and desktop transport. Executed production TypeScript reader/schema code with in-memory transpilation under tc-gate, without installing dependencies or editing files. Host: this Mac; Node 24.18.0 and SQLite 3.54.1. Synthetic full-schema populations: 10,000 / 100,000 sends, each with a distinct queued card/provider ID, one opener and one completed root turn. Opened the first operation by both send ID and card ID.

Work for one bounded read N = 10,000 sends / turns 10N = 100,000 sends / turns
Executed SQL statements 22 22
All rows returned by those statements, including size/head reads 23 23
JournalSqlScope.work.rows 16 16
JSON bytes decoded by scope 786 786
Returned items / submissions 3 / 2 3 / 2
SQLite VM instructions for all 22 captured production statements 1,841 1,841

The VM check replayed the exact captured statements and bindings against the same full schema/populations in Python SQLite 3.54.1 with a per-instruction progress counter. Thus the result is not just a count of rows crossing into JavaScript. Query-plan checks showed full-key searches on head/card/provider/answered-turn/item indexes, submitted-sequence range searches, and visible-item sequence ranges. The answering-turn query uses the expression key, including its +item_id affinity adjustment. Correlated position reads use the item primary key; sorting is over matches, not all sends.

Correctness controls executed: exact item/submission identities for both anchor types, complete=false when a later turn exists, absent-operation empty output, incompatible-anchor rejection, and retention of the target turn after removing both explicit answer and opener links. The committed Vitest contract was inspected, not run.

Trigger, population and bound for changed work

Paths below are under src/main/native-chat/agent-session-journal/ unless stated otherwise. A = operation anchors, W = visible rows in the selected interval before optional shape filtering, C = discovered related sends, K = backward interval extensions, M = total saved attempts.

Changed work and target citation Trigger / owner / lifetime Population and bound
Option admission and operation resolution, journal-domain-operation-window.ts:74–115; journal-operation-window-sends.ts:29–55 Each explicit point read; journal reader worker; request-local Validate before send reads. Queue-card point lookups per anchor; two initial indexed send queries plus relationship discovery. Default callers still list current sends as before. Added anchor reach bookkeeping follows anchored sends, with no new global inventory.
End discovery, journal-operation-window-end.ts:6–12; journal-domain-operation-window.ts:334–347 Once per positioned anchored send One next-root-turn seek, or two for a position-only import. No later root means head fallback. The status-turn index can visit intervening non-root turn rows while finding a root; it does not enumerate the unrelated suffix after the next root.
In-window send selection, journal-operation-window-sends.ts:60–86 Initial interval and each newly admitted backward stretch Four queries: three enumerate W interval item keys and probe send indexes; one ranges over submitted sequence. No scan of all M sends. Each matched selector performs at most three keyed item-position lookups and reads its own metadata payload.
Related-send closure and retention, journal-operation-window-sends.ts:92–128; journal-domain-operation-window.ts:120–135,161–193 Per discovery/extension Deduplicate by message ID; discover providers/cards through indexes; sort C sends by ordinal. Frontiers stop when no fresh send exists. Start only retreats, so at most K distinct extensions. Closure/filter passes and copying depend on C, relationship depth and K, not unrelated later sends. No retained registry is added.
Item sizing, projection and decoding, journal-operation-window-rows.ts:28–113 Once after interval settles Size/read only the sequence interval; optional shape filtering narrows output. Existing large-row measurement/cutting and 64 MiB reply rejection remain. Costs follow W, selected payload bytes and required stored-output/tail hydration, not the later suffix. Multiple anchors can intentionally span intervening turns.
Payload reads and reply construction, journal-operation-window-sends.ts:173–181; journal-domain-operation-window.ts:136–150 One payload lookup per retained submission, one result per request O(C) payloads plus selected items; fixed keyed first-position/head reads. Existing reply measurement/serialization and backpressure apply. No new publication stream.
Three indexes, database/journal-submission-window-indexes.ts:10–19; migration call at database/journal-domain-migrations.ts:29 Every writable store open checks existence; each missing index is built on the writer worker before readiness Three separate table traversals over M attempts, testing current=1, then key sorting/building for current attempts. Two explicit JSON expression keys and the generated provider key process current payloads. Three entries per current attempt, including null keys. Existing indexes skip population work.
Index upkeep Current-attempt insert, payload/current-state update, import or deletion; existing writer transaction Three local index entries on insert; payload changes can recompute keys and delete/reinsert three entries; retirement/deletion removes them. JSON work follows the changed row's payload; B-tree navigation is logarithmic in indexed records. No history scan, additional transaction or per-item subprocess is added. Journal item/tool-stream writes do not acquire these send-table indexes.
Performance contract and two ratchet baselines Test/static-check invocation only Contract populations are 10/100 turns, populated in one transaction each with fixture teardown. Baseline changes are annotations/count allowances, not runtime work or proof of acceptable cost.

“Bounded” here means bounded against unrelated later history, not a universal constant independent of requested output. Repeated carriers of an anchored card, shared provider identities, sends answered inside the interval, widely separated anchors and backward placement dependencies can enlarge C/W. Those are included for attribution completeness. The inherited closure/filter algorithm can take multiple passes through that required component; no new fleet-wide scan was found. No fixed wall-clock claim is made for arbitrarily large required windows.

Startup build and per-write price

Full-schema Node measurements with small send metadata: first creation of all three indexes took 14.2 ms at 10,000 current attempts / 168.8 ms at 100,000. Re-running their DDL with indexes present took 0.011 / 0.028 ms. These are in-memory harness measurements, not packaged-app or disk startup times.

A separate reduced-schema VM check used the exact new index DDL, 1 KiB payload padding and 10,000 / 100,000 total attempts, half current:

Incremental work N 10N
First index creation, VM instructions 325,177 3,250,177
DDL with indexes already present, VM instructions 15 15
Added SQLite page allocation 270,336 bytes 2,826,240 bytes
Single insert, existing head index → head plus new indexes 38 → 80 instructions 38 → 80 instructions
Keyed same-payload update 33 → 116 instructions 33 → 116 instructions
Keyed retirement (current=0) 51 → 106 instructions 51 → 106 instructions

The build is necessary one-time index construction, with linear input visits and sorting/storage cost, not “one pass over current sends.” It delays journal readiness: journal-sql-worker-entry.ts:77–100 opens/migrates before its ready reply, and database/journal-sql-database.ts:79 awaits that reply. It occupies the writer worker, not Electron main. Successful indexes survive restarts; after interrupted partial creation, existing ones skip and remaining ones build.

The isolated per-row increment is +42 / +83 / +55 VM instructions at both populations. At an illustrative 100 indexed send-row updates/s, the same-payload case adds 8,300 VM instructions/s and up to 600 individual index delete/insert operations/s, not 100 scans/s over saved history. This is necessary local indexing work; it is not an instruction-to-milliseconds conversion or complete send-latency/WAL measurement. Index storage scales with current attempts; ordinary B-tree depth and the written payload's size still matter.

Subscription/publication census at HEAD

The diff adds zero subscriptions, broadcasts, timers, polling loops or renderer listeners. I traced the existing point-result route through unchanged files as well:

  • journal-sql-reads.ts:167 → reader pool point → reader entry's point case: one request and one logical result, addressed by ID to one pending requester. Up to four reader slots per pool, two admitted reads per slot; none is created per tab/worktree.
  • Each active reader has one parentPort message handler (journal-sql-reader-entry.ts:121) and one owner-side result listener (journal-sql-reader-slot.ts:89). Error/exit listeners are lifecycle-only.
  • Desktop hosting adds one utility-host request-port handler and one worker-result handler per hosted reader (utility-worker-host-entry.ts:128,148), then one receiving port handler (hosted-worker.ts:59) forwarding to that same slot listener. In-process fallback has one local-worker forwarding listener instead. This is relay transport, not subscriber fanout.
  • At load R reads/s, there are R logical requests and R results. Hosted result bytes B are relayed in ceil(B / 32 MiB) frames, with one consumption acknowledgement per charged result via the existing host-control listener. The measured tiny window fits one result frame. Existing reply credit is 64 MiB; these limits are unchanged.
  • Reader diagnostics have one optional global sink, installed by worker-thread-diagnostics.ts:55; it updates bounded crash annotations when pending-reader state changes, without renderer publication. Writer readiness has one owner listener resolving its startup promise (journal-sql-owner.ts:68).
  • Desktop renderer listeners for this private operation-window result: zero. Searches included src/renderer and shared contracts. Existing journal subscriptions are not emitted by this read, and index creation/upkeep adds no journal change notice.

For these channels, idle request/result frames remain 0/s before and after on main, renderer, journal workers and daemon. Added steady-idle wakeups are 0/s in each process. Existing diagnostics/maintenance schedules elsewhere are unchanged; this is a source census, not an app-wide idle-CPU measurement.

Pre-existing amplification, not a regression of this span

Without the option, one first-operation read at 10,000 sends returned 20,000 items and 10,000 submissions, issued 10,009 SQL statements, returned 60,004 total SQL rows, and decoded 5,162,610 bytes in this fixture. At 100,000 sends, that control hit RangeError: Maximum call stack size exceeded at journal-domain-operation-window.ts:126, spreading retained positions into Math.min. That spread and all-send/default-window behavior are present in the base. The new bounded read completed at both sizes. This limitation is reported separately, not waived as a newly introduced regression.

Six scan questions and touched regression classes

  1. Work before admission: reviewed; incompatible anchors fail before reads; indexed predicates precede decoding; interval bounds reach both size and payload queries.
  2. Ownership multiplication: reviewed; existing profile writer/four-reader pool, no new per-row/tab/chat/worktree owner. Scaling 750 worktrees to 7,500 does not multiply one point read.
  3. Thread/storage: reviewed; reader workers execute reads, writer worker builds/maintains indexes; startup readiness waits for creation. Parameterized SQL uses the existing 256-entry statement cache. Physical locking/WAL costs were not measured.
  4. Growth/progress: reviewed; unrelated-history counts and internal VM work are constant at N/10N; frontiers deduplicate and starts retreat. Required interval/component size and first-build storage remain data-dependent.
  5. Execution host: source reviewed; queries run at the owning journal host with no new shell/path probes or per-row SSH round trips. Windows/Linux/WSL and live remote timings were not executed.
  6. Obsolete work/lifetime: reviewed; new arrays/maps/sets are request-local. No new long-lived cache, listener, queue or idle work. Existing admission/credit/close paths are unchanged; an already admitted synchronous SQLite statement still runs to completion.

Touched classes: history rereads/hot-path rescans — new indexed path disproved by plans plus N/10N VM counts; default amplification labeled pre-existing. Sync SQLite/startup imports — worker ownership established; first-build and existing-index costs priced; imports are small local modules. Hot-column index/write amplification — measured local per-row increment, no history scan. Snapshot/serialization — selected interval feeds existing size/credit limits. Retention/fanout — request-local state and unchanged owner/transport census. No added code matches periodic polling, steady-idle wakeups, no-op publications or renderer selector churn.

Remaining measurement gaps: packaged cold startup, physical disk/WAL/checkpoint/lock contention, large stored-output/tail hydration, and execution on Windows/Linux/remote hosts. The executed counts establish the targeted unrelated-history bound; they do not certify arbitrary output sizes or app-wide responsiveness.

@brennanb2025
brennanb2025 merged commit 64a5726 into main Nov 23, 2026
58 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