Skip to content

perf(storage): persist blob verification receipts across restarts - #3566

Merged
Sinity merged 2 commits into
masterfrom
feature/perf/persist-blob-verification-receipts
Aug 2, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/perf/persist-blob-verification-receipts

Conversation

@Sinity

@Sinity Sinity commented Aug 2, 2026

Copy link
Copy Markdown
Owner

Summary

Raw-authority frontier census now persists blob verification receipts in source.db, so an unchanged blob verified in a prior census is trusted across daemon restarts instead of being re-hashed from scratch every time.

Problem

_verified_blob_bytes (polylogue/storage/raw_reconciler.py) cached content-hash verification only in a process-lifetime dict (_VERIFIED_BLOB_STATS), so the cache was empty again after every daemon restart. Every restart forced a full re-hash of every accepted frontier blob, even ones that hadn't changed since the last census. Given the corpus's measured size skew (top 5% of raws = 69% of bytes, polylogue-el374), this is tens of GiB of wasted reads per restart, contributing to the read-amplification finding in the broader performance audit.

Solution

  • New durable table verified_blob_receipts in source.db (migration storage/sqlite/migrations/source/017_verified_blob_receipts.sql, SOURCE_SCHEMA_VERSION bumped 16 → 17), keyed by blob_hash, recording the on-disk fingerprint (st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns) observed at the moment BlobStore.verify() last proved the bytes match their content-addressed hash.
  • _verified_blob_bytes now reads this receipt first and only trusts it when every fingerprint field matches the blob's current stat() exactly. Any mismatch — a changed size/mtime/ctime, a different inode, or no receipt at all — forces a fresh verify() re-hash; a stale receipt is never partially trusted. On a successful fresh verify, the receipt is rewritten to the current fingerprint.
  • _frontier_items (the sole caller path, through _classify_frontier) now commits the connection it already held open, so the receipt write actually persists — previously this connection was opened read-write but never committed, since it had no writes to make.
  • Removed the now-superseded process-memory cache (_VERIFIED_BLOB_STATS) entirely.

Safety invariant (deliberately conservative, matters more than the performance win): the receipt is a hint, never an authority. Absent proof the blob is byte-identical to what was last verified, the default is always "re-verify from scratch."

Verification

  • devtools test tests/unit/storage/test_raw_authority_ledger.py tests/unit/storage/test_durable_migrations.py — 71 passed / 40 passed. 10 pre-existing failures in test_raw_authority_ledger.py (all "no messages, no positive conversational evidence" refusals on empty-text codex fixtures) reproduce identically on origin/master baseline and are unrelated to this change.
  • New test test_verified_blob_receipt_skips_rehash_on_unchanged_blob_across_census_passes patches BlobStore.verify to count real invocations across two census passes over the same unchanged blob and asserts zero re-hashing on the second pass.
  • New test test_verified_blob_receipt_invalidates_when_blob_bytes_change_underneath_it mutates blob bytes in place (same content-addressed path, different content) between two census passes and asserts the item is reclassified MISSING_BYTES_REACQUIRE. Anti-vacuity: I manually reverted the fingerprint comparison to "any receipt is trusted" and confirmed this exact test fails, then restored the fix and re-confirmed it passes.
  • devtools verify --quick — exit 0 (format, lint, mypy --strict, render all --check, schema-versioning/classifier-fingerprints/schema-promotion lab policies all green). Ran again automatically via the pre-push hook with the same result.
  • devtools lab policy schema-versioning — schema evolution policy intact (0 invalid durable migration resources, 0 undeclared index deltas).

Ref polylogue-byw3y

@coderabbitai

coderabbitai Bot commented Aug 2, 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: 32 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: 50b47617-a5f7-4f0c-9b79-9d61476b2e9f

📥 Commits

Reviewing files that changed from the base of the PR and between 4a3842e and 11ca3fd.

📒 Files selected for processing (7)
  • .beads/issues.jsonl
  • docs/schema.md
  • polylogue/storage/raw_reconciler.py
  • polylogue/storage/sqlite/archive_tiers/source.py
  • polylogue/storage/sqlite/migrations/source/017_verified_blob_receipts.sql
  • tests/unit/storage/test_durable_migrations.py
  • tests/unit/storage/test_raw_authority_ledger.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 force-pushed the feature/perf/persist-blob-verification-receipts branch 2 times, most recently from 54dcd06 to 317c5d0 Compare August 2, 2026 14:30
Sinity added 2 commits August 2, 2026 16:36
Problem: raw-authority frontier census re-verifies every accepted
frontier blob's content-hash from scratch on every daemon restart.
_verified_blob_bytes cached verification only in a process-lifetime
dict, so the cache was empty again after every restart, forcing a
full content re-hash of every accepted blob -- tens of GiB of reads
given the corpus's measured size skew (top 5% of raws = 69% of
bytes, polylogue-el374).

What changed: verification receipts now persist in a new source.db
table, verified_blob_receipts (migration 017, SOURCE_SCHEMA_VERSION
17), keyed by blob_hash and recording the on-disk fingerprint
(device/inode/size/mtime/ctime) observed at the moment
BlobStore.verify() last proved the bytes match their content-
addressed hash. _verified_blob_bytes (storage/raw_reconciler.py)
now checks this durable receipt before re-hashing, and only trusts
it when every fingerprint field matches the blob's CURRENT stat()
exactly -- any mismatch, including the blob having vanished or been
replaced in place, forces a fresh verify() and rewrites the receipt.
_frontier_items now commits through the connection it already holds
open (previously read-only in effect) so the receipt persists.

Alternatives rejected: keying the receipt on hash alone with no
fingerprint check would have been simpler, but would silently trust
a blob whose bytes were corrupted/mutated after the receipt was
recorded -- the safety invariant here matters more than the
performance win, so the fingerprint check is deliberately strict
and defaults to re-verifying whenever it can't prove "unchanged".

Verification:
- devtools test tests/unit/storage/test_raw_authority_ledger.py
  tests/unit/storage/test_durable_migrations.py -- 71 passed, 40
  passed respectively; 10 pre-existing failures in
  test_raw_authority_ledger.py are unrelated to this change
  (confirmed identical on origin/master baseline, all reproduce the
  same "no messages, no positive conversational evidence" refusal
  for empty-text codex fixtures).
- New test
  test_verified_blob_receipt_skips_rehash_on_unchanged_blob_across_census_passes
  counts actual BlobStore.verify() invocations across two census
  passes and asserts zero re-hashing on the second pass over an
  unchanged blob.
- New test
  test_verified_blob_receipt_invalidates_when_blob_bytes_change_underneath_it
  mutates blob bytes in place between two census passes and asserts
  the item is reclassified MISSING_BYTES_REACQUIRE. Anti-vacuity:
  manually reverted the fingerprint check to "any receipt is trusted"
  and confirmed this exact test fails before restoring the fix.
- devtools verify --quick -- exit 0 (format, lint, mypy --strict,
  render all --check, schema-versioning/classifier-fingerprints/
  schema-promotion lab policies all green).

Ref polylogue-byw3y
@Sinity
Sinity force-pushed the feature/perf/persist-blob-verification-receipts branch from 317c5d0 to 11ca3fd Compare August 2, 2026 14:36
@Sinity
Sinity merged commit d0f522d into master Aug 2, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/persist-blob-verification-receipts branch August 2, 2026 14:38
Sinity added a commit that referenced this pull request Aug 2, 2026
Sinity added a commit that referenced this pull request Aug 2, 2026
…3573)

## Summary
PR #3566 and PR #3568 (developed concurrently in separate worktrees during a merge-train session) both claimed source-tier migration number 017 with `SOURCE_SCHEMA_VERSION` left at 17. The rebase merged clean at the file level (distinct new files, no textual conflict), but `migration_runner.py`'s `_load_migrations()` hard-fails with `MigrationError` on duplicate version numbers.

## Problem
Reproduced live immediately after both PRs landed on master:
```
MigrationError duplicate source migration versions: [2, 3, ..., 16, 17, 17]
```
Any real `migrate_archive_tier(ArchiveTier.SOURCE, ...)` call — daemon startup against an older archive, `polylogue ops backup`, schema commit — would hit this the moment it actually ran. Caught during merge-train verification, before any live use.

## Solution
- Renamed `017_raw_live_source_reconciliation_receipts.sql` to `018_*`.
- Bumped `SOURCE_SCHEMA_VERSION` 17 → 18 (`archive_tiers/source.py`).
- Fixed `test_durable_migrations.py`'s now-stale `applied_versions`/`to_version` assertions.
- `test_source_publication_backfill_requires_verified_backup` simulated a v9 archive by dropping tables but not the `revision_authority_evidence` column (since `workspace_env` bootstraps via current canonical DDL, which already includes it) — added the missing `ALTER TABLE raw_sessions DROP COLUMN revision_authority_evidence` so the fixture actually represents a pre-v18 archive; without it migration 018's own `ADD COLUMN` failed with "duplicate column name".
- `docs/schema.md`'s hand-maintained `SOURCE_SCHEMA_VERSION` reference line.

## Verification
```
devtools test tests/unit/storage/test_durable_migrations.py tests/unit/maintenance/test_raw_live_source_reconciliation_apply.py tests/unit/storage/test_raw_authority_ledger.py
# 85 passed
devtools verify --quick
# exit 0
```
Reproduced the pre-fix crash directly: `_load_migrations(ArchiveTier.SOURCE)` raised `MigrationError` before this fix, loads cleanly (18 steps) after.
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem: CircleCI's quick-gate job hand-picked five discrete steps
(render-all-check, ruff check, ruff format, mypy) as a stand-in for
`devtools verify --quick`, per its own header comment. That subset had
drifted from the real thing: devtools/verify.py's default `if not commit:`
block has grown to ~17 steps over time (topology/layering/closure-matrix,
lab schema roundtrip, manifests, ci-workflows, doc-commands,
docs-coverage, test-infra-currency, pytest-timeout-overrides,
degrade-loudly, hash-boundary-census, schema-versioning,
classifier-fingerprints, schema promotion audit, and now
demo-tour-freshness), none of which quick-gate ever ran. The
schema-versioning check specifically was wired only into
.github/workflows/ci.yml, a GitHub Actions workflow that does not
execute (GHA is billing-locked; CircleCI is the only live CI in this
repo) -- so the migration-number collision behind PR #3566/#3568 that
made the live archive briefly unqueryable (fixed by hand in PR #3573)
would not have been caught by any CI that actually ran, despite
appearing "CI-gated" in ci.yml. See polylogue-ze5i.

What changed: replaced the four hand-picked ruff/mypy/render-all steps
with a single `devtools verify --quick` call, which is the real superset
and self-heals going forward -- any future step added to build_verify_steps'
default block is automatically covered without a matching CircleCI edit.
`devtools verify public-claims --json` stays separate since it is not
part of that default block. Added a `lab-policies` job, wired into the
existing nightly scheduled workflow alongside full-suite, running the
7 `lab policy *` checks that remain intentionally --lab-only
(timestamp-doctrine, insight-honesty, demo-packet-registry, docs-drift,
campaign-archive-boundaries, backlog-hygiene, bead-graph) so a
continuously-failing policy is at least visible on a schedule instead of
reachable only via a human remembering `devtools verify --lab`. Each
step uses `when: always` so backlog-hygiene/bead-graph's known
pre-existing backlog debt (485 findings / 225 missing-AC beads) does not
mask a regression in one of the other five checks in the same job.

Verification: reintroduced the exact migration-number-collision shape
(bumped INDEX_SCHEMA_VERSION without a lifecycle.py delta declaration)
and confirmed `devtools verify --quick` -- the command now wired into
quick-gate -- fails with "Policy violation: each index schema bump needs
a declared delta class"; reverted. Also confirmed demo-tour-freshness
catches injected drift in docs/examples/demo-tour/report.json; reverted.
`python -c "import yaml; yaml.safe_load(open('.circleci/config.yml'))"`
parses cleanly; `devtools verify ci-workflows` passes (pre-existing
unrelated warning on .github/workflows/ci.yml, not touched here).

Ref polylogue-ze5i

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…_verify_steps (#3587)

## Summary

Closes the gate-placement question in polylogue-ze5i for all 10
`devtools lab policy *` checks. Promotes `demo-tour-freshness`
(previously red) into the default verify gate alongside
`schema-versioning`/`classifier-fingerprints`, fixes CircleCI's
`quick-gate` job so it actually runs that gate instead of a stale
hand-picked subset, and wires the remaining 7 `--lab`-only checks into a
new nightly CircleCI job so a continuously-failing policy is at least
visible.

## Problem

Measured 2026-07-28 (polylogue-ze5i): schema-versioning,
demo-tour-freshness, backlog-hygiene, and bead-graph all sat behind
`devtools verify --lab`, which no standing gate runs. A migration-number
collision (PR #3566/#3568) made the live archive briefly unqueryable and
was only caught by hand afterward (PR #3573).

A prior session moved `schema-versioning` (and
`classifier-fingerprints`) out of `--lab` into `devtools/verify.py`'s
default `if not commit:` block. But investigating further this session
found that promotion was hollow in practice: CircleCI's `quick-gate` job
-- the only CI that actually runs in this repo (GitHub Actions is
billing-locked/dark; `.github/workflows/ci.yml` references
`schema-versioning` but does not execute) -- hand-picked five discrete
steps (`render all --check`, `public-claims`, ruff, mypy) instead of
calling `devtools verify --quick`. None of `verify topology`/`verify
layering`/`schema-versioning`/`classifier-fingerprints`/`schema
promotion audit`/etc. (~17 steps total) ever ran in live CI.

`demo-tour-freshness` itself was red: the committed
`docs/examples/demo-tour/` fixture was missing a `healed_tiers` key the
demo receipts code had already grown.

## Solution

- `devtools/verify.py`: moved `lab policy demo-tour-freshness` from the
`if lab:` block into the default `if not commit:` block, with a comment
on why it's safe to gate every push (deterministic -- wall-clock timing
already masked before comparison -- and fixed-cost against one committed
fixture, unlike the corpus-scanning `backlog-hygiene`/`bead-graph`).
Added an explanatory comment on why those two stay `--lab`-only.
- `docs/examples/demo-tour/`: regenerated via `polylogue demo tour
--out-dir polylogue-demo-tour --force` and copied the fresh evidence in,
fixing the drift.
- `.circleci/config.yml`: replaced `quick-gate`'s four hand-picked steps
with a single `devtools verify --quick` call (public-claims stays
separate since it isn't part of that block) -- this self-heals going
forward, since any future addition to `build_verify_steps`' default
block is automatically covered without a matching CircleCI edit. Added a
`lab-policies` job wired into the existing nightly scheduled workflow,
running the 7 checks that remain intentionally `--lab`-only
(`timestamp-doctrine`, `insight-honesty`, `demo-packet-registry`,
`docs-drift`, `campaign-archive-boundaries`, `backlog-hygiene`,
`bead-graph`), each step using `when: always` so the two known-red
corpus-scan checks don't mask a regression in the other five.
- `tests/unit/devtools/test_verify.py`: fixed
`test_quick_verify_omits_pytest`'s hardcoded step list, which was
already failing on master before this change (missing
`classifier-fingerprints`, added in an earlier PR without a matching
test update).
- Filed polylogue-2bp5f (485 backlog-hygiene findings) and
polylogue-83nhi (225 beads missing acceptance criteria) to track the
corpus-wide debt those two checks report, since fixing it is out of
scope for a gate-placement change.
- Closed polylogue-ze5i with the full per-policy classification table
and rationale.

## Verification

- `devtools test tests/unit/devtools/test_verify.py` -- 88 passed.
- `devtools verify --quick` -- green end-to-end, ~90-105s total.
- Anti-vacuity: reintroduced the exact migration-number-collision shape
(`INDEX_SCHEMA_VERSION` bump with no `lifecycle.py` delta declaration)
and confirmed `devtools verify --quick` -- the exact command now wired
into CircleCI's `quick-gate` -- fails with `Policy violation: each index
schema bump needs a declared delta class`; reverted.
- Anti-vacuity: injected drift into
`docs/examples/demo-tour/report.json` and confirmed `devtools lab policy
demo-tour-freshness` catches it; reverted.
- `python -c "import yaml;
yaml.safe_load(open('.circleci/config.yml'))"` parses cleanly; `devtools
verify ci-workflows` passes (one pre-existing, unrelated warning on
`.github/workflows/ci.yml`, not touched here).

Not run: the actual CircleCI pipeline (can't trigger from here) --
verified locally that the exact command it now calls (`devtools verify
--quick`) behaves as claimed.

Ref polylogue-ze5i

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Verification now includes additional policy checks, improving
detection of stale demo content and classification issues.
- Nightly validation now covers the complete policy-check suite,
including known backlog items.

- **Documentation**
- Refreshed demo-tour examples with current manifest identifiers, timing
data, output sizes, and report metadata.
- Updated recorded transcripts and reports while preserving command
results and exit statuses.

- **Tests**
- Updated verification expectations to reflect the expanded quick-check
coverage.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[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