Skip to content

perf(storage): extract pure prepare_session_rows for off-writer prep - #3219

Merged
Sinity merged 1 commit into
masterfrom
perf/storage/prepared-session-rows
Jul 20, 2026
Merged

Sinity merged 1 commit into
masterfrom
perf/storage/prepared-session-rows

Conversation

@Sinity

@Sinity Sinity commented Jul 20, 2026

Copy link
Copy Markdown
Owner

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 a ParsedSession tree into messages/blocks SQL row tuples (enum lookups, JSON encoding of tool_input, per-message/per-block content hashing) entirely inside the single-writer transaction hold. Measured on the live archive: index.full_replace.messages/.blocks stage 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. See bd show polylogue-623q for 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 — only messages/session_id/duplicate_native_ids in, row tuples out). _write_messages/_write_blocks gained an optional rows= passthrough so a caller with already-built rows skips rebuilding.
  • New PreparedSessionRows (frozen dataclass: session_id, session_content_hash, message_rows, block_rows) and prepare_session_rows(session: ParsedSession) -> PreparedSessionRows — a pure function computable from nothing but a ParsedSession, safe to call from any thread (e.g. a parse-prefetch worker) well before any writer hold exists. session_content_hash is pipeline.ids.session_content_hash(session) — the same hash ordinary ingest callers already compute and pass as content_hash=.
  • write_parsed_session_to_archive gains an optional prepared= parameter. Right before the full-replace write, it decides whether to reuse the supplied PreparedSessionRows under two independent, cheap conditions checked on the writer thread:
    1. 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 passed content_hash) always falls back to inline preparation.
    2. Lineage resolution did not slice messages — _extract_prefix_tail returns messages unchanged in every case except real prefix-sharing composition against an already-archived parent (detected via lineage_inheritance == "prefix-sharing"), which the prefetch worker has no DB access to know about ahead of time.
  • Any other combination transparently rebuilds rows inline; 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 in sources/revision_backfill.py. That pipeline's actual index writes go through ArchiveStore.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. Wiring PreparedSessionRows all 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 under polylogue-623q.

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 in 7.71s

devtools verify --quick
# exit_code: 0 (ruff format/check, mypy --strict, render all --check,
# topology/layering/manifests/doc-commands gates)

New tests (tests/unit/storage/test_prepared_session_rows.py):

  • equivalence: writing a synthetic corpus (plain text, tool_use/tool_result/thinking blocks, duplicate-native-id messages) via inline building vs. via prepare_session_rows produces byte-identical sessions/messages/blocks dumps.
  • anti-vacuity reuse proof: monkeypatches _build_message_rows/_build_block_rows to raise, then proves a matching-content-hash write with prepared= still succeeds with correct rows — only possible if the inline builders were genuinely skipped.
  • stale-prepared fallback: mutates a session's text after prepare_session_rows() ran, asserts the writer detects the content-hash mismatch and stores the NEW content (never the stale prepared text).
  • content_hash=None degrades safely (prepared rows never used, since the identity-only fallback hash can't coincide with a real content hash).
  • prepare_session_rows purity: 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 the write_parsed_session_to_archive call):

targeted stage (messages+blocks) inline:   3.048s / 2.922s / 3.738s  (3 runs)
targeted stage (messages+blocks) prepared: 2.945s / 2.529s / 3.303s
targeted stage reduction:                  3.4%   / 13.4%  / 11.6%

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 (larger tool_input JSON 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

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]>
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 12cd09c7-4ded-4359-8543-dd3699d00dc7

📥 Commits

Reviewing files that changed from the base of the PR and between 491a239 and d4d76d3.

📒 Files selected for processing (2)
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/storage/test_prepared_session_rows.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/storage/prepared-session-rows

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

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity

Sinity commented Jul 20, 2026

Copy link
Copy Markdown
Owner Author

Coordinator review stand-in (CodeRabbit rate-limited on this PR — no findings were produced).

Read the full diff. Assessment:

  • Extraction is behavior-preserving: _build_message_rows/_build_block_rows are verbatim lifts of the old inline rows() generators; _write_messages/_write_blocks keep identical signatures for all existing call sites and only add an optional rows= passthrough.
  • Reuse gate is conservative and correct: prepared rows are used only when (a) not merge_append (prepared assumes position_offset=0), (b) lineage_inheritance != "prefix-sharing" (the single case where _extract_prefix_tail slices messages after preparation), and (c) the prepared content hash equals this call's content_hash. Identity-only hashes (content_hash=None callers) can never match a real content hash, so those callers are structurally safe. Any mismatch silently falls back to inline building — passing a stale prepared is never incorrect, only wasted work.
  • Tests are non-vacuous: equivalence proven by full-table dump comparison across text/tool/thinking/duplicate-native-id corpora; genuine reuse proven by monkeypatching the inline builders to raise; stale-prepared fallback proven to reflect NEW content.
  • Honest scoping: daemon prefetch-cache wiring is explicitly deferred (separate, larger change through the census/spill/replay pipeline) — documented, not silently dropped.

Verification per PR body: 126 tests green across the new file + revision-replay/write/lineage/bulk-build suites; devtools verify --quick exit 0. Merging on green quick-gate.

@Sinity
Sinity merged commit 93a5388 into master Jul 20, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the perf/storage/prepared-session-rows branch July 20, 2026 19:32

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Sinity added a commit that referenced this pull request Jul 31, 2026
## 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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 76.F001 / P1: fixed-already at the checked revision: Session hashing now includes source_name and provider_session_id, so otherwise identical transcripts belonging to different sessions have different prepared content hashes. The hash-equality admission gate rejects the wrong-session prepared result instead of reusing its embedded row identifiers. See polylogue/pipeline/ids.py:91 and polylogue/storage/sqlite/archive_tiers/write.py:2387.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant