Skip to content

perf(storage): stop rewriting user_version on every same-version tier reapply - #4021

Merged
Sinity merged 4 commits into
masterfrom
feature/harness/bootstrap-ddl-counter
Aug 19, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/harness/bootstrap-ddl-counter

Conversation

@Sinity

@Sinity Sinity commented Aug 19, 2026 •

Copy link
Copy Markdown
Owner

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_version write 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):

wall cpu
NVMe, default synchronous=FULL 7.78s 0.24s
NVMe, PRAGMA synchronous=OFF 0.03s 0.03s
tmpfs, default 0.02s 0.02s

Under 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.executescript with the process burning almost no CPU — it is durability wait, not computation.

This matters more than it looks, because devtools/verify_runs.py sets POLYLOGUE_PYTEST_TMPFS = "0" under default_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_COUNTS keyed (tier, outcome) under its own lock, with archive_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 for EMBEDDINGS, which is excluded from the cache.
  • ddl_reapply — non-empty database, whole-tier DDL re-executed. Each one is a fully redundant executescript plus its commit fsync.

The counter is an integer increment against work that already runs SQL. The one added query is a COUNT(*) over sqlite_master on the EMBEDDINGS path, 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.json sidecar per worker at session end and read_archive_ddl_counts() sums them, mirroring the existing _flush_counts / read_progress_counts pair exactly. The controller folds the total into the summary payload as archive_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

devtools test tests/unit/storage/test_archive_tier_init.py tests/unit/devtools/test_pytest_progress_plugin.py
  => 23 passed in 9.63s

devtools verify --quick
  => "status": "success"

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:

"archive_tier_init_counts": {
  "audit.ddl_fresh": 1,      "audit.prototype_hit": 2,
  "embeddings.ddl_fresh": 3,
  "index.ddl_fresh": 1,      "index.prototype_hit": 2,
  "ops.ddl_fresh": 1,        "ops.ddl_reapply": 8,   "ops.prototype_hit": 2,
  "source.ddl_fresh": 1,     "source.prototype_hit": 2,
  "user.ddl_fresh": 1,       "user.prototype_hit": 2
}

That single field already shows the two findings the instrument exists to size: embeddings never gets a prototype_hit, and ops alone accumulates ddl_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_database treats a same-version tier three different ways — INDEX gets its targeted benign-DDL convergence, USER gets its annotation-schema ensure, and every other tier returns immediately. OPS alone routes back through initialize_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 OPS the same targeted treatment INDEX already has — run its convergence plan and _ensure_ops_* helpers, skip the whole-schema executescript. That is not done here; it needs its own change and a test proving _ensure_schema_drift_samples_check still fires on an already-versioned database, since that repair deliberately runs at an unchanged user_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_ddl fails 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_reapply asserts ops.ddl_reapply == 2 and index.ddl_reapply absent, so it fails both if OPS stops reapplying and if another tier starts. test_read_archive_ddl_counts_sums_every_worker_sidecar fails 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 executescript on a user_version match. Measuring the parts first showed that would have been the wrong target and actively unsafe.

Isolating a no-op OPS reapply on NVMe:

what runs median
executescript + PRAGMA user_version = N + commit (before) 148.80ms
executescript + commit, no version write 0.34ms
executescript only 0.33ms
no executescript, version write + commit 147.49ms
connect + PRAGMA foreign_keys only 0.01ms

The executescript costs 0.33ms. Hundreds of no-op CREATE TABLE IF NOT EXISTS statements write nothing and are effectively free. The entire 148ms is PRAGMA 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:

  1. The reapply is the declared delivery mechanism for same-version additive OPS changes — initialize_archive_database's own comment says it exists so "existing same-version archives receive newly introduced tables and indexes", and OPS_BENIGN_DDL_CONVERGENCE_PLAN is two index statements whose docstring says it runs after canonical DDL reapplication. It presumes the reapply rather than replacing it.
  2. It would disable _ensure_schema_drift_samples_check, which repairs a stale CHECK at an unchanged user_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_check fail, and the shipped guard leaves it passing. That test is the load-bearing red twin.

After the fix, nvme OPS reapply is 0.62ms against tmpfs 0.66ms — the reapply is no longer I/O-bound at all.

Audit of the same shape on other tiers

initialize_archive_tier is reached directly, on databases that may be non-empty, from daemon/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) and maintenance/schema_inference_gate.py (any tier). The header write was unconditional for all of them, so the fix is placed in _initialize_archive_tier_ddl and covers every caller and tier rather than special-casing OPS.

Via initialize_archive_database the 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.py fails 1–2 tests order-dependently (test_bootstrap_reconciles_and_persists_interrupted_train_evidence, test_bootstrap_finishes_persisted_applied_train_without_reapplying). This reproduces on pristine origin/master — 2, 1, 1 failures across three runs with master's bootstrap.py and pytest_progress_plugin.py checked 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

Bead Whole-Bead disposition Evidence Residual
polylogue-c1jgh satisfied tests/unit/storage/test_archive_tier_init.py; the devtools test command above none — all three contract tests land, and the INDEX audit it asked for is in the body above

The three-part test contract is met, with one substitution the measurement forced: the bead's item (2) asked to prove the executescript is 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

@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, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 816afbca-323e-44ba-aa2c-111233b31109


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 changed the title feat(harness): count archive tier initializations into the run receipt perf(storage): stop rewriting user_version on every same-version tier reapply Aug 19, 2026
@Sinity
Sinity merged commit 44bd927 into master Aug 19, 2026
3 checks passed
@Sinity
Sinity deleted the feature/harness/bootstrap-ddl-counter branch August 19, 2026 08:47
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