Skip to content

perf(storage): skip the no-op full-replace delete cascade for new sessions - #3460

Merged
Sinity merged 2 commits into
masterfrom
perf/rebuild-index-writes
Jul 31, 2026
Merged

Sinity merged 2 commits into
masterfrom
perf/rebuild-index-writes

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

Skips write_parsed_session_to_archive's full-replace delete cascade
(_clear_session_projection_rows's ~14 point-DELETEs plus a bare DELETE FROM messages) when the session_id provably has no prior rows -- a strict,
proven no-op removal, not a heuristic.

Problem

polylogue-623q (import performance envelope: full-corpus rebuild must land
in well under an hour) established the single SQLite writer dominates
rebuild wall-clock (54-84% across every measurement so far). polylogue-cs86
(filed by a prior lane on this epic) measured the full-replace delete cascade
at ~20% of apply_s on a small (n=50 raw) synthetic probe, even with every
index present -- because a from-empty bulk-build generation still pays the
full statement-execution + index-descent cost per table on a DELETE that
matches zero rows.

Solution

write_parsed_session_to_archive already ran a PK lookup on sessions
before its own upsert (SELECT raw_id FROM sessions WHERE session_id = ?),
to capture existing_session_raw_id for the union-precedence decision
(_union_with_existing_rows). That existing query is reused, with a new
sibling session_row_existed: bool -- distinct from existing_session_raw_id
because a session row can exist with a NULL raw_id (ambiguous with "no row
at all" if reused for this purpose).

session_row_existed threads into _replace_full_session_messages_and_blocks,
which now skips (when False):

  • _clear_session_projection_rows (action_pairs, blocks, attachment_refs,
    paste_spans, session_provider_usage_events, session_agent_policies,
    session_working_dirs, session_repos, session_commits, session_model_usage,
    session_refs, session_events, session_links, plus a parent_message_id-
    nulling UPDATE)
  • the bare DELETE FROM messages WHERE session_id = ?
  • the three FTS/trigram scoped deletes (gated separately behind
    use_scoped_fts_rebuild, the non-bulk-build daemon path)

Why this is exactly correctness-preserving: every row these statements
would delete is written ONLY together with (or after) that same sessions
row, by this same function or by merge_append (which itself requires the
session to already exist -- it reads MAX(position) FROM messages WHERE session_id = ?). So "no prior sessions row" implies "no prior rows
anywhere in the cascade," unconditionally -- not scoped to bulk-build mode
specifically. Same-connection reads see the same transaction's own
uncommitted writes, so a session_id revisited later in one multi-raw bulk
transaction (e.g. a second accepted revision in the same raw-revision chain)
correctly observes session_row_existed=True on its second occurrence and
still runs the cascade. Default session_row_existed=True reproduces prior
behavior byte-for-byte for any caller that doesn't thread it.

Corrective finding vs polylogue-cs86's own probe

A controlled, resolution-verified before/after measurement (see
"Verification" below for how resolution was verified) using
tests/infra/rebuild_cost_model.py's two-point regression against the
claude-code-session/d9 stratum (n1=15/n2=60, the single largest stratum at
15,954/41,572 = 38% of the live population) shows marginal cost per raw
dropping from 0.05607s -> 0.04951s (-11.7%). Real, but well short of
cs86's 20% probe signal, which does not replicate at realistic sample sizes
-- the delete cascade against indexed tables is genuinely cheap most of the
time; cs86's n=50 single-sample probe was noisier than its own docstring
already warned ("not averaged/repeated -- directional signal only").
Landed anyway: it is a strict no-op removal with a real, if modest, benefit,
zero correctness risk.

A second stratum (codex-session/d9, n1=3/n2=12) was also measured but
produced a negative marginal-cost slope on BOTH before and after runs --
the sample was too small under this session's host contention (~10
concurrent agent worktrees) to trust in either direction, so it is reported
as inconclusive rather than cherry-picked.

What this does NOT close

Per an explicit operator ask for the honest structural diagnosis (recorded
on polylogue-623q): this fix is not an order-of-magnitude lever. The
single-writer invariant remains the floor. The larger remaining lever is
polylogue-9soj (selective secondary-index deferral for blocks/messages
during bulk rebuild -- 7 secondary indexes on blocks, 11 on messages,
all live-maintained on every INSERT throughout replay) -- explicitly NOT
attempted here: a prior blanket-deferral experiment measured +69% WORSE
because the (then-unindexed) delete cascade went from O(log n) to
O(table_size). This PR's fix narrows but does not resolve that risk (the
cascade-serving indexes still need auditing against the ~50-60 non-cascade
query-serving ones before any deferral is safe). field_path_union
(13-16s of a full_replace pass) is confirmed to be unparallelized
Python row-construction cost (_build_message_rows/_build_block_rows:
per-item hashing, JSON encoding, enum lookups), not the union query itself
(which already early-returns for free in the common case) -- the codebase
has an unwired fix for this already built (prepare_session_rows/
PreparedSessionRows, zero production callers), filed as a follow-up.
Concurrency (process-pool start method, parse-worker cap) is confirmed
already fixed and live in source, not the current bottleneck.

Verification

  • devtools test tests/unit/storage/test_archive_tiers_write.py -> 76 passed
  • devtools test tests/unit/maintenance/test_rebuild_parse_apply_split.py tests/unit/storage/test_fts_identity_ledger.py -> 22 passed
  • devtools test tests/benchmarks/test_rebuild_cost_model.py -> 2 passed, 1 skipped (opt-in full run)
  • devtools verify --quick -> exit 0 (rebased onto fresh origin/master, INDEX_SCHEMA_VERSION 51)
  • Resolution-verified before/after: a standalone script
    (/realm/tmp/perf-rebuild-index/measure_ab.py, not part of this PR --
    scratch tooling) asserts polylogue.storage.sqlite.archive_tiers.write.__file__
    resolves to the target worktree before trusting any measurement, guarding
    against the shared-venv editable-install hazard (.pth points at the main
    checkout; an earlier attempt this session silently measured the wrong
    code before this guard was added -- retracted, not reported here).

Ref polylogue-cs86, polylogue-623q

…sions

Problem: write_parsed_session_to_archive's full-replace path always ran
_clear_session_projection_rows (~14 point-DELETEs across action_pairs,
blocks, attachment_refs, paste_spans, and 9 other tables, plus a
parent_message_id-nulling UPDATE) and a bare DELETE FROM messages, even
when the session_id had never been written before -- guaranteed to match
zero rows on a from-empty bulk-build generation. polylogue-cs86 measured
this cascade at ~20% of apply_s on a small (n=50) synthetic probe.

Solution: the caller already ran a PK lookup on `sessions` before its own
upsert (to capture existing_session_raw_id for the union-precedence
decision) -- added a sibling `session_row_existed` boolean from the same
query (existing_session_raw_id alone is ambiguous: a row can exist with a
NULL raw_id). Threaded through to _replace_full_session_messages_and_blocks,
which now skips the delete cascade, the bare messages delete, and the
scoped FTS/trigram deletes when session_row_existed is False. This is
correctness-preserving by construction, not a heuristic: every row the
cascade would remove is written only together with (or after) that same
sessions row, so "no prior sessions row" implies "no prior rows anywhere
in the cascade," unconditionally. Same-connection reads see the same
transaction's own uncommitted writes, so a session_id revisited later in
one multi-raw bulk transaction still runs the cascade correctly.

Corrective finding: a controlled, resolution-verified before/after
measurement (tests/infra/rebuild_cost_model.py's two-point regression,
claude-code-session/d9 stratum, n1=15/n2=60, the largest single stratum at
38% of the live population) shows marginal cost per raw dropping from
0.05607s to 0.04951s (-11.7%) -- real, but well short of cs86's 20% probe
signal, which does not replicate at realistic sample sizes. Landed anyway
as a strict no-op removal with a genuine, if modest, benefit.

Verification: devtools test on tests/unit/storage/test_archive_tiers_write.py
(76 passed), tests/unit/maintenance/test_rebuild_parse_apply_split.py (22
passed combined with test_fts_identity_ledger.py), tests/benchmarks/
test_rebuild_cost_model.py smoke (2 passed, 1 skipped). devtools verify
--quick: exit 0 on fresh origin/master rebase (INDEX_SCHEMA_VERSION 51).

Ref polylogue-cs86, polylogue-623q

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 31, 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: 40 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 Plus

Run ID: a98fbf5f-86b1-4270-a59d-216939ddafcc

📥 Commits

Reviewing files that changed from the base of the PR and between 21477ec and 4afaa8c.

📒 Files selected for processing (1)
  • polylogue/storage/sqlite/archive_tiers/write.py

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 merged commit 2bbe757 into master Jul 31, 2026
1 of 2 checks passed
@Sinity
Sinity deleted the perf/rebuild-index-writes branch July 31, 2026 13:52
Sinity added a commit that referenced this pull request Jul 31, 2026
)

## Summary

Re-ran the index-deferral experiment that `polylogue-9soj` scoped, on
top
of `#3460` (merged minutes before this session started), and closed the
bead with a well-evidenced negative/neutral finding: index deferral is
not the rebuild-speedup lever it looked like, even in its simplest
blanket form. No production code changes in this PR — pure bead
bookkeeping (`.beads/issues.jsonl`).

## Problem

The operator's last full index rebuild took 4h20m (measured stage split:
`index_parsed_write` 47%, `full_replace` 38%, `census` 16% — the write
side is 85%). `polylogue-9soj` recorded that the classic lever — build
secondary B-tree indexes after bulk insert instead of maintaining them
during — had been tried and rejected: dropping all 72 non-unique
`CREATE INDEX` statements before bulk write and recreating after made
`apply_s` **187.6s -> 317.7s (+69%)**, because
`_clear_session_projection_rows`'s
point-DELETEs against ~14 tables became full table scans without
indexes, even though every DELETE matched zero rows on a from-empty
rebuild.

`#3460` (merged 2026-07-31, `2bbe7574d`) threads a `session_row_existed`
boolean into `_replace_full_session_messages_and_blocks` and skips that
entire delete cascade when a session provably has no prior rows —
exactly
true for every session in a full rebuild-from-empty. That looked like it
might have retired the root cause the original index-deferral experiment
tripped over, so the operator asked to re-measure before investing in
the
bead's scoped selective-audit alternative (~50-60 of 72 indexes kept,
requiring a new defer-flag threaded through
`IndexGenerationStore.create()`/`initialize_archive_database()` plus a
new terminal rebuild stage).

## Solution

No code change. Re-measured using the same two-point regression harness
`#3460` itself used to justify its own numbers
(`tests/infra/rebuild_cost_model.py:measure_stratum`), against the two
largest representative strata (`claude-code-session/d9` = 38% of the
live
population by raw count, `codex-session/d9`). The deferred variant
monkeypatches `archive_tiers.ARCHIVE_DDL_BY_TIER[ArchiveTier.INDEX]` to
strip the 72 non-unique `CREATE INDEX` statements before the pass, then
recreates them against the built `index.db` afterward (scratch scripts,
not committed: `/realm/tmp/perf-rebuild-index/measure_defer.py`,
`measure_defer_breakdown.py`).

**Result**: `#3460` genuinely fixed the pathology — the catastrophic
+69% regression is gone. But blanket deferral doesn't meaningfully help
either. Repeated single-pass measurements (3x each, n=15 and n=60,
`claude-code-session/d9`, taken clean of host contention):

| metric | eager (median) | deferred (median) | delta |
| --- | --- | --- | --- |
| wall_s @ n=60 | 6.22s | 5.26s | -15% |
| wall_s @ n=15 | 3.98s | 3.06s | -23% |
| cpu_s @ n=60 | 2.77s | 2.75s | ~0% |
| cpu_s @ n=15 | 1.50s | 1.43s | -5% |
| **marginal s/raw (wall)** | 0.0498 | 0.0489 | **-2%** |
| **marginal s/raw (cpu)** | 0.0281 | 0.0293 | **+4%** |

CPU time (immune to other processes stealing cycles on this session's
~10-concurrent-agent-worktree host) is the trustworthy signal here: it's
within noise either direction. Wall-clock shows a consistent small
edge to deferred, but it's driven by the `fixed_s` intercept (fresh
archive DDL bootstrap: 72 fewer `CREATE INDEX` at connect time, ~1s),
not
a per-raw saving — and a real rebuild pays that fixed cost once for the
whole run, not once per stratum sample. Projected against 4h20m, the
realistic win is low tens-of-seconds, not an order of magnitude.

**First-pass numbers were a red herring.** An initial single-sample
2-point run showed deferred 2.4x *worse* (marginal 0.1246 vs 0.0481
s/raw) — but that run overlapped an unrelated background
`test_full_population_projection` baseline attempt (which itself failed
on `pytest-timeout`'s default 120s ceiling — the opt-in full-population
test needs `--timeout=0`, undocumented in the harness's own docstring
example). Repeating cleanly after that process exited reproduced neither
the win nor the loss — flat, near-zero difference. This is recorded in
the close reason as a methodology note: single-sample 2-point
regressions
on a shared, noisy host are not trustworthy without repetition.

**Root cause of the wash**: `#3460` already removed the one place index
absence helped (zero-match point-DELETEs going O(n) without an index).
Every other per-session write during bulk-build (messages/blocks/
action_pairs inserts, `field_path_union`, `graph_resolve`) is genuinely
INSERT-bound — B-tree maintenance during insert was never the dominant
cost. `_repopulate_bulk_build_derived_state`'s post-pass FTS/trigram/
action_pairs/delegation_facts bulk repopulation reads back through
`blocks`/`messages` at full-table scale regardless of when secondary
indexes get built, confirmed by instrumenting its `bulk_build_substages`
timings directly (each sub-stage within noise of the other, eager vs
deferred).

`polylogue-9soj` is closed rather than narrowed to its selective
variant:
since blanket deferral (all 72) is already a wash, a subset (50-60)
would
move the needle even less — the selective audit isn't worth building.

## Verification

- `bd show polylogue-9soj --json` -> `status: closed`, full numbers in
  `close_reason`.
- Measurement scripts run via

`/realm/project/polylogue/.claude/worktrees/agent-a2955c03f32b27b5e/.venv/bin/python`
  (own venv, resolution-verified against
  `polylogue.storage.sqlite.archive_tiers.write.__file__` before every
  run — guards the shared-venv `.pth` hazard that pointed the main
  checkout's venv at `/realm/project/polylogue` and invalidated other
  lanes' numbers tonight).
- `devtools verify --quick` not applicable — no `polylogue/` source
  changed, only `.beads/issues.jsonl`. Pre-push hook's beads-only-diff
  check ran automatically on push: "backlog hygiene: zero unhandled
  findings across 1434 issues scanned."
- Not run: the full `test_full_population_projection
--run-cost-model-full`
  harness end to end (needs `--timeout=0`; the per-stratum quick
  methodology above is the same one `#3460` itself used for its landed
  claims, and is sufficient evidence for a negative/neutral result on a
  ~2-4% effect size).

Ref polylogue-9soj, polylogue-623q, polylogue-cs86
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]>
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