Repository navigation
perf(storage): stop rewriting user_version on every same-version tier reapply - #4021
Merged
Merged
Conversation
Ref polylogue-l218h
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 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 |
… reapply Ref polylogue-c1jgh
Sinity
added a commit
that referenced
this pull request
Aug 19, 2026
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Counts how each archive tier initialization actually resolved — page-copy restore, fresh DDL, or whole-schema reapply — publishes the tally into the run's pytest summary, and then uses it to find and fix the actual cost: a redundant
PRAGMA user_versionwrite that turned every same-version reapply into a full commit fsync. Measured on NVMe, a reapply drops from 148.80ms to 0.62ms.Problem
The archive bootstrap turns out to be the suite's largest unmeasured cost, and the split that matters is invisible from outside the process.
Measured on this machine, identical work (the full 6-tier DDL, 2.2 MB written, one process):
synchronous=FULLPRAGMA synchronous=OFFUnder concurrent lane load the NVMe figure reached 36–50s while tmpfs stayed at 0.63–0.71s. Absolute NVMe numbers swing with contention; the ~200–260x ratio held across every measurement. cProfile attributes ~99% of cold wall to
sqlite3.Connection.executescriptwith the process burning almost no CPU — it is durability wait, not computation.This matters more than it looks, because
devtools/verify_runs.pysetsPOLYLOGUE_PYTEST_TMPFS = "0"underdefault_full_suite_scratch: broad-suite runs deliberately use NVMe while focused runs get tmpfs. So the penalty applies to the full corpus run and is structurally invisible to per-module focused profiling, which is how it went unnoticed.To size any fix you need to know how many initializations happen and, critically, which kind — and there was no way to know. All three outcomes look identical to a caller. A throwaway instrumented run showed the volume is real and wildly uneven (
live_batch_support: 377 builds for 138 tests;schema_generation: 6 for 35), but a throwaway patch is not a measurement anyone can repeat, and the rate varies 16x across modules so a handful of samples cannot be extrapolated.Solution
polylogue/storage/sqlite/archive_tiers/bootstrap.py—_TIER_INIT_COUNTSkeyed(tier, outcome)under its own lock, witharchive_tier_init_counts()/reset_archive_tier_init_counts()as the read side. Three outcomes, because they have three different costs and three different fixes:prototype_hit— restored by page copy from this process's cache.ddl_fresh— verifiably-empty database, real DDL. Once per tier per process for cacheable tiers; once per archive forEMBEDDINGS, which is excluded from the cache.ddl_reapply— non-empty database, whole-tier DDL re-executed. Each one is a fully redundantexecutescriptplus its commit fsync.The counter is an integer increment against work that already runs SQL. The one added query is a
COUNT(*)oversqlite_masteron theEMBEDDINGSpath, which bypasses the cacheable branch and so had no emptiness check to reuse; without it that tier could not be classified at all.devtools/pytest_progress_plugin.py—_flush_archive_ddl_counts()writes one.archive-ddl.jsonsidecar per worker at session end andread_archive_ddl_counts()sums them, mirroring the existing_flush_counts/read_progress_countspair exactly. The controller folds the total into the summary payload asarchive_tier_init_counts. Sidecars rather than a shared file because the counters live inside each pytest process — the supervisor cannot sample them from outside the way it samples RSS or I/O. Telemetry failures are swallowed: a counter must never fail a run.Verification
End-to-end on a real run (
tests/unit/cli/test_plain_cli_snapshots.py), read back out of.cache/verify/current-pytest-summary.json:That single field already shows the two findings the instrument exists to size:
embeddingsnever gets aprototype_hit, andopsalone accumulatesddl_reapply.What the instrument corrected while being built
Writing the tests disproved my own reading of the code, which is worth recording because it narrows the follow-up considerably. I expected any tier reopened at the same version to re-run its DDL. It does not:
initialize_archive_databasetreats a same-version tier three different ways —INDEXgets its targeted benign-DDL convergence,USERgets its annotation-schema ensure, and every other tier returns immediately.OPSalone routes back throughinitialize_archive_tier, which finds a non-empty database and re-executes the entire tier schema.So the redundant-executescript problem is one tier wide, and the precedent for fixing it is in the same function: give
OPSthe same targeted treatmentINDEXalready has — run its convergence plan and_ensure_ops_*helpers, skip the whole-schemaexecutescript. That is not done here; it needs its own change and a test proving_ensure_schema_drift_samples_checkstill fires on an already-versioned database, since that repair deliberately runs at an unchangeduser_version(#3451 / polylogue-u6tl) and a naive version-equality skip would silently disable it.Anti-vacuity
test_tier_init_counts_separate_page_copy_from_fresh_ddlfails if the restore and DDL outcomes share a counter — collapsing them is precisely what hides the cost.test_tier_init_counts_expose_the_ops_only_whole_schema_reapplyassertsops.ddl_reapply == 2andindex.ddl_reapplyabsent, so it fails both if OPS stops reapplying and if another tier starts.test_read_archive_ddl_counts_sums_every_worker_sidecarfails without summation, and its truncated-sidecar leg fails if a JSON error escapes and takes the run's telemetry with it.The fix the instrument found, and the one it ruled out
polylogue-c1jgh proposed skipping the whole-tier
executescripton auser_versionmatch. Measuring the parts first showed that would have been the wrong target and actively unsafe.Isolating a no-op OPS reapply on NVMe:
executescript+PRAGMA user_version = N+ commit (before)executescript+ commit, no version writeexecutescriptonlyexecutescript, version write + commitPRAGMA foreign_keysonlyThe
executescriptcosts 0.33ms. Hundreds of no-opCREATE TABLE IF NOT EXISTSstatements write nothing and are effectively free. The entire 148ms isPRAGMA user_version = N, which rewrites the database header even when N is already the stored value, dirtying a page and forcing the commit to fsync.So this PR removes only the redundant header write. It does not skip the schema pass, for two independent reasons:
initialize_archive_database's own comment says it exists so "existing same-version archives receive newly introduced tables and indexes", andOPS_BENIGN_DDL_CONVERGENCE_PLANis two index statements whose docstring says it runs after canonical DDL reapplication. It presumes the reapply rather than replacing it._ensure_schema_drift_samples_check, which repairs a stale CHECK at an unchangeduser_version(feat(storage): wire literal_check into DDL, fix a drift CHECK gap #3451 / polylogue-u6tl).Point 2 is not an argument, it is a measurement: patching in the proposed version-equality skip makes
test_same_version_reapply_still_repairs_a_stale_drift_samples_checkfail, and the shipped guard leaves it passing. That test is the load-bearing red twin.After the fix,
nvme OPS reapplyis 0.62ms againsttmpfs 0.66ms— the reapply is no longer I/O-bound at all.Audit of the same shape on other tiers
initialize_archive_tieris reached directly, on databases that may be non-empty, fromdaemon/fts_startup.py(INDEX),daemon/cursor_lag_baseline.py×2,daemon/convergence_stages.py,daemon/embedding_backlog.py(OPS),operations/durable_change_train.py×2 (AUDIT),storage/sqlite/durable_change_train.py×4 (SOURCE) andmaintenance/schema_inference_gate.py(any tier). The header write was unconditional for all of them, so the fix is placed in_initialize_archive_tier_ddland covers every caller and tier rather than special-casing OPS.Via
initialize_archive_databasethe picture is narrower and worth recording: only OPS routes a same-version open back through the whole-schema path. INDEX gets its targeted benign-DDL convergence, USER its annotation-schema ensure, and every other tier returns immediately.Pre-existing failures, not caused by this PR
tests/unit/storage/test_durable_change_train.pyfails 1–2 tests order-dependently (test_bootstrap_reconciles_and_persists_interrupted_train_evidence,test_bootstrap_finishes_persisted_applied_train_without_reapplying). This reproduces on pristineorigin/master— 2, 1, 1 failures across three runs with master'sbootstrap.pyandpytest_progress_plugin.pychecked out — and is identical with and without this PR's changes under deterministic ordering (-p no:randomly: 2 failed both ways, same two tests).Worth stating how nearly this went wrong: I first "bisected" it to this PR by comparing
-k-isolated runs (which always pass) against full-module runs (which flake), and briefly reverted a correct fix on that false signal. The tests only fail as part of the full module. They are unrelated to this change and want their own Bead.Bead disposition matrix
tests/unit/storage/test_archive_tier_init.py; thedevtools testcommand aboveThe three-part test contract is met, with one substitution the measurement forced: the bead's item (2) asked to prove the
executescriptis skipped on a version match. It is not skipped, because the measurement showed it costs 0.33ms and skipping it would break both same-version OPS additive delivery and the u6tl repair. The equivalent proof for what this PR actually does —test_same_version_reapply_does_not_rewrite_user_version, which traces the connection and asserts no header assignment is issued — is in its place. Items (1) drift-samples repair still fires and (3) fresh-db path unchanged are as specified.polylogue-yh20k (EMBEDDINGS excluded from the prototype cache) is untouched and remains the larger per-event cost at ~259ms per fresh archive against this reapply's former ~148ms.
Ref polylogue-l218h, polylogue-yh20k