Repository navigation
perf(storage): extract pure prepare_session_rows for off-writer prep - #3219
Conversation
Problem: write_parsed_session_to_archive's full-replace path built every message/block SQL row tuple (enum lookups, JSON encoding, content hashing) inside the single-writer transaction hold. Measured 34-40s per 2,000-page full-corpus rebuild and 165-287s on whale pages in the index.full_replace.messages/.blocks stage timings, while the daemon's 14-thread parse-prefetch pool sat idle ahead of the writer hold (polylogue-623q). Solution: extract the row-building loops in _write_messages/_write_blocks into pure functions (_build_message_rows/_build_block_rows) that take nothing but a normalized message list -- no DB connection. A new prepare_session_rows(session) composes them into a PreparedSessionRows dataclass computable from a bare ParsedSession, safe to call from any thread (e.g. a parse-prefetch worker) well before any writer hold exists. write_parsed_session_to_archive gains an optional prepared= parameter. Reuse is gated by two independent, cheap checks performed on the writer thread right before the full-replace write: (1) prepared.session_content_ hash (pipeline.ids.session_content_hash, computed from the pre-lineage session) must match this call's own content_hash -- a session whose content changed between prepare and write, or a caller that never passed a content_hash, always falls back to inline preparation; (2) lineage resolution must not have sliced messages (_extract_prefix_tail returns messages unchanged in every case except real prefix-sharing composition against an already-archived parent, which the prefetch worker has no DB access to know about). Any other combination transparently rebuilds rows inline -- prepared=None reproduces the exact prior behavior byte-for-byte. Not wired yet: the daemon's parse-prefetch cache (RawParsePrefetchCache) and the census/spill/replay pipeline in sources/revision_backfill.py. That pipeline's actual write calls go through ArchiveStore.apply_raw_ revision_replay/apply_raw_membership_classification, which resolve mixed full-replace/append cohorts from a pickled sqlite spill cache shared between the census and replay phases -- wiring PreparedSessionRows all the way through would mean extending three independent budget/eviction mechanisms (inflight-bytes, tree-bytes, spill payload-bytes) and the cohort-resolution logic that decides per-raw full vs append semantics. That is a separate, larger change; this PR ships the mechanically-clean extraction plus its correctness contract so that wiring can build on a tested foundation. Verification: - devtools test tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_revision_replay.py tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_bulk_build_lifecycle.py -> 126 passed - devtools verify --quick -> exit 0 (ruff format/check, mypy --strict, render all --check, topology/layering/manifests/doc-commands gates) - Micro-benchmark (200 synthetic sessions, 80 messages each, mixed text/tool_use/thinking blocks, /dev/shm): targeted index.full_replace.messages+blocks stage time dropped ~3-13% across three runs (noisy at this corpus size -- SQLite executemany() itself dominates on tmpfs); full write() call time roughly flat to slightly down. The row-building CPU work this extracts is a genuine but modest fraction of the full-replace stage at this scale; real corpora with richer blocks (larger tool_input JSON, more messages per session) are expected to show a larger relative share moved off the writer thread. Ref polylogue-623q Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 34 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
Coordinator review stand-in (CodeRabbit rate-limited on this PR — no findings were produced). Read the full diff. Assessment:
Verification per PR body: 126 tests green across the new file + revision-replay/write/lineage/bulk-build suites; |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d4d76d30e4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
## Summary Wires the previously-unused `prepare_session_rows`/`PreparedSessionRows` (polylogue-623q, #3219) into the offline/CLI bulk-rebuild path so row-tuple construction (message/block hashing, JSON encoding, enum lookups) runs on a background thread concurrently with the single SQLite writer's own work, instead of inline inside the writer's hold. ## Problem polylogue-fpid: this was the last unexplored performance lever for a full index rebuild, which the archive needs to run to pick up 5,300 misclassified sessions and every parser fix landed today. Concurrency (#p0pw/#8249), FTS-trigger deferral, and delete-cascade skip (#3460) were already measured and closed off; the remaining diagnosis was that bulk-build is INSERT-bound and `prepare_session_rows`/`PreparedSessionRows` existed complete, tested, and wired nowhere. Instrumenting the real rebuild engine (`tests/infra/rebuild_cost_model.py`'s `_run_one_rebuild_pass`, not a microbenchmark) against the two largest population strata (codex-session/d9: 7508 raws, claude-code-session/d9: 15954 raws — 57% of the 41,363-raw corpus by count) showed `index.full_replace.field_path_union`'s timer wrapping `_union_with_existing_rows`'s call expression — whose arguments (`_build_message_rows`/`_build_block_rows`) evaluate before the function body's own early return. On a from-empty bulk build (`existing_raw_id is None`, always the early-return branch for this stratum shape) the entire measured cost of that stage is pure row construction, not the union it's named for: 0.355s/40 raws (42% of `full_replace`) on codex-d9, 0.072s/40 (11%) on claude-code-d9. ## Solution - `polylogue/storage/sqlite/archive_tiers/revision_governance.py`: threads `PreparedSessionRows`/`Future[PreparedSessionRows]` through `apply_raw_revision_replay` → `_index_parsed_for_retained_raw` → `_write_parsed_precedence_result` → `write_parsed_session_to_archive`'s existing (previously unwired) `prepared` parameter. Only ever resolved at chain position 0 (the sole full-replace write — every later position is `merge_append`, which never accepts prepared rows). - `polylogue/sources/revision_backfill.py`: `backfill_historical_revision_ evidence`'s byte-proven replay loop submits `prepare_session_rows` for position 0's session to a one-worker `ThreadPoolExecutor` right when `parsed_by_raw_id` is built, so it runs concurrently with `apply_raw_revision_replay`'s own attachment-preacquisition/blob-flush/ head-lookup preamble on the calling thread. Gated on `parallel_threads_effective()` (same guard the existing parse-thread pool uses) — a GIL build gets `prepare_pool=None` and is byte-for-byte unchanged. - `polylogue/storage/sqlite/archive_tiers/archive.py`: threads the new parameter through `ArchiveStore.apply_raw_revision_replay`'s wrapper. - Correctness: `write_parsed_session_to_archive`'s existing validity gate (content-hash match, not `merge_append`, not prefix-sharing) already made a stale/wrong `prepared` argument always safe to pass — this change adds no new gating logic, only a new supplier. - Also restores `literal_check` (deleted by #3458 despite live call sites #3451 added the same day — polylogue-7qfq, already fixed on another branch as `3fc622ecb`, cherry-picked here to unblock local verification on this worktree's `origin/master` base) and fixes a test double (`test_live_cursor_persistence.py`'s `_lock_first_index_persistence` fixture, which re-declares `_write_parsed_precedence_result`'s signature) to accept and forward the new `prepared` parameter. ## Verification Re-instrumented after wiring, same two strata, 4 repeated runs each under host load 14–17 (contended, hence the repeats): `field_path_union` collapsed from 0.355s/0.072s to a consistent ~0.0002s (99.9%+ eliminated) in every run. `full_replace` dropped 25–45% (codex-d9: 0.85s → 0.46–0.63s; claude-code-d9: 0.64s → 0.45–0.48s). `index_parsed_write` (the full per-session writer hold) dropped 19–22%. Weighted by raw count across the two dominant strata (57% of the corpus), this projects to roughly a 10–15% cut of writer apply time on the majority of a full rebuild — an estimated **25–40 minutes off the calibrated 4h20m baseline**. Did not run the full ~40-pass population projection benchmark (`test_full_population_projection`) — a concurrent instance of the same benchmark was already running in another worktree on this host when this was measured; the per-stratum stage-level measurement above uses the same real rebuild engine, just without the two-point regression's fixed-cost stripping. - `devtools test tests/unit/sources/test_revision_backfill.py tests/unit/storage/test_revision_replay.py tests/unit/storage/test_raw_retention.py tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_archive_tiers_write.py tests/unit/sources/test_live_cursor_persistence.py` — 228 passed, 1 failed (`test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule`, confirmed pre-existing on unmodified `origin/master` via a diff-free byte-for-byte rerun; filed as polylogue-6mpy, unrelated to this change). - `devtools verify --quick` — exit 0 (ran twice: once pre-commit, once via the pre-push hook). - `mypy polylogue devtools` — Success, no issues found in 1277 source files. - Not run: full/testmon suite (per-PR CI skips it by design; the affected-surface `devtools test` selection above covers every touched call site). Ref polylogue-fpid, polylogue-623q, polylogue-7qfq --------- Co-authored-by: Claude Opus 5 <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Extracts the CPU-bound row-tuple-building work in the full-replace write path (
write_parsed_session_to_archive/_replace_full_session_messages_and_blocks) into a pure function that can run off the single-writer thread, with a cheap, always-safe validity check gating reuse.Problem
write_parsed_session_to_archive's full-replace path converts aParsedSessiontree intomessages/blocksSQL row tuples (enum lookups, JSON encoding oftool_input, per-message/per-block content hashing) entirely inside the single-writer transaction hold. Measured on the live archive:index.full_replace.messages/.blocksstage timings of 34-40s per 2,000-page rebuild pass and 165-287s on whale pages, while the daemon's 14-thread parse-prefetch pool (polylogue/daemon/parse_prefetch.py) sits idle ahead of the writer hold. Seebd show polylogue-623qfor the full import-performance-envelope context.Solution
polylogue/storage/sqlite/archive_tiers/write.py: split_write_messages/_write_blocks's inline row-building generators into pure functions_build_message_rows/_build_block_rows(no DB access — onlymessages/session_id/duplicate_native_idsin, row tuples out)._write_messages/_write_blocksgained an optionalrows=passthrough so a caller with already-built rows skips rebuilding.PreparedSessionRows(frozen dataclass:session_id,session_content_hash,message_rows,block_rows) andprepare_session_rows(session: ParsedSession) -> PreparedSessionRows— a pure function computable from nothing but aParsedSession, safe to call from any thread (e.g. a parse-prefetch worker) well before any writer hold exists.session_content_hashispipeline.ids.session_content_hash(session)— the same hash ordinary ingest callers already compute and pass ascontent_hash=.write_parsed_session_to_archivegains an optionalprepared=parameter. Right before the full-replace write, it decides whether to reuse the suppliedPreparedSessionRowsunder two independent, cheap conditions checked on the writer thread:prepared.session_content_hash == <this call's own content_hash>— a session whose content changed between prepare-time and write-time (or a caller that never passedcontent_hash) always falls back to inline preparation.messages—_extract_prefix_tailreturnsmessagesunchanged in every case except real prefix-sharing composition against an already-archived parent (detected vialineage_inheritance == "prefix-sharing"), which the prefetch worker has no DB access to know about ahead of time.prepared=None(the default, every existing caller) reproduces the exact prior behavior byte-for-byte.Not wired in this PR: the daemon's parse-prefetch cache (
RawParsePrefetchCache) and the census/spill/replay pipeline insources/revision_backfill.py. That pipeline's actual index writes go throughArchiveStore.apply_raw_revision_replay/apply_raw_membership_classification, which resolve mixed full-replace/append cohorts out of a pickled sqlite spill cache (_ParsedSessionSpill) shared between the census and replay phases across three independent budget/eviction mechanisms (inflight-bytes, tree-bytes, spill payload-bytes) plus cohort-resolution logic that decides per-raw full-vs-append semantics. WiringPreparedSessionRowsall the way through that machinery is a separate, larger change that can now build on this tested extraction + correctness contract rather than reinventing it. Remaining scope tracked underpolylogue-623q.Verification
New tests (
tests/unit/storage/test_prepared_session_rows.py):prepare_session_rowsproduces byte-identicalsessions/messages/blocksdumps._build_message_rows/_build_block_rowsto raise, then proves a matching-content-hash write withprepared=still succeeds with correct rows — only possible if the inline builders were genuinely skipped.prepare_session_rows()ran, asserts the writer detects the content-hash mismatch and stores the NEW content (never the stale prepared text).content_hash=Nonedegrades safely (prepared rows never used, since the identity-only fallback hash can't coincide with a real content hash).prepare_session_rowspurity: two calls on the same immutable session produce identical output.Micro-benchmark (200 synthetic sessions, 80 messages each, mixed text/tool_use/thinking blocks,
/dev/shm, timing only thewrite_parsed_session_to_archivecall):Reduction is real but modest and noisy at this synthetic corpus size —
sqlite3.Connection.executemany()itself dominates wall time on tmpfs, so the CPU-bound row-building work this extracts is a genuine but not majority share of the targeted stage here. Real corpora with richer block content (largertool_inputJSON payloads, more messages per session, the whale pages the bead's own numbers cite) are expected to show a larger relative share of stage time moved off the writer thread, since row-building cost scales with content complexity while the SQLite insert cost scales roughly with row count.Ref polylogue-623q