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
Opening a bot item no longer reads its whole history - #47478
Opening a bot's item used to read through every comment the item ever had, just to work out which question is still waiting for you. On a long thread that grew with every comment. Now the app remembers that answer next to the item. Usually opening it reads that answer plus only the comments added since; after a new question or an answer it reads the whole thread once, then remembers again. Adding a comment costs nothing extra.
Files
Added
Deleted
Net
Test
1
$\color{#1a7f37}{\Huge{\mathbf{+}}}$132
$\color{#cf222e}{\Huge{\mathbf{−}}}$2
$\color{#1a7f37}{\Huge{\mathbf{+}}}$130
Prod
8
$\color{#1a7f37}{\Huge{\mathbf{+}}}$191
$\color{#cf222e}{\Huge{\mathbf{−}}}$14
$\color{#1a7f37}{\Huge{\mathbf{+}}}$177
What Changed
Before: each time an item's page opened (and on every refresh while open), the app loaded and parsed the item's whole activity history to work out which question still waits on the owner. That read was added in #47385, so an item with hundreds of comments paid for all of them on every open.
After: opening an item, or an owner's reply checking which question it answers, reads the stored answer and only the events added since it was stored. Writes never store or update it.
Mechanism:
A side table, item_waiting_asks (item_uid, ask, at, rules), holds each item's waiting question (0 means none), as worked out from its events up to event at under rules: the pairing rules version plus the build (its commit on desktop; on a remote server, whose bundle names no commit, its version). A row any other build wrote is never trusted, so after an upgrade or downgrade each item's answer is worked out again on its first open.
The table is created with CREATE TABLE IF NOT EXISTS when the store opens. It is not a numbered migration step, so the schema version stays the same and an older Orca can still write the file.
On open, the app reads the events after at, at most 64. The stored answer still holds when none of them can change it:
a bot comment that asks nothing, a move onto Needs you that answers nothing, and edits or links pair nothing;
an owner comment or another move can at most answer or end a question, so a stored "none" still holds.
Otherwise (a new question, an answer while a question waits, or more than 64 new events), the open works the answer out from all events once and stores it. The store is skipped if a write landed while it was reading.
Writes never store into the table, so they gain no extra commit and no new way to fail. An owner reply reads it like an open does. Events written by an older Orca are checked like any other.
Storing never runs inside a write and never waits on the file. If it fails, the next open simply checks again.
The open-status check still applies when the answer is read.
Why
Opening an item should usually cost the same however long its thread is, and writes shouldn't pay for that instead. The answer depends only on events, and events are append-only with increasing ids. So "the answer as of event at" plus a check of the events after at is exact. That check reuses the pairing rules in bot-item-question-answers.ts: which events can start, answer or end a question.
Linked Issue
N/A (internal report of slow item pages on long threads).
Visual Proof
N/A: no visual change. The same question shows as waiting; only how it is looked up changed.
Testing
I manually tested these changes locally (not in the app: the store-level benchmark below and unit tests on macOS)
Automated tests added/updated, or explained why not below:
Three tests in bot-items-open-questions.test.ts. One checks the new-event rule against full pairing for every event kind, so the two can't drift apart unnoticed. Through bot comments, a new question and its answer, an open always answers what pairing every event answers. Comments that ask nothing are answered from the stored answer without working it out again. A new question is worked out again and stored. A missing entry, or an event written by an older Orca, is worked out from the events.
The existing question-pairing tests now read through this path.
Every added test fails without this change and avoids the test anti-patterns
Platforms: macOS (unit tests and the store benchmark).
Performance
Measured with the item store on an on-disk WAL file on this head (M-series Mac, 1 KB comments, median of 21):
Item events
Bot comment
Comment, then open
Item open (this PR)
History read main does per open
600
0.11 ms
0.34 ms
0.24 ms
1.0 ms
3000
0.10 ms
0.55 ms
0.38 ms
7.0 ms
Writes do exactly what main does; an owner reply reads the stored answer the same way an open does. An open reads one row plus at most 64 events since the stored answer. It reads the whole history only after a new question, an answer while a question waits, or 64 new events, and then stores the result.
Risk
The riskiest part is the check of new events wrongly keeping an answer. If it did, the comment box could reply to the wrong question. The check only keeps an answer for events the pairing code ignores, or for answer and end events when no question is waiting. Anything else works the answer out from all events.
There is no schema version bump, so moving between this build and an older one keeps items writable. If the table can't be created, read or written, opens fall back to the full read, as on main, with at most one warning per run for each of creating and storing. A plain revert brings back the full read and leaves an unused table behind.
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)
… not its whole history
Since #47385 every item open read and parsed all of the item's events to find the question waiting
on the owner. The item row now keeps it, worked out when a comment or a move lands; a row from
before the column works it out once on its first open.
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
The change adds helpers to persist waiting-ask pairings and reconstruct them from item events when no valid stored pairing exists. Bot-item storage initializes the table for writable databases and uses the new lookup path. File-backed tests check reconstruction, clearing after a later status event, and consistency across comments, asks, and answers.
Merge Risk: Low · previous review 677d9
The change makes opening a bot item cheaper by reusing a stored waiting question instead of re-reading the full history. No functional or performance defect was established. One small test-cleanup gap remains, where a failing test can leave an extra database connection open. This is low risk and can be followed up after merge.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "Opening a bot item no longer reads its whole history" matches the main change. The PR stores each item's waiting question in a side table, so opening an item reads the stored answer plus on…
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 closely and is substantially complete. It has an ELI5, a detailed What Changed section with before/after and mechanism, a Why section explaining the app…
Full details: Title check
Explanation
The title "Opening a bot item no longer reads its whole history" matches the main change. The PR stores each item's waiting question in a side table, so opening an item reads the stored answer plus only later events instead of the full event history. The title is specific and short, and it describes the user-visible effect.
Full details: Description check
Explanation
The description follows the repository template closely and is substantially complete. It has an ELI5, a detailed What Changed section with before/after and mechanism, a Why section explaining the approach, Testing with specific tests and platforms, a Performance section with measured numbers, and a Risk section with level and revert plan. The Linked Issue section says N/A and gives an internal-report reason rather than an issue link. The Visual Proof section gives an N/A reason. The AI Disclosure section is empty. The Review section is empty, and the Testing checkbox for manual testing is unchecked while the text says manual app testing was not done. These gaps are non-critical, so the check passes.
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.
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 60facc0a-f193-44f4-8660-e638498bd60e
Commits
Reviewing files that changed from the base of the PR and between 818e5aa and 677d94d.
Files selected for processing: 3
src/main/bots/bot-item-waiting-ask-keep.ts
src/main/bots/bot-items-open-questions.test.ts
src/shared/bots/bot-item-question-answers.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.
Perf scan: #47478 (head ccfd3038574, range origin/main...HEAD)
Verdict: blocked, one P1. The fix works for opens: an open with an up-to-date kept ask no longer reads the item's history. But every comment or status write now re-reads and re-pairs the item's whole event history right after it commits, whether or not anyone will open the item. So the O(history) cost moved from opens to writes. Agent comments and status moves didn't pay it before.
Finding
P1: each comment or status write re-pairs the item's full event history, even for items nobody is viewing.
Where:src/main/bots/bot-item-waiting-ask-keep.ts:96-101 (keepAfterWrite, the item.pairs branch calling pairWaitingAsk). It is called from src/main/bots/bot-items-tables.tstransaction() after COMMIT (and from appendEvent outside a write). Introduced in this PR.
Trigger: every appendEvent of kind commented or status on a writable file. Paths that reach it:
bot comments (bot-items-writes.ts:53)
close and cancel (:76)
wait and status-text moves (:157, :168, bot-items-edits.ts:149/153/167)
owner moves and comments (bot-items-owner.ts:121/167/212/218)
moveToWait and the status writes in bot-items-tables.ts
Work per trigger:SELECT * FROM item_events WHERE item_uid = ? ORDER BY id, then for every row eventRecordOf (JSON parse of data), eventViewOf, and botItemQuestionPairing. That is O(E) rows and bytes for an item with E events. Nothing caps events per item, and a comment can be up to 8,000 chars. It runs on the bots DB worker and holds it, so the write RPC's reply and every queued bots read wait behind it.
Before vs after, per write:
Write
Base
Head
Bot comment or status move
0 history reads
1 full history read
Owner comment
1 (inside the transaction)
1 (after commit)
Close or cancel
0
1 (wasted: readers drop the ask once the item closes)
Why it is unnecessary: the lazy path already exists. waitingAskOf re-pairs and keeps on the next open when the kept row is stale. With K writes between opens, eager pairing costs K × O(E) and lazy costs 1 × O(E). With a view open, the cost is the same either way, because every write's change notice re-reads the open view once.
Price at the reference fleet: a dozen agents calling the CLI every few seconds gives about 2–3 comment or status writes per second. Each one reads the touched item's full thread: hundreds to thousands of events at fleet scale, 10× at the growth target, each row JSON-parsed. That cost grows with thread length on a repeated trigger, and it is paid for unobserved items. That makes it P1 (history-growing, unobserved work). It is off Electron main and off the renderer, so it is not P0. Not measured: no timing was run (review only, on battery). The impact above is the proven count per write.
Remedy (not verified): on a pairing write, don't pair. Drop the kept row instead (or leave it stale; the at = last_event_id check already invalidates it), and let the next open pair once and keep. Keep the cheap carry UPDATE for writes that don't pair. Also skip done and canceled. This keeps:
freshness: the kept row holds only while at matches last_event_id
the open-view case: the first re-read after a write pairs and keeps
the owner-comment transaction: it falls back to the full pair, as on base
Check that proves it: use a real BotItemsStore on a temp file with an item of E = 200 and then 2,000 events. Run 10 bot comment() calls with no view open. Count item_events full-history selects (or eventRecordOf calls): at most 1 per subsequent open, and 0 per write. It fails on this head (10 × E rows).
Work census (new or changed)
Work
Trigger
Population
Bound
keptWaitingAsk: one PK lookup joined to items
each owner.show (item open, each change-notice re-read of an open view, chip preview, mobile show) and the in-transaction waitingAsk of an owner comment
1 row per open item
O(1), indexed. Replaces the O(E) pairing that base ran on every open. Improvement.
pairWaitingAsk fallback on open, then keepWaitingAsk
open when nothing is kept, or the kept row is stale (an older build wrote, a keep failed, or the file is read-only)
per stale item
O(E) once, then kept. Read-only files pair on every open, the same as base.
pairWaitingAsk after commit
each commented or status event
every item written, observed or not
O(E) per write, unbounded in history. The P1 finding above.
Carry UPDATE item_waiting_asks SET at
each write of other event kinds (links, edits, unsnoozed…)
per touched item per write
O(1), PK. Fine.
lastEventOf SELECT in appendEvent
first event per item per write
1 per touched item
O(1), PK. Fine.
quietly: 3 busy_timeout pragmas around each keep
per keep
per touched item
O(1). Fine.
touched map
per transaction
items touched by one write (usually 1)
cleared in finally, no retention
ensureKeptWaitingAsks / hasKeptWaitingAsks
store open, first keepsWaitingAsks() call
1 per store
once per process, cached in this.keeps
New table item_waiting_asks
on disk
1 row per item ever paired
O(items), WITHOUT ROWID, no growth per event
Subscribers and listeners: no new subscription, emit or notification. The existing onBotsChanged listener in use-bot-item-view.ts (filtered by botId, kinds items and workers) re-reads owner.show for every open item view on any change to that bot. On base, each of those re-reads did a full pairing. Now it is one PK lookup while the kept row holds. Idle rate: unchanged (0 frames). No timers, polls or IPC added, so new idle wakeups/s are 0 on main, the renderer and the worker.
Regression classes touched
Re-reading unchanged input: matched. The open path is fixed: two opens with unchanged events do 1 indexed lookup each, not 2 full reads. The write path re-reads all of history per write even when the new event can't consume the result before the next open. That is the finding.
Sync fs or SQLite on Electron main: matched and disproved. BotItemsStore.open is only called in src/main/bots/db-worker/bots-db-worker-entry.ts:23, and the new file is added to config/main-blocking-worker-entries.json. The cost lands on the bots DB worker, which serializes bots RPCs. Priced in the finding.
Whole-file rewrite per change: matched and disproved. One keyed upsert per write, no whole-state flush.
Per-entity state outlives the entity: matched and disproved. touched is per transaction and cleared in finally. Table rows are per item (deleting an item leaves a stale orphan row of a few bytes; it is never read, because the join on items fails).
Hidden or unheard owners keep working: finding. Pairing on write runs with no viewer (the same finding).
The six questions
Unused work before the skip gate: finding. Write-time pairing runs before any open needs it, and even for closed items.
Ownership multiplies work: reviewed. The keep is per touched item, not per open view. Open views now share the kept row instead of each pairing. Improvement.
Which thread pays: reviewed. The bots DB worker (node:sqlite via SyncDatabase), not Electron main or the renderer. The post-commit pairing runs before the write returns, so it adds O(E) latency to bot comment and status RPCs.
What grows: finding. O(E) per write with unbounded E. Retry and progress: a failed keep leaves the row stale, and the next open re-pairs, so there is no stranded state. The at = last_event_id guard stops a late keep from overwriting a newer write.
Execution host: reviewed. The same code runs on local and remote hosts' bots worker. There are no per-item round trips over SSH (the show RPC is unchanged in shape). Busy and disk-full cases fall back quietly with busy_timeout = 0.
Obsolete work stops: reviewed. No timers or async work. Everything is synchronous inside the RPC and finishes there.
Examined:bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-owner.ts, bot-items-writes.ts, bot-items-edits.ts, shared/bots/bot-item-question-answers.ts, runtime/rpc/methods/bots-items-owner-methods.ts, renderer/.../bots/items/use-bot-item-view.ts, db-worker/bots-db-worker-entry.ts. Static trace only. Nothing was run (review only, no app launch). perf-surface-detect returned no surfaces.
Pre-existing, not from this PR: in botItemQuestionPairing, each owner comment calls answeredLines(open, …) over all open asks, so one pairing is O(E × open asks).
Residual gaps: no timing for one pairing at large E. The P1 rests on the source-proven count per write.
Perf scan: #47478 (head 5f0e6e0894c, range origin/main...HEAD)
Verdict: clear, no blocking finding. Opening an item now does one indexed lookup while the kept waiting ask is current. It reads the item's history only the first time after the kept ask goes stale, and then keeps the result. The P1 from the last scan (each comment or status write re-paired all of the item's history after it committed) is fixed. keepAfterWrite (src/main/bots/bot-item-waiting-ask-keep.ts:130-141) no longer pairs. It runs one keyed UPDATE or returns early, so a write's cost no longer grows with the thread.
Work census (new or changed)
Work
Trigger
Population
Bound
keptWaitingAsk: a lookup on the item_waiting_asks key, joined to items by its key
each owner.show (item open, each change-notice re-read of an open view), and waitingAsk inside an owner comment's transaction
1 row per item shown
O(1). Replaces the O(E) pairing that base ran on every open. Improvement.
pairWaitingAsk + keepWaitingAsk on open
an open when nothing is kept or the kept ask is stale (a question was asked, an answering write when an ask waits, an older build wrote, a keep failed)
per stale item
O(E) once, then kept. Adds one small autocommit upsert to that read, once per stale period. Read-only files pair on every open, the same as base.
pairWaitingAsk inside an owner comment's transaction
an owner comment while the kept ask is stale
1 item
O(E), not kept. Same as base, which paired on every owner comment.
keepAfterWrite carry UPDATE ... SET at
after commit, once per item the write touched
usually 1 item
O(1) by key, plus 3 busy_timeout pragmas. For asks writes it returns without touching the DB. Fixes the previous P1.
waitingAskChange → botItemQuestionShape(data)
each non-owner commented event
1 per event
parses one comment, capped at 8,000 chars. Constant.
lastEventOf
first event per item per write
1 per touched item
O(1) by key
touched map
per transaction()
items one write touches
cleared in finally, nothing kept
ensureKeptWaitingAsks, hasKeptWaitingAsks
store open, first keepsWaitingAsks()
1 per store
once per process. The result is cached in this.keeps.
Table item_waiting_asks
on disk
1 row per item ever paired (items are never deleted)
O(items), WITHOUT ROWID, nothing added per event
Per write, base vs head:
Write
Base
Head
Bot comment or status move
0 history reads
0 history reads, plus 1 keyed UPDATE
Bot question
0
0 (the kept ask is left stale)
Owner comment
1 full read (inside the transaction)
0 while the kept ask holds, else 1 (as base)
Close or cancel
0
0
Per open: base did 1 full read of E events every time. Head does 1 keyed lookup, or 1 full read and 1 small upsert when the kept ask is stale. Head is at or below base on every path.
Price at the reference fleet: a dozen agents calling the CLI every few seconds is about 2–3 writes/s. Each adds one keyed UPDATE and 3 pragmas on the bots DB worker. That stays constant in thread length, item count and fleet size. Each open view's re-read after a change costs one keyed lookup, where base paid O(E). Nothing new runs on Electron main or the renderer. No timers, polls, subscriptions or IPC were added, so new steady-idle wakeups are 0/s on main, the renderer and the worker, the same as base.
Not blocking: the fix is incomplete for one common case (behavior is no worse than base)
waitingAskChange (bot-item-waiting-ask-keep.ts:26) treats every commented or status event as answers. When an ask is waiting (kept ask ≠ 0), the carry UPDATE then matches no row and the kept ask goes stale. But botItemQuestionPairing (src/shared/bots/bot-item-question-answers.ts:152-171, 43-48) can't be changed by:
a bot comment that asks nothing (continue at :170)
a non-answer move to needs_you
So while an agent posts progress comments under an earlier ask that is still waiting, every open after each comment still reads all E events. This is the case the PR describes, where a later question leaves an earlier one open. With a view open, that is one O(E) read per bot comment, the same as base. It is not a regression, but the issue stays partly unfixed there. Possible remedy (not verified): only owner comments, closes, endsAsks moves and cause: 'answer' moves would count as answers. Everything else would carry. To check it: on a real file store with a waiting ask and E = 200, then 2,000, post 10 bot plain comments and open after each. Expect 0 full item_events selects. Today it is 10.
Regression classes touched
Re-reading unchanged input: matched and fixed. Two opens with unchanged events do 1 lookup each (the first may pair once if stale). Remaining re-reads are limited to the stale case above. Not a regression.
Sync fs or SQLite on Electron main: matched and disproved. BotItemsStore.open runs only in src/main/bots/db-worker/bots-db-worker-entry.ts, and the new file is listed in config/main-blocking-worker-entries.json.
Whole-file rewrite per change: matched and disproved. One keyed UPDATE per touched item per write, and at most one keyed upsert per stale open. No whole-state flush.
Hidden or unheard owners keep working: matched and disproved. Writes no longer pair for items nobody opens. Pairing happens only when something opens the item.
Per-entity state outlives the entity: matched and disproved. touched is cleared in finally. Table rows are one per item, and items are never deleted.
New wakeups in steady idle: no matching code (0 new timers or listeners).
The six questions
Unused work before the skip gate: reviewed. The previous eager pairing on writes is gone. botItemQuestionShape runs on each non-owner comment, which costs one bounded parse.
Ownership multiplies work: reviewed. The keep is per item, not per open view. Open views share the kept row.
Which thread pays: reviewed. The bots DB worker (node:sqlite via SyncDatabase). The carry runs after COMMIT with busy_timeout = 0, so it never waits on another writer. A stale open now adds one small autocommit write to a read RPC, once per stale period.
What grows: reviewed. Write cost is O(1) in E. Open cost is O(1), or O(E) once per stale period. Progress: a failed or skipped keep leaves the row stale, and the next open pairs and keeps it. The at = last_event_id guard stops a late keep from overwriting a newer event.
Execution host: reviewed. The same code runs on local and remote hosts' bots worker. The show RPC's shape is unchanged, so there are no new per-item round trips over SSH. A read-only file skips keeping and pairs on every open (as base). A busy or full disk fails quietly and warns once per run.
Obsolete work stops: reviewed. Everything is synchronous inside the RPC, with no async or timer work left behind.
Examined:
the files this PR changes: bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-open-questions.test.ts, config/main-blocking-worker-entries.json
the callers: bot-items-owner.ts, bot-items-writes.ts, bot-items-edits.ts, bot-items-runtime.ts (views), runtime/rpc/methods/bots-items-owner-methods.ts
This was a static trace only. Nothing was run (review only, no app launch, on battery), so there are no timing claims. perf-surface-detect surfaces: none.
Pre-existing, not from this PR:botItemQuestionPairing calls answeredLines(open, …) over all open asks for each owner comment, so one pairing costs O(E × open asks).
Residual gaps: no timing for one pairing at large E. That cost now runs only on stale opens.
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: cb7938ac-03e2-4562-abd3-f3e931ef7eb6
Commits
Reviewing files that changed from the base of the PR and between ccfd303 and 5f0e6e0.
Files selected for processing: 3
src/main/bots/bot-item-waiting-ask-keep.ts
src/main/bots/bot-items-open-questions.test.ts
src/main/bots/bot-items-tables.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.
Verdict: clear. No perf findings. Opening an item no longer reads all of its events while the kept ask holds. This head makes two changes since the last scan (5f0e6e0):
One write's carries now share a single transaction, instead of one autocommit per item.
waitingAskChange now gives null (carry any kept ask) for a bot comment that asks nothing and for a move onto Needs you that no answer made. That closes the gap the last scan flagged: progress comments under an earlier ask that is still waiting no longer make the kept ask stale.
Work that is new or changed
Work
Trigger
Population
Bound
keptWaitingAsk: keyed SELECT ... JOIN items
each show RPC (views(..., true)), and each owner comment inside its transaction
1 item
O(1) by primary key. Base did a full read of all E events every time.
pairWaitingAsk: full read of item_events plus pairing
an open or owner comment while the kept ask is stale (missing, or an older build wrote after it)
1 item
O(E), and pairing costs O(E × open asks), as base. It runs once per stale period, because the next open keeps the result.
keepWaitingAsk: guarded upsert
after a stale pairing outside a write
1 item
O(1), autocommit, busy_timeout = 0. It is skipped when a write landed after the read (last_event_id guard).
keepAfterWrite: BEGIN IMMEDIATE, one keyed UPDATE per carried item, COMMIT, 3 pragmas
after each committing write that has at least one non-asks touched item
items one write touched: 1 for most writes, uids.length for a bulk owner status write
O(touched items), each O(1). Changed at this head: 1 transaction per write instead of 1 commit per item. It does nothing for writes that only ask. The carry statement is prepared once per write, and SyncDatabase caches it.
lastEventOf: keyed SELECT last_event_id
first event per item per write
1 per touched item
O(1)
waitingAskChange → botItemQuestionShape(data)
each non-owner commented event
1 per event
Parses one comment (bounded text). Constant. Changed at this head: the categories are now null, answers and asks, and they match botItemQuestionPairing (src/shared/bots/bot-item-question-answers.ts:43-48, 143-170).
touched map
per transaction()
items in that write
Set to null in finally, so nothing outlives the write.
ensureKeptWaitingAsks / hasKeptWaitingAsks
store open, first keepsWaitingAsks()
1 per store
Once per process. The result is cached in this.keeps.
Table item_waiting_asks (WITHOUT ROWID)
on disk
1 row per item paired at least once
O(items). Nothing is added per event.
Per write, base vs head:
Write
Base
Head
Bot comment that asks nothing, bot status move
0 history reads
0 history reads. One carry transaction: 1 keyed UPDATE per item.
Bot question
0
0, and no carry transaction
Owner comment
1 full read inside the transaction
0 while the kept ask holds, else 1 (as base). Then a carry that applies only while no ask waits.
Bulk owner status over N items
per-item owner-comment reads, as above
the same, plus 1 carry transaction with N keyed UPDATEs
Per open: base read all E events every time. Head does 1 keyed lookup, or 1 full read and 1 small upsert once per stale period. Head is at or below base on every read path.
Price at the reference fleet. A dozen agents calling the CLI every few seconds makes about 2–3 item writes/s. Each write adds one short write transaction on the bots DB worker.
When the UPDATE changes a row, that is one extra WAL commit (and its sync) per write. That is about 2–3/s, which is less than the previous head's one commit per touched item.
A carry that matches no row writes no WAL frames.
The cost is constant in thread length E, item count and fleet size, and it pays for O(1) opens. Nothing new runs on Electron main or in the renderer. No timers, polls, subscriptions or IPC were added, so steady-idle wakeups are 0/s on main, the renderer and the worker, the same as base.
Regression classes touched
Re-reading unchanged input: matched and fixed. Two opens with no new events cost 1 keyed lookup each, and the first may pair once if the kept ask is stale. Bot comments that ask nothing now keep a waiting ask, so the remaining re-reads come only from a new question or a write by an older build.
Sync fs or SQLite on Electron main: matched and disproved. BotItemsStore.open runs only in the bots DB worker, and bot-item-waiting-ask-keep.ts is listed in config/main-blocking-worker-entries.json.
Whole-file rewrite per change: matched and disproved. A write does keyed UPDATEs for the items it touched, and a stale open does at most one keyed upsert. There is no whole-state flush.
Hidden or unheard owners keep working: matched and disproved. Writes never pair. Pairing happens only when something opens the item, or inside an owner comment, as in base.
Per-entity state outlives the entity: matched and disproved. touched is cleared in finally. The table holds one row per item, and items are never deleted.
Unbounded fan-out or queues: matched and disproved. The carry loop is synchronous, and its length is the number of items the write already touched.
New wakeups in steady idle: no matching code (0 new timers or listeners).
The six questions
Is unused work paid for before the skip gate? Reviewed. Writes don't pair. keepAfterWrite returns before BEGIN when every touched item asked. botItemQuestionShape runs only on non-owner comments, at one bounded parse each.
Does ownership multiply or recreate work? Reviewed. The kept ask is per item, not per open view, so views share the row. keeps is computed once per store.
Which thread and storage layer pays? Reviewed. The bots DB worker (node:sqlite via SyncDatabase, with cached statements). The carry runs after the write's COMMIT, in its own BEGIN IMMEDIATE with busy_timeout = 0, so it never waits on another writer and never fails the write. A failure rolls back, leaves the kept ask stale and warns once per run. A failed BEGIN is outside the inner try, so nothing is rolled back that we didn't start.
What grows, and does the next attempt advance? Reviewed. Write cost is O(touched items), independent of E. Open cost is O(1), or O(E) once per stale period. A failed or skipped keep leaves the row stale, and the next open pairs and keeps it. Both the carry (at = before and the last_event_id check) and the keep stop a late update from overwriting a newer event.
What does the execution host change? Reviewed. The same code runs in each host's bots worker. The show RPC's shape is unchanged, so there are no new per-item SSH round trips. A read-only file skips keeping and pairs on every open, as base. A busy or full disk fails quietly.
Does obsolete work stop and release its budget? Reviewed. Everything runs synchronously inside the RPC or write, and no async work, waiters or timers remain afterwards.
Examined:
the files this PR changes: bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-open-questions.test.ts, config/main-blocking-worker-entries.json
shared/bots/bot-item-question-answers.ts (pairing, which I checked against the new categories)
This was a static trace only. Nothing was run (review only, no app launch, on battery), so there are no timing claims.
Pre-existing, not from this PR: pairing calls answeredLines over all open asks for each owner comment, so one pairing costs O(E × open asks). That cost now runs only on stale opens and on owner comments while the kept ask is stale.
Residual gaps:
No timing for one pairing at large E.
No count of WAL syncs per write under the real synchronous setting.
Verdict: clear. I found no P0 or P1. Opening an item used to read and pair all E of its events every time. It now reads one kept row plus at most 65 events found by index. The full O(E) pairing runs only when a question, or an answer to a kept ask, landed since the kept row, or when more than 64 events have piled up since it. After that pairing the open keeps a fresh row, so the next open is short again. Writes no longer touch the side table.
items.show / events-page RPC with withWaitingAsks (bots-items-owner-methods.ts:149). Runs on a user open, once per open item
1 item per open
1 PK lookup on item_waiting_asks + 1 range seek on idx_item_events_item(item_uid,id) with LIMIT 65: ≤65 rows parsed and classified. Constant in E (base: all E rows + O(E × open asks) pairing)
waitingAskOf, stale fallback → pairWaitingAsk + keepWaitingAsk
same open, when a question, an answer to a kept ask, or more than 64 events landed since at, or no row exists
1 item
O(E) read + pairing (same as base, every open), then 1 guarded INSERT … ON CONFLICT outside any transaction with busy_timeout = 0 (3 pragma statements, all cached). Once per stale period: a later open that changes nothing writes nothing
kept-check ≤65 events, else O(E) pairing as base. writing flag stops any keep inside the write, so no extra write and no lock wait
ensureKeptWaitingAsks (bot-items-store.ts:19)
store open, writable file
1 per store open
1 CREATE TABLE IF NOT EXISTS, one-time
hasKeptWaitingAsks (bot-items-tables.ts:137)
first waitingAsk per store
1 per store instance
1 sqlite_master query, cached in keeps
item_waiting_asks rows
stale opens
≤1 row per item ever opened while open (items are never deleted)
~3 integers per row, keyed by uid (WITHOUT ROWID)
Price at fleet scale: opens come from the user, a few per second at most. With 10× history (an item with tens of thousands of events), a kept open costs ≤65 event rows, against E rows before. Agents and CLI writes (a dozen agents every few seconds) pay nothing new. Owner comments pay ≤65 rows, or the old O(E). Nothing new runs at idle (0 → 0 wakeups/s on main, renderer and the bots worker).
Regression classes touched
Re-reading unchanged input: matched, and this PR fixes it. The kept row is keyed by event id (at, plus a check against last_event_id when keeping). Events are immutable: the only UPDATE item_events statements set action or mail, not kind, actor or data. So an unchanged item re-reads ≤65 rows and writes nothing.
Sync fs or SQLite on Electron main: disproved. All of it runs in the bots DB worker, and the new file is added to config/main-blocking-worker-entries.json.
Whole-file rewrite per change: disproved. A keep is one small upsert, made only on a stale open, and writes do not keep.
Per-entity state outlives the entity: disproved. That's one row per item, and items are never deleted. In memory there's only the per-store keeps flag and a once-per-run keepFailureTold boolean.
Hot-path rescans: disproved. The check is capped at 65 rows, uses the existing index, and classifies each row once (waitingAskChange, one botItemQuestionShape per non-owner comment).
Expensive code reachable past a gate: no matching code. No gate was removed. withWaitingAsks callers are unchanged: only the single-item show RPC passes true.
New wakeups in steady idle: no matching code. There are no timers, polls or subscriptions.
Six questions
Is unused work paid for before the skip gate? Reviewed. The cheap check runs before any full read. List and summary views still skip waiting asks (withWaitingAsks = false).
Does ownership multiply or recreate work? Reviewed. There is one store per DB worker, and the per-store cache (keeps) is computed once. There are no per-row or per-pane owners.
Which thread and storage layer pays? Reviewed. All work runs in the bots DB worker. Statements come from the SyncDatabase statement cache. A keep runs outside the write transaction with busy_timeout = 0, so it never waits on another writer, and failures are quiet.
What grows, and does the next attempt advance? Reviewed. A kept open is O(1) in E. A stale open is O(E) once, and its keep moves at to the newest event, so the next open is short. A failed keep (busy or full disk) leaves the old row, and the next open retries. A read-only file pairs on every open, as base does.
What does the execution host change? Reviewed. The same code runs in each host's bots worker. The RPC shape is unchanged, so there are no new SSH round trips.
Does obsolete work stop and release its budget? Reviewed. Everything is synchronous inside the RPC or write, and nothing async remains afterwards.
Pre-existing, not from this PR: a full pairing calls answeredLines over all open asks for each owner comment, so it costs O(E × open asks). It now runs only on stale opens, and inside an owner comment write only when the kept check fails.
Examined:
the files this PR changes: bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-open-questions.test.ts, config/main-blocking-worker-entries.json
the callers: bot-items-owner.ts, bot-items-runtime.ts (views), runtime/rpc/methods/bots-items-owner-methods.ts, runtime/rpc/methods/bots-items.ts
Verdict: clear. I found no P0 or P1. Before this PR, opening an item read and paired all E of its events every time. Now it reads one kept row plus at most 65 events, found through the index. The full O(E) pairing runs only when:
a question landed since the kept row,
an answer to a kept ask landed since the kept row,
more than 64 events piled up since the kept row,
there is no kept row,
or the kept row was worked out under different pairing rules (new in 677d94d).
After a full pairing, the open keeps a fresh row, so the next open is short again. Writes still never touch the side table.
What the last commit changes: it adds a rules column to item_waiting_asks. The kept-row lookup now also filters AND rules = ?, and the upsert writes one more integer. The lookup is still a single primary-key seek with one extra column compare. A row kept under other rules counts as a miss: that open pairs in full (O(E), the same as every base open) and overwrites the row with the current rules. So the next open on this build is short again.
items.show RPC (bots-items-owner-methods.ts:149, the only withWaitingAsks = true caller), via viewRows (bot-items-reads.ts:168). User-driven, once per open item.
1 item per open
1 primary-key lookup on item_waiting_asks (item_uid, plus a rules compare), then 1 range seek on idx_item_events_item(item_uid, id) with LIMIT 65. At most 65 rows parsed and classified once each by waitingAskChange. Constant in E (base: all E rows, plus O(E × open asks) pairing).
waitingAskOf, stale path → pairWaitingAsk + keepWaitingAsk
The same open, in any of the full-pairing cases listed above
1 item
O(E) read and pairing, as base does on every open. Then 1 guarded INSERT … ON CONFLICT outside any transaction, with busy_timeout = 0 (3 cached pragma statements). Happens once per stale period: a later open with nothing new writes nothing.
waitingAsk inside an owner comment (bot-items-owner.ts:77)
Owner comment write, inside BEGIN IMMEDIATE
1 item
Kept check of at most 65 events, else O(E) as base. The writing flag stops any keep inside the write, so there is no extra write and no lock wait.
ensureKeptWaitingAsks (bot-items-store.ts:19)
Store open on a writable file
1 per store open
1 CREATE TABLE IF NOT EXISTS, one time
hasKeptWaitingAsks (bot-items-tables.ts:137)
First waitingAsk call per store
1 per store instance
1 sqlite_master query, cached in keeps
item_waiting_asks rows
Stale opens
At most 1 row per item ever opened while open (items are never deleted)
4 small columns per row, WITHOUT ROWID
Price at fleet scale:
Opens come from the user, a few per second at most. At 10× history (an item with tens of thousands of events), a kept open costs at most 65 event rows, against E rows before.
Agent and CLI writes (a dozen agents calling every few seconds) pay nothing new.
Owner comments pay at most 65 rows, or the old O(E).
Nothing new runs at idle: 0 → 0 wakeups/s on main, renderer and the bots worker.
Upgrading or downgrading the rules re-pairs each item once, on its next open. If two builds with different rules took turns opening the same item in one file, each of those opens would cost O(E). That is never more than base, which pays O(E) on every open.
Regression classes touched
Re-reading unchanged input: matched, and this PR fixes it. The kept row is keyed by event id (at, with a check against last_event_id when keeping) and by rules. Events are immutable: the only UPDATE item_events statements set action or mail, never kind, actor or data. An unchanged item re-reads at most 65 rows and writes nothing.
Sync fs or SQLite on Electron main: disproved. All of it runs in the bots DB worker, and the new file is listed in config/main-blocking-worker-entries.json.
Whole-file rewrite per change: disproved. A keep is one small upsert, made only on a stale open. Writes never keep.
Per-entity state outlives the entity: disproved. The table holds one row per item, and items are never deleted. In memory there is only the per-store keeps flag and a once-per-run keepFailureTold boolean.
Hot-path rescans: disproved. The check is capped at 65 rows, uses the existing index, and classifies each row once (one botItemQuestionShape per non-owner comment).
Expensive code reachable past a gate: no matching code. No gate was removed, and the withWaitingAsks callers are unchanged: only the single-item show RPC passes true.
New wakeups in steady idle: no matching code. There are no timers, polls or subscriptions.
Six questions
Is unused work paid for before the skip gate? Reviewed. The cheap kept check, including the rules compare, runs before any full read. List and summary views still skip waiting asks (withWaitingAsks = false).
Does ownership multiply or recreate work? Reviewed. There is one store per DB worker, and its keeps cache is computed once. There are no per-row or per-pane owners.
Which thread and storage layer pays? Reviewed. Everything runs in the bots DB worker, and statements come from the SyncDatabase statement cache. A keep runs outside the write transaction with busy_timeout = 0, so it never waits on another writer, and its failures are quiet.
What grows, and does the next attempt advance? Reviewed.
A kept open is O(1) in E.
A stale open, or one that finds another build's rules, pays O(E) once. Its keep moves at to the newest event and sets the current rules, so the next open advances.
A failed keep (busy or full disk) leaves the old row, and the next open retries.
A read-only file pairs on every open, as base does.
What does the execution host change? Reviewed. The same code runs in each host's bots worker. The RPC shape is unchanged, so there are no new SSH round trips.
Does obsolete work stop and release its budget? Reviewed. Everything is synchronous inside the RPC or the write, and nothing async is left afterwards.
Pre-existing, not from this PR: a full pairing calls answeredLines over all open asks for each owner comment, so it costs O(E × open asks). It now runs only on stale opens, and inside an owner comment write only when the kept check fails.
Not perf, but worth a look: a file written by an earlier build of this branch already has a 3-column item_waiting_asks table. CREATE TABLE IF NOT EXISTS leaves that table alone, and SELECT … AND rules = ? would then fail with "no such column", which waitingAskOf does not catch. This only affects files from unreleased builds of this branch. If none of those builds went out, nothing needs to change.
Examined:
The files this PR changes: bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-open-questions.test.ts, shared/bots/bot-item-question-answers.ts, config/main-blocking-worker-entries.json.
The callers: bot-items-owner.ts, bot-items-runtime.ts (views), runtime/rpc/methods/bots-items-owner-methods.ts.
bot-items-schema.ts, for the indexes.
This was a static trace only. Nothing was run (review only, no app launch, on battery), so there are no timing claims.
Residual gaps:
No timing for one full pairing at large E.
No measured size of the at most 65 SELECT * rows when comments carry large data.
Verdict: clear. I found no P0 or P1 in origin/main...8bc55abe8ab. On base, every item open read and paired all E of the item's events. On this head, an open reads one kept row and then at most 65 events through idx_item_events_item(item_uid, id). The full O(E) pairing runs only in these cases:
a question landed after the kept row;
an answer to a kept ask landed after it;
more than 64 events landed after it;
there is no kept row, or it was kept under other rules;
the side table can't be read.
A full pairing on a writable file keeps a fresh row, so the next open is short again. Writes never touch the side table.
What the last commit changes:keptRow now catches a failed read and treats it as a miss. That covers a table shape another build left, for example the 3-column table from earlier builds of this branch. In that case every open pairs in full, the same as base. The upsert into that table then fails without being retried, quietly logs it once per run, and nothing else runs. The rest of the commit is comments only (bot-item-ask.ts, bot-item-answer-lines.ts, bot-item-question-answers.ts). This also settles the "not perf" note from the earlier scan.
The bots.items.owner.show RPC (bots-items-owner-methods.ts:149, the only withWaitingAsks = true caller), through viewRows (bot-items-reads.ts:169). An open item view calls it on mount and again on every onBotsChangeditems/workers event for that bot (use-bot-item-view.ts:129), one read in flight at a time. A chip preview calls it once when it opens.
1 item per call, per open view
1 primary-key seek on item_waiting_asks, then 1 index range seek with LIMIT 65. At most 65 rows are parsed, and waitingAskChange classifies each once (botItemQuestionShape only for bot comments). Constant in E. When nothing landed since the kept row, the range is empty. Base read all E rows each time, plus O(E × open asks) pairing.
waitingAskOf, stale path → pairWaitingAsk + keepWaitingAsk
The same call, in one of the full-pairing cases above
1 item
O(E) read and pairing, the same as every base open. Then 1 guarded INSERT … ON CONFLICT in autocommit, with busy_timeout = 0 around it (3 pragma calls). The keep moves at to the newest event, so a stale period costs one full pairing and one row write. The next call checks only the events after that.
waitingAsk inside an owner comment (bot-items-owner.ts:77)
An owner comment write, inside BEGIN IMMEDIATE
1 item
A kept check of at most 65 events, else O(E) as on base. writing = true turns off keeping inside the write, so it adds no extra write and no lock wait.
ensureKeptWaitingAsks (bot-items-store.ts:19)
Store open on a writable file
Once per process per DB
1 CREATE TABLE IF NOT EXISTS. One-time, never repeats.
1 sqlite_master lookup, cached in keeps after that.
item_waiting_asks rows
One per item whose ask was paired in full on a writable file
≤ item count (items are never deleted)
4 integer/text columns, WITHOUT ROWID. Grows with items, not with events or opens.
Regression classes touched
Re-reading unchanged input. Disproved. On base, every repeat open of an unchanged item re-read all E events. Now a repeat open with nothing new reads 1 row and an empty range, and repeat opens with a few new non-asking events read at most 64 rows. A passing check does not move at, so up to 64 events can be read again on each call until one fallback pairs in full and keeps a new row. That is a fixed constant, independent of E and of opens.
Sync fs or SQLite on Electron main. No matching code. All SQL runs in the bots DB worker. The new file is added to config/main-blocking-worker-entries.json, and its importers are bot-items-tables.ts and bot-items-store.ts, both already listed as worker-only.
Whole-file rewrite per change. Disproved. A keep is one row upsert, and only after a full pairing. Writes add nothing.
Per-entity state outlives the entity. Disproved. There is one row per item and items are never deleted. The in-memory state is two fields per store (writing, keeps) and one module flag (keepFailureTold).
Hot-path rescans. Disproved. new Set(since.map(...)) runs over at most 65 rows once per call, with no nested scan.
Expensive code newly reachable past a gate. Disproved. The full pairing is the code base ran on every open. It now runs on fewer calls, under the same isOpenBotItemStatus and withWaitingAsks gates.
Fixed-cadence poll, new idle wakeups, hidden owners. No matching code. The PR adds no timer, subscription or IPC. Re-reads on onBotsChanged are pre-existing and only became cheaper.
Six questions
Is unused work paid for before the skip gate? Reviewed. waitingAsk runs only for open items, and only on the single-item show path or the owner comment write. List views pass withWaitingAsks = false (bot-active-work-read.ts:59, bots-items.ts:58, bots-items-owner-methods.ts:99/123), so they pay nothing.
Does ownership multiply or recreate work? Reviewed. Each open view makes one call per bots-changed event, with re-reads coalesced by running/again. That cadence is pre-existing, and the cost per call drops from O(E) to at most 65 rows. The store and its keeps cache are created once per process.
Which thread and storage layer pays? Reviewed. Everything runs in the bots DB worker, using SyncDatabase cached statements. A keep runs outside any transaction with busy_timeout = 0, so it never waits on another writer. A failed keep is quiet and leaves the old row in place.
What grows, and does the next attempt advance? Reviewed.
A kept open is O(1) in E.
A stale open pays O(E) once, and its keep moves at to items.last_event_id. That column is set on every event insert (bot-items-tables.ts:121, the only INSERT INTO item_events), so the guard holds and the next open advances.
A keep that loses to a concurrent write, or fails as busy, leaves the next open to retry.
On a read-only file or an unreadable table, every open pairs in full, as base does. That is no regression, but it never advances on that file.
What does the execution host change? Reviewed. The same code runs in each host's bots worker, local or remote. Mobile uses the same RPC (runtime-rpc-mobile-bot-methods.ts). The RPC shape is unchanged, so there are no new SSH round trips.
Does obsolete work stop and release its budget? Reviewed. Everything runs synchronously inside the RPC or the write. Nothing async is left behind, and busy_timeout is restored in finally.
Pre-existing, not from this PR:
A full pairing calls answeredLines over all open asks for each owner comment, which is O(E × open asks). It now runs only on stale opens, and inside an owner comment write only when the kept check fails.
An open item view re-reads show on every items change for any item of that bot (use-bot-item-view.ts:129). That fan-out is unchanged. Its cost per call drops with this PR.
Examined:
The files this PR changes: bot-item-waiting-ask-keep.ts, bot-items-tables.ts, bot-items-reads.ts, bot-items-store.ts, bot-items-open-questions.test.ts, the three shared/bots files, and config/main-blocking-worker-entries.json.
The callers and consumers: bot-items-owner.ts, bot-items-runtime.ts, bots-items-owner-methods.ts, bots-items.ts, bot-active-work-read.ts, use-bot-item-view.ts, use-bot-items.ts, bot-item-chip-preview.ts.
bot-items-schema.ts, for the indexes.
This was a static trace only. Nothing was run (review only, no app launch, on battery), so there are no timing claims.
Residual gaps:
No timing for one full pairing at large E.
No measured size of the at most 65 SELECT * rows when comments carry large data.
Verdict: clear. I found no P0 or P1 in origin/main...1fa63aa524d. The only change since the last scan (8bc55abe8ab) is commit 1fa63aa, which adds a two-line comment to src/shared/bots/bot-item-ask.ts and no code. I traced the whole diff again from scratch.
Base vs head. On base, every open of a bot item read all E of its events with SELECT * and paired them. On head, an open reads one kept row from item_waiting_asks, then reads at most 65 events past it through idx_item_events_item(item_uid, id). The full O(E) pairing still runs when:
a question, or an answer to a kept ask, landed after the kept row;
more than 64 events landed after it;
the item has no kept row, or its row was kept under other WAITING_ASK_RULES;
the table can't be read;
the file is read-only.
On a writable file, a full pairing keeps a fresh row with at = last_event_id, so the next open is short again.
bots.items.owner.show (bots-items-owner-methods.ts:149), the only caller that passes withWaitingAsks = true, through viewRows (bot-items-reads.ts:168). An open item view calls it on mount and on every items/workers change for that bot (use-bot-item-view.ts:129), with one read in flight. A chip preview calls it once.
1 item per call, per open view
1 primary-key read, then 1 index range read with LIMIT 65. Each of those ≤ 65 rows is parsed once and classified once by waitingAskChange (which runs botItemQuestionShape only on non-owner comments). Constant in E. If nothing landed since the kept row, the range is empty.
waitingAskOf, stale path: pairWaitingAsk + keepWaitingAsk
The same call, in one of the full-pairing cases above
1 item
O(E) read plus O(E × open asks) pairing, the same as every base open. Then 1 guarded INSERT … ON CONFLICT outside any transaction, wrapped in busy_timeout = 0 (3 pragma calls). A stale period costs one full pairing and one row write; after that, opens check only the events since.
waitingAsk inside an owner comment (bot-items-owner.ts:77)
Owner comment write, inside BEGIN IMMEDIATE
1 item
A kept check of ≤ 65 events, else O(E) as on base. writing = true skips the keep, so a write gains no extra write and no lock wait.
One per item that was fully paired on a writable file
≤ item count
4 integer/text columns, WITHOUT ROWID. Grows with items only, not with events or opens.
1fa63aa and the other shared/bots edits
None (comments only)
n/a
No runtime work.
Regression classes touched
Re-reading unchanged input: disproved.
On base, every open of an unchanged item re-read all E events.
On head, an open with nothing new reads 1 row and an empty range.
A passing check does not move at, so up to 64 non-asking events can be re-read on each open until one fallback pairs in full and keeps a new row. That is a fixed constant, independent of E and of how often the item is opened.
Sync fs or SQLite on Electron main: no matching code. All SQL runs in the bots DB worker. The new file is listed in config/main-blocking-worker-entries.json, and its only importers (bot-items-tables.ts, bot-items-store.ts) are listed as worker-only.
Whole-file rewrite per change: disproved. A keep is a single-row upsert, and it runs only after a full pairing. Writes add nothing.
Per-entity state outlives the entity: disproved.
The table holds one row per item, and items are never deleted.
In memory: two fields per store (writing, keeps) and one module flag (keepFailureTold).
Hot-path rescans: disproved. new Set(since.map(...)) builds once per call over ≤ 65 rows, with no nested scan.
Expensive code newly reachable past a gate: disproved.
The full pairing is what base ran on every open. It now runs on fewer calls, behind the same isOpenBotItemStatus and withWaitingAsks gates.
The list readers bot-active-work-read.ts:59, bots-items.ts:58/80 and bots-items-owner-methods.ts:99/123, and the viewRows callers in bot-items-runtime.ts:324 and bot-item-usage-limit-wait.ts:82, all leave withWaitingAsks false.
Fixed-cadence poll, new idle wakeups, hidden owners: no matching code. The PR adds no timer, subscription or IPC. Idle wakeups/s are 0 → 0 on main, renderer and the worker.
Six questions
Is unused work paid for before the skip gate? Reviewed. Waiting asks are computed only for open items, on the single-item show path or inside an owner comment write. Lists pay nothing.
Does ownership multiply or recreate work? Reviewed. Each open view makes one call per bots-changed event, coalesced by running/again. That cadence is pre-existing; the cost per call drops from O(E) to ≤ 65 rows. The store and its keeps cache are made once per process.
Which thread and storage layer pays? Reviewed. Everything runs in the bots DB worker on cached SyncDatabase statements. A keep runs outside any transaction with busy_timeout = 0, so it never waits on another writer. A failed keep is quiet and leaves the old row in place.
What grows, and does the next attempt advance? Reviewed.
A kept open is O(1) in E.
A stale open pays O(E) once. Its keep is guarded on items.last_event_id, which the only INSERT INTO item_events path updates (bot-items-tables.ts:121), so the guard is sound and the next open advances.
A keep that loses a race or hits busy leaves the next open to retry.
On a read-only file or an unreadable table, every open pairs in full, the same as base. That is no regression, but on that file opens never get faster.
What does the execution host change? Reviewed. Each host runs the same code in its own bots worker, local or remote, and mobile uses the same RPC. The RPC shape is unchanged, so there are no new SSH round trips.
Does obsolete work stop and release its budget? Reviewed. All of it runs synchronously inside the RPC or the write, nothing async is left behind, and busy_timeout is restored in finally.
Pre-existing, not from this PR:
A full pairing calls answeredLines over every open ask for each owner comment, which is O(E × open asks). It now runs only on stale opens.
An open item view re-reads show when any item of its bot changes (use-bot-item-view.ts:129). That fan-out is unchanged, and each re-read is now cheaper.
Examined:
Every file in the diff.
The callers and consumers listed in the marker.
bot-items-schema.ts, for the indexes.
This was a static trace only: no app launch and no benchmarks (review only, on battery), so this comment makes no timing claims.
Residual gaps:
No timing for one full pairing at large E.
No measured size of the ≤ 65 SELECT * rows when comments carry large data.
Verdict: clear. I found no P0 or P1 in origin/main...494696dab90. Since the last scan (1fa63aa524d), the only change is commit 494696d. It rewords the comment headers in src/shared/bots/bot-item-ask.ts and src/shared/bots/bot-item-answer-lines.ts (+4/−8) and changes no code. I still traced the whole diff again from the start, as if it were new.
Base vs head. On base, every open of a bot item ran SELECT * over all E of its events and paired them. On head, an open does three things:
It reads the item's kept row in item_waiting_asks, matched on rules = WAITING_ASK_RULES.
It reads at most 65 events after that row through idx_item_events_item(item_uid, id).
It sorts each of those events with waitingAskChange.
The full O(E) pairing still runs in these cases:
a question landed after the kept row
an answer or a move landed after a kept ask that isn't "none"
more than 64 events landed after the kept row
the item has no kept row, or its row was kept under other rules
the table can't be read
the file is read-only
On a writable file, after a full pairing outside a write, the open stores one row guarded on items.last_event_id (bot-items-tables.ts:121, the only path that adds events). The next open is short again.
bots.items.owner.show (bots-items-owner-methods.ts:149) is the only caller that passes withWaitingAsks = true; it goes through viewRows (bot-items-reads.ts:168). An open item view reads on mount and on every items/workers change for its bot, one read in flight (use-bot-item-view.ts:129).
1 item per call, per open view
1 primary-key read, then 1 index range read with LIMIT 65. Each row is parsed once and sorted once; only comments from someone other than the owner run botItemQuestionShape. Constant in E. The range is empty when nothing landed.
O(E) read plus O(E × open asks) pairing, the same as every base open. Then 1 guarded upsert outside any transaction, with busy_timeout = 0 and 3 pragma calls around it. Each stale period costs one full pairing and one row write.
waitingAsk during an owner comment (bot-items-owner.ts:77)
Owner comment write, inside BEGIN IMMEDIATE
1 item
The kept check (≤ 65 events), else O(E) as on base. writing = true skips the keep, so a write gains no extra write and never waits on a lock.
One per item that is fully paired on a writable file
≤ item count
4 columns, WITHOUT ROWID, upserted in place. Grows only with the number of items, not with events or opens.
494696d and the other src/shared/bots edits
None (comments only)
n/a
No work at runtime.
Regression classes touched
Re-reading unchanged input: disproved.
On base, an open of an unchanged item re-read all E events. On head it reads 1 row and an empty range.
A passing check doesn't move at. Up to 64 events that can't change the ask can therefore be re-read on each open until one falls back and keeps a new row. That cost is fixed, whatever E is and however often the item is opened.
Sync fs or SQLite on Electron main: no matching code. All of this SQL runs in the bots DB worker. The new file is listed in config/main-blocking-worker-entries.json, and so are both files that import it.
Whole-file rewrite per change: disproved. A keep is a single-row upsert, and it runs only after a full pairing. Writes add nothing.
Update published when nothing changed: disproved. A keep writes SQL directly and never goes through notifyChanged (bot-items-runtime.ts:179), so it sends no botsChanged. An open can't trigger another read of itself.
Per-entity state outlives the entity: disproved. The table holds one row per item, and items are never deleted (there is no DELETE FROM items). In memory the PR adds two fields per store and one module-level flag.
Hot-path rescans: disproved. One Set is built per call over ≤ 65 rows, with nothing nested inside.
Expensive code newly reachable past a gate: disproved. The full pairing is what base ran on every open. It now runs on fewer calls, behind the same isOpenBotItemStatus and withWaitingAsks gates. List readers still leave withWaitingAsks false.
Fixed-cadence poll, new idle wakeups, hidden owners: no matching code. The PR adds no timer, subscription or IPC. Idle wakeups per second stay 0 → 0 on main, renderer and worker.
Six questions
Is unused work paid for before the skip gate? Reviewed. The kept check comes before the O(E) read. Comment rows are classified only after they are read, but there are at most 65 of them.
Does ownership multiply or recreate work? Reviewed.
Each open view makes one call per botsChanged, coalesced by running/again. That cadence existed before this PR. The cost per call drops from O(E) to ≤ 65 rows.
At the reference fleet (100+ agents, status arriving more than once a second), a change to another item on the same bot leaves the kept row valid. The re-read then costs one row read and an empty range.
Which thread and storage layer pays? Reviewed. Everything runs in the bots DB worker on SyncDatabase statements.
A keep runs outside any transaction with busy_timeout = 0, so it never waits on a writer. A failed keep is quiet and leaves the old row in place.
busy_timeout is restored in finally.
What grows, and does the next attempt advance? Reviewed.
A kept open is O(1) in E. A stale open pays O(E) once and then keeps a row, guarded on last_event_id.
A keep that loses a race leaves the next open to retry. That open costs the same as a base open, not more.
On a read-only file or an unreadable table, every open pairs in full, as on base. No regression, and no speedup either.
If two builds with different WAITING_ASK_RULES share a file, each open can fall back and overwrite the other's row. That costs base plus one row write, and only in that unusual setup.
What does the execution host change? Reviewed. Each host runs this code in its own bots worker, and mobile uses the same RPC. The wire shape is unchanged, so there are no new SSH round trips.
Does obsolete work stop and release its budget? Reviewed. All of it runs synchronously inside the RPC or the write. Nothing async or retained is left behind.
Pre-existing, not from this PR:
A full pairing calls answeredLines over every open ask for each owner comment, which is O(E × open asks). It now runs only on stale opens.
An open item view re-reads show whenever any item or worker of its bot changes (use-bot-item-view.ts:129). That fan-out is unchanged, and each re-read is now cheaper.
Examined:
Every file in the diff
The callers and consumers listed in the marker
bot-items-schema.ts, for the indexes
The notifyChanged path, to confirm a keep sends no change notice
This was a static trace only: no app launch and no benchmarks (review only, on battery). This comment makes no timing claims.
Residual gaps:
No timing for one full pairing at large E.
No measured size of the ≤ 65 SELECT * rows when events carry large data.
No P0 or P1 findings. Since the last scan (494696d), the only runtime change is that a kept ask is now keyed by "<WAITING_ASK_RULES>:<ORCA_BUILD_COMMIT>" (column rules is now TEXT) instead of the rules number alone. This scan re-traced the whole diff origin/main...HEAD, not only that delta.
New or changed work: trigger, population, bound
All of it runs in the bots DB worker (SyncDatabase), never on Electron main or the renderer.
Work
Trigger
Population
Bound
ensureKeptWaitingAsks: CREATE TABLE IF NOT EXISTS
each store open on a writable file
1 per bots DB per process start
1 DDL statement, a no-op after the first run
hasKeptWaitingAsks: a sqlite_master lookup
first waitingAsk call per store
1 per store lifetime (cached in keeps)
1 row lookup
keptRow: PK lookup on (item_uid) filtered by rules = KEPT_BY
each open (show with withWaitingAsks) of an open-status item, and each owner comment write (bot-items-owner.ts:77)
1 per open item view per botsChanged re-read, a cadence that predates this PR
1 row
events since the kept row: item_events WHERE item_uid = ? AND id > ? ORDER BY id LIMIT 65
the same calls, when a row matches
as above
≤ 65 rows, on index idx_item_events_item(item_uid, id), plus one Set over ≤ 65 values
full pairing (pairWaitingAsk): all E events of the item, then botItemWaitingAsk
no matching row (first open, a different build, an unreadable table), > 64 events since the row, or an event since the row that can change the ask
1 per stale open
O(E) reads plus the pre-existing O(E × open asks) pairing. This is exactly what base ran on every open.
keepWaitingAsk upsert, guarded on items.last_event_id
after a full pairing, outside a write (!writing), when the file is writable
1 per stale open
1 row write, busy_timeout = 0, no transaction, failure logged once per run. Never runs inside the write transaction.
item_waiting_asks table
–
1 row per item (PK item_uid, upserted)
≤ item count. Items are never deleted, so the table stays at most as large as items. Rows from older builds are overwritten in place, so builds do not add rows.
First open of each item after a build upgrade
KEPT_BY now contains the build commit, so after an upgrade (or a downgrade, or a different desktop build opening the same file) no existing row matches. For each open-status item:
The first open of that item under the new build runs a full O(E) pairing, the same work as base, plus one guarded upsert that rewrites the row under the new key.
Every later open is back to one row lookup plus ≤ 65 rows, until an event that can change the ask, or more than 64 events, arrive.
Items never opened under the new build cost nothing. There is no migration sweep and no startup backfill, so an upgrade does no per-item work at startup across the fleet. The work is paid lazily, once per item per build, only for items someone opens.
Owner comment writes (the bot-items-owner.ts:77 read inside the write transaction) do not keep a row. Until a plain open re-keeps it, each such write pays a full pairing, which is base cost, not more.
The worst case is a heavy user who opens every one of N open items after each nightly update. That is N full pairings per build, once each, which equals one base-cost open per item. Nothing repeats per event or per poll, and nothing grows with the number of builds.
Two desktop builds alternating on one file (for example stable and RC sharing a profile) now always mismatch, so every open on either build is base cost plus one row write. Before this commit that happened only when WAITING_ASK_RULES differed. The cost is bounded at base + 1 write per open and never more than base in reads. The server bundle defines no ORCA_BUILD_COMMIT, so its key is "1:". It runs its own worker on its own file, so it does not ping-pong with desktop.
Dev builds re-key on every commit (resolveBuildSourceCommit), so each open item gets one full pairing per rebuild. This affects only developers.
A file whose table was created by an earlier iteration of this PR still has the column as rules INTEGER. CREATE TABLE IF NOT EXISTS does not alter it. A non-numeric text such as "1:<sha>" stays TEXT under INTEGER affinity, and the rules = ? comparison still matches. Only unreleased dev files can be in this state.
Regression classes touched
Re-reading unchanged input: disproved, and the PR improves it. An unchanged open re-reads 1 row plus ≤ 65 rows, where base read E rows. The commit key adds one O(E) re-read per item per build, not per call.
Sync fs or SQLite on Electron main: disproved. bot-item-waiting-ask-keep.ts is registered in config/main-blocking-worker-entries.json as bots DB worker only. There are no *Sync( fs calls.
Expensive code newly reachable past a gate: disproved. The full pairing is base behavior. It stays behind the same isOpenBotItemStatus gate (bot-items-reads.ts:169, bot-items-owner.ts:77) and the withWaitingAsks gate, and list readers still pass false.
Update published when nothing changed: disproved. A keep writes SQL directly, outside transaction()/notifyChanged, so it sends no botsChanged and an open cannot set off another read of itself.
Whole-file rewrite per change: disproved. Each keep is a 1-row upsert.
Per-entity state outlives the entity: disproved. The table has ≤ 1 row per item, upserted, with no per-build accumulation. In memory: two fields per store and one module flag.
Hot-path rescans: disproved. One Set over ≤ 65 items, nothing nested.
Polls, idle wakeups, hidden owners, fan-out, subprocesses, eager imports: no matching code. No timer, subscription, IPC, child process or SDK import is added. Idle wakeups/s stay 0 → 0 on main, renderer and the bots worker.
Six questions
Is unused work paid for before the skip gate? Reviewed. The kept-row check and the 65-row read come before the O(E) read. Rows are classified only after they are read, but there are at most 65 of them.
Does ownership multiply or recreate work? Reviewed. There is one call per open item view per botsChanged re-read, coalesced by running/again in use-bot-item-view.ts, a cadence that predates this PR. At the reference fleet (100+ agents, status more than once a second), a change to another item on the same bot leaves this item's row valid, so each re-read costs one row lookup and an empty range.
Which thread and storage layer pays? Reviewed. Everything runs on the bots DB worker. A keep runs outside any transaction with busy_timeout = 0, so it never waits on a writer, and the timeout is restored in finally. Reads use the (item_uid, id) index and the table's PK.
What grows, and does the next attempt advance? Reviewed.
A kept open is O(1) in E. A stale open pays O(E) once, then the guarded upsert keeps the row for the next open.
A keep that loses a race is retried by a later open at base cost.
On a read-only file, or with an unreadable table, every open pairs in full as on base: no regression and no speedup.
The commit key adds one O(E) pass per item per build (see above), bounded and not repeated.
What does the execution host change? Reviewed. Each host runs this code in its own bots worker, and mobile uses the same RPC. The wire shape is unchanged, so there are no new SSH round trips. The server bundle keys by rules alone.
Does obsolete work stop and release its budget? Reviewed. Everything runs synchronously inside the RPC or the write, and nothing async or retained is left behind.
Pre-existing, not from this PR:
A full pairing runs answeredLines over every open ask for each owner comment, which is O(E × open asks). It now runs only on stale opens.
An open item view re-reads show whenever any item or worker of its bot changes (use-bot-item-view.ts:129). Each of those re-reads is now cheaper.
Examined: every file in the diff, plus the callers, schema and ORCA_BUILD_COMMIT definitions named in the marker.
This was a static trace only (review only, on battery): no app launch and no benchmark. This comment makes no timing claims.
Residual gaps:
No timing for one full pairing at large E, which is the cost of the first open of each item after an upgrade.
No measured size of the ≤ 65 SELECT * rows when events carry large data.
I did not confirm that the bots worker bundle gets the ORCA_BUILD_COMMIT define (electron.vite.config.ts:231/254). If it does not, the key falls back to "1:". That would be safe for perf, but the guard against other desktop builds would not apply.
No P0 or P1 findings. Since the last scan (0dc28d7), the one runtime change is in bot-item-waiting-ask-keep.ts. A kept ask is keyed by "<WAITING_ASK_RULES>:<build>", where <build> is ORCA_BUILD_COMMIT when the bundle defines it, else process.env.ORCA_APP_VERSION (the server), else "". The key is computed once per worker (keptBy ??=). I re-traced the whole diff origin/main...HEAD, not just that change.
New or changed work: trigger, population, bound
All of it runs on the bots DB worker thread (SyncDatabase, config/main-blocking-worker-entries.json). None of it runs on Electron main or in the renderer.
Work
Trigger
Population
Bound
ensureKeptWaitingAsks: CREATE TABLE IF NOT EXISTS ... WITHOUT ROWID
store open on a writable file
1 per bots DB per process start
1 DDL statement, a no-op after the first run
hasKeptWaitingAsks: sqlite_master lookup
first waitingAsk call per store
1 per store lifetime (cached in keeps)
1 row
keptByThisBuild
first keep or lookup
1 per worker (memoized)
string concatenation
keptRow: PK lookup item_uid = ? AND rules = ?
show of an open item (bots-items-owner-methods.ts:149, the only caller passing withWaitingAsks = true, always one record), and each owner comment write (bot-items-owner.ts:77)
1 per open item view per re-read, on the re-read cadence that already exists (use-bot-item-view.ts:129)
1 row
events since the kept row: item_events WHERE item_uid = ? AND id > ? ORDER BY id LIMIT 65, then waitingAskChange on each
same calls, when a row matches
as above
≤ 65 rows on index (item_uid, id); ≤ 65 botItemQuestionShape calls (bot comments only); one Set of ≤ 3 values
full pairing pairWaitingAsk: all E events, then botItemWaitingAsk
no matching row, more than 64 events since the row, or an event since the row that can change the ask
1 per stale open
O(E) reads plus the O(E × open asks) pairing that predates this PR. This is what base ran on every open.
keepWaitingAsk upsert, guarded on items.last_event_id = at
after a full pairing, outside a write (!writing), on a writable file with the table
1 per stale open
1 autocommit row write with busy_timeout = 0, restored in finally; failures logged once per run. It never runs inside a write transaction, so it adds nothing to writes.
item_waiting_asks storage
none
1 row per item ever opened while open (PK item_uid, upserted)
≤ the row count of items, which are never deleted. Rows from other builds are overwritten in place, so builds do not add rows.
How the stale path stays bounded:
An event that can change the ask (a bot question, or an owner answer while an ask is kept) causes one full pairing on the next open. The keep then moves at to the newest event, so the open after that is short again.
More than 64 neutral events cause one full pairing and a re-key.
So the O(E) passes are bounded by question/answer events plus E/64, not by how often the item is opened. Base paid O(E) on every open and every botsChanged re-read.
First open of each item after a build upgrade
Desktop. The key holds the build commit, so after any upgrade, downgrade or other desktop build no existing row matches. For each item:
Its first open runs one full O(E) pairing, the same work as base, plus one guarded upsert under the new key.
Later opens go back to 1 PK lookup plus ≤ 65 rows.
Items nobody opens cost nothing. There is no startup sweep or backfill, so an upgrade does no per-item work at startup across 750+ worktrees or any item count.
Worst case: every open item is opened after each nightly build. That is N full pairings per build, one base-cost open per item, and nothing grows with the number of builds.
Server (new in this head). The key changes when the bundle version stamped by stampOrcadAppVersion (orcad-host-adapters.ts:58) changes, so the first open per item after a server update pays the same one base-cost pairing. If ORCA_APP_VERSION is unset, the key falls back to "1:". That is safe for perf (rows keep matching) but gives no per-version invalidation, which is a correctness question, not perf.
Two builds sharing one file (desktop stable and RC on one profile) always mismatch. Each open is then base-cost reads plus 1 row write, never more than base in reads, and bounded.
Owner comment writes read the kept row inside the transaction but never keep. On a stale row they pay a full pairing, which is base cost.
Regression classes
Class
Disposition
Re-reading unchanged input
Fixed, not introduced. A kept row with no events since it costs 1 PK lookup plus an empty range, where base re-read and re-paired all E events per re-read.
Sync fs or SQLite on Electron main
Disproved. The new module is registered as a bots DB worker entry, and every statement runs in that worker.
Per-entity state outlives the entity
Disproved. 1 row per item, items are never deleted, and the upsert on PK prevents rows piling up per build.
Expensive code newly reachable past a gate
Disproved. No gate was removed. The fallback (no table, read-only file, unreadable table, a new build) is exactly the base full pairing.
Whole-file rewrite per change
Disproved. At most 1 single-row upsert per stale open, none per write, none when the row is valid.
Fixed-cadence poll / new idle wakeups
No matching code: no timer, interval, subscription or IPC is added. Idle wakeups/s on main, renderer and daemon: 0 before and 0 after.
Subprocess per item, unbounded fan-out, eager startup imports
No matching code: no spawn, no Promise.all, and the new module only joins the worker graph.
Six questions
Is unused work paid before the skip gate? Reviewed. Waiting asks are computed only for show of an open-status item (isOpenBotItemStatus) and for owner comment writes. List and summary views pass withWaitingAsks = false and do no pairing.
Does ownership multiply work? Reviewed. One store, and one memoized key and keeps flag, per worker. The work is per open item view, on the re-read cadence that predates this PR. A change to another item of the same bot leaves this item's row valid.
Which thread and storage layer pays? Reviewed. Everything runs on the bots DB worker. Reads use the PK and the (item_uid, id) index. A keep never waits on another writer (busy_timeout = 0) and never runs inside a transaction.
What grows, and does the next attempt advance? Reviewed.
A valid open is O(1) in E, with ≤ 65 rows checked.
A stale open pays O(E) once, then the guarded upsert moves at forward.
A keep that loses a race is retried on a later open at base cost.
A read-only or unreadable file pairs in full on every open, as base does.
What does the execution host change? Reviewed. Each host runs this in its own bots worker, and mobile uses the same RPC with an unchanged wire shape, so there are no new SSH round trips. The desktop worker gets the ORCA_BUILD_COMMIT define (bots-db-worker-entry is in MAIN_BUILD_ENTRY_POINTS, built with the main define). The server bundle has no define and keys by version.
Does obsolete work stop and release its budget? Reviewed. Everything is synchronous inside the RPC or the write, and nothing async or retained is left behind.
Pre-existing, not from this PR:
A full pairing runs answeredLines over every open ask for each owner comment, which is O(E × open asks). It now runs only on stale opens.
An open item view re-reads show on any item or worker change of its bot (use-bot-item-view.ts:129). Each of those re-reads is now cheaper.
Examined: every file in the diff, plus the callers, worker build entries and version-stamp paths named in the marker.
This was a static trace only (review only, on battery): no app launch and no benchmark. This comment makes no timing claims.
Residual gaps:
No timing for one full pairing at large E, which is the cost of the first open of each item after an upgrade.
No measured size of the ≤ 65 SELECT * rows when events carry large data.
I did not verify that stampOrcadAppVersion runs before the server spawns its bots worker, which copies the env when it starts. If it runs later, the key is "1:", which is perf-safe.
Problem: opening a bot item read and parsed every event the item ever had, to find the question still waiting on the owner. #47385 added this read, so long threads got slower to open with every comment. The page also re-reads on every change while it is open.
What the user sees now: the same item page and the same waiting question, opened in constant time on long threads. Writes such as comments, moves and bulk changes do exactly what main does.
How:
A side table keeps each item's waiting question together with the event it covers, keyed by the pairing rules and the build (commit on desktop, version on a remote server).
An open reads that row plus at most 64 events since it. When none of them can change the answer it is used as is; otherwise the open pairs every event once and keeps the result.
No migration step and no schema version bump, so older builds keep writing the file.
Fixed during review:
Write cost. Earlier heads refreshed the kept answer on every write, inside the write, then after it, then as one batched commit. Reviewers showed each version either replayed history on writes or added a commit per comment. The final design never writes during a write.
Failed and busy writes. Keeping an answer can never fail or slow a user's write. It runs outside any write and never waits on another writer.
Stale answers. An answer is trusted only for the build and rules that kept it. Events after it are checked with rules that a test pins against full pairing for every event kind.
Unreadable table. An open falls back to the full read, as on main, and warnings are limited (busy errors are silent).
Accuracy. The PR body now matches the code.
Deferred: nothing.
Verified:
Tests: bot-items-open-questions.test.ts (three new tests) plus the item and RPC suites, 39 tests in all, and pnpm check:changed. CI is green.
Reviews: the regression audit on the final head (blinded, merged onto main) says SAFE with no findings. The last Claude check is CLEAN, and the perf scan of this head is clear.
QA: tests and the benchmark below, because the change is store-level with no screen or process changes.
Since e1ff12b: 1ca82f3 only closes a test's second database connection when an assertion fails (a CodeRabbit thread, resolved). No shipped file changed, so the audit on e1ff12b still covers it; the perf scan and the benchmark were rerun on 1ca82f3. One perf-scan marker said verdict=clear for "clean"; I changed that word so the checker reads it.
Benchmark: head=1ca82f364bfbb4a613454f781927a1eb895dd8ac gate=PASS name=item-open-waiting-ask corpus=one item, 600 and 3000 bot comments of 1 KB, on-disk WAL item store, median of 21 runs on an M-series Mac. Open 0.12 ms at 600 events and 0.27 ms at 3000; the full history read main does per open is 1.15 ms and 6.97 ms.
Benchmark: head=1ca82f364bfbb4a613454f781927a1eb895dd8ac gate=PASS name=item-write-cost corpus=same item. A bot comment takes 0.08 ms at 600 events and 0.14 ms at 3000; this PR adds no work to writes.
Perf scan: PR #47478 (kept waiting ask per bot item)
Head 1ca82f364bfbb4a613454f781927a1eb895dd8ac, range origin/main...HEAD (17 commits, 9 files). Reviewed from source only: no app launch and no benchmarks (machine on battery).
Verdict: clean. I found no P0 or P1. Every open now reads a bounded number of events where it used to read all of them. The worst case costs the same as main plus a constant, and nothing new runs while the app is idle.
Findings
None.
New or changed work: trigger, population, bound
All the SQL runs on the bots DB worker thread (config/main-blocking-worker-entries.json gains the new file). None of it runs on Electron main or in the renderer.
Work
Trigger
Population
Bound per trigger
ensureKeptWaitingAsks: CREATE TABLE IF NOT EXISTS item_waiting_asks
Store open, writable files only
1 per store lifetime
One DDL. Free once the table exists
hasKeptWaitingAsks: sqlite_master probe
First waitingAsk call on a writable store
1 per store lifetime (this.keeps caches it)
One indexed lookup
keptRow: PK lookup item_uid = ? AND rules = ?
Each waitingAsk call
Single-item open (bots.items get with withWaitingAsks=true), and an owner comment on an open item (inside its write)
One PK lookup on a WITHOUT ROWID table
Check of events since the kept ask
When a kept row matches this build
Same
At most 65 rows, using idx_item_events_item(item_uid, id) and LIMIT 65. Does not grow with thread length
pairWaitingAsk: read and pair every event
No kept row, more than 64 events since it, or a new ask (or an answer to a kept ask) since it
Same
O(item events). This is exactly main's cost on every open, so the worst case is main plus the 65-row check
keepWaitingAsk: conditional upsert, plus 2 busy_timeout pragmas
After a full pairing, only outside a write (store = !writing) and only on writable files
1 per full pairing
One single-row upsert. busy_timeout = 0 means it never waits on another writer, and it is skipped when a write landed after the pairing
First open of each item after a build upgrade
rules is keyed by WAITING_ASK_RULES plus the build commit (or the version on the server), so a new build matches no kept rows
Only items actually opened. There is no backfill or migration pass over all items
One full pairing (equal to main's cost for that open) plus one upsert. After that, every open is bounded again
Item writes (transaction)
Every item write
Every write
No change: writes never touch the table. The only change is a writing boolean
The cost no longer grows with the thread. Main read every event of the item on every open. Now the full read happens at most once per 64 neutral events, once per new ask, or once per build, and each full read resets the window. The 64-event window does not move forward while the check keeps passing, so an open reads at most 65 rows there, and the next full pairing resets it.
Regression classes touched
Class
Disposition
Sync fs or SQLite on Electron main
Matched and disproved. The new SQL runs only on the bots DB worker. The worker entry is registered, and the store already runs there
Re-reading unchanged input
This PR fixes this class. An unchanged item now costs 1 PK lookup plus 0 rows past the kept event. Each open used to read all N events
Whole-file rewrite per change
Matched and disproved. A keep is a single-row upsert that runs only after a full pairing, never per write, and is skipped when the result would be stale
Per-entity state outlives the entity
Matched and disproved. There is one row per item that has been opened, keyed by item_uid. Items are never deleted, so the table is bounded by the item count (4 small columns per row). Rows left by a previous build are overwritten, never added alongside (one PK per item)
Expensive code newly reachable past a gate
Matched and disproved. No gate was removed. waitingAsk keeps its callers (isOpenBotItemStatus plus withWaitingAsks, which only the single-item get sets)
New wakeups in steady idle / fixed-cadence poll
No matching code. There are no timers, polls, listeners or IPC
Eager startup imports
Matched and disproved. The new imports are shared bot modules that the worker already loads
Six questions
Unused work before the skip gate: reviewed. List and summary views never call waitingAsk, because withWaitingAsks defaults to false. The write path skips the keep.
Ownership multiplying work: reviewed. There is one store per DB worker, and keeps and keptBy are cached per store and per process. There is no work per mounted consumer.
Which thread and storage layer pays: reviewed. The bots DB worker runs node:sqlite through SyncDatabase. The keep never waits on a writer (busy_timeout = 0, then restored). WAL write amplification is one row per full pairing.
Growth and whether the next attempt advances: reviewed. Each full pairing advances at to the newest event. If a keep fails (busy, a full disk, or a read-only file), the next open costs the same as main, not more. If a writable file can never be kept, the failure is logged once per run. Two different builds that open the same file alternately overwrite each other's row. Each open then costs main's full read plus one upsert, which is bounded and only happens when a user opens an item.
Execution host: reviewed. The code is the same SQL locally, on the server (keyed by version) and on remote hosts. There are no host probes or round trips per item. A read-only file takes main's path.
Does obsolete work stop: not applicable. The work is synchronous and request-scoped, with no retained handles, waiters or queues.
Coverage and gaps
Files examined: the changed sources, the test file, and their callers bot-items-reads.tsviewRows, bot-items-owner.ts comment write, bot-items-runtime.tsviews, bots-items-owner-methods.ts get, and bot-items-schema.ts indexes.
I did not run anything, so I make no timing claims. The bounds above come from reading the source (LIMIT 65, PK lookup, one full pairing per invalidation). I read the test's assertions but did not run them.
perf-surface-detect --pr 47478 reports no surfaces.
Follow-up timing on a Linux QA machine, current main (b6beb47, which still has the read this PR removes). The test data was a 600-event item with 3 linked workers and a PR link, a 50-event item, 100 worktrees, and a bot whose Home chat has history.
What
Time
Item read (bots.items.owner.show), 600-event item
17 ms cold, 3–4 ms warm
Item read, 50-event item
1–5 ms
Opening the 600-event item, row click until the newest event is in the page
86–253 ms
Each "Show earlier" page, up to all 600 events
82–142 ms, no long tasks
Home chat reply on screen after a window reload
about 510 ms from navigation (about 200 ms after the bot row)
Drawing was timed in a hidden window, so layout and paint aren't included. Reloading while the bot's first message was starting recovered to the reply rather than leaving a spinner. None of this reproduced as seconds at this scale.
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
Opening a bot's item used to read through every comment the item ever had, just to work out which question is still waiting for you. On a long thread that grew with every comment. Now the app remembers that answer next to the item. Usually opening it reads that answer plus only the comments added since; after a new question or an answer it reads the whole thread once, then remembers again. Adding a comment costs nothing extra.
What Changed
Before: each time an item's page opened (and on every refresh while open), the app loaded and parsed the item's whole activity history to work out which question still waits on the owner. That read was added in #47385, so an item with hundreds of comments paid for all of them on every open.
After: opening an item, or an owner's reply checking which question it answers, reads the stored answer and only the events added since it was stored. Writes never store or update it.
Mechanism:
item_waiting_asks (item_uid, ask, at, rules), holds each item's waiting question (0 means none), as worked out from its events up to eventatunderrules: the pairing rules version plus the build (its commit on desktop; on a remote server, whose bundle names no commit, its version). A row any other build wrote is never trusted, so after an upgrade or downgrade each item's answer is worked out again on its first open.CREATE TABLE IF NOT EXISTSwhen the store opens. It is not a numbered migration step, so the schema version stays the same and an older Orca can still write the file.at, at most 64. The stored answer still holds when none of them can change it:Why
Opening an item should usually cost the same however long its thread is, and writes shouldn't pay for that instead. The answer depends only on events, and events are append-only with increasing ids. So "the answer as of event
at" plus a check of the events afteratis exact. That check reuses the pairing rules inbot-item-question-answers.ts: which events can start, answer or end a question.Linked Issue
N/A (internal report of slow item pages on long threads).
Visual Proof
N/A: no visual change. The same question shows as waiting; only how it is looked up changed.
Testing
bot-items-open-questions.test.ts. One checks the new-event rule against full pairing for every event kind, so the two can't drift apart unnoticed. Through bot comments, a new question and its answer, an open always answers what pairing every event answers. Comments that ask nothing are answered from the stored answer without working it out again. A new question is worked out again and stored. A missing entry, or an event written by an older Orca, is worked out from the events.Platforms: macOS (unit tests and the store benchmark).
Performance
Measured with the item store on an on-disk WAL file on this head (M-series Mac, 1 KB comments, median of 21):
Writes do exactly what main does; an owner reply reads the stored answer the same way an open does. An open reads one row plus at most 64 events since the stored answer. It reads the whole history only after a new question, an answer while a question waits, or 64 new events, and then stores the result.
Risk
The riskiest part is the check of new events wrongly keeping an answer. If it did, the comment box could reply to the wrong question. The check only keeps an answer for events the pairing code ignores, or for answer and end events when no question is waiting. Anything else works the answer out from all events.
There is no schema version bump, so moving between this build and an older one keeps items writable. If the table can't be created, read or written, opens fall back to the full read, as on main, with at most one warning per run for each of creating and storing. A plain revert brings back the full read and leaves an unused table behind.
Level: Low
AI Disclosure
Review
Agent skill upstream boundary
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)