Skip to content

fix: Anchor the sqlite degradation ratchet on content, not counts - #5096

Merged
Sinity merged 1 commit into
masterfrom
fix/sqlite-degradation-content-anchored
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/sqlite-degradation-content-anchored

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

docs/plans/sqlite-degradation-baseline.json was a count ratchet — {"total": 424, "sites": {<file>: <int>}} over 114 files. This converts it, and devtools/verify_layering.py's consumption of it, to the content-anchored form the repo already implements in devtools/verify_patterns.py: a site is identified by (file, sha1 of its normalized handler source), and new violations are a Counter difference. The conversion admits exactly the violations the count form admitted — zero added, zero dropped.

Problem

A per-file integer ceiling is measured against whichever baseline the branch started from. Neither of two concurrent branches sees the other's additions, so both are green and their sum on master is not. Demonstrated on the count form (pkg/reader.py, shared baseline {pkg/reader.py: 1}):

shared baseline: {'pkg/reader.py': 1}
branch A findings: [{'file': 'pkg/reader.py', 'rule': 'sqlite_degradation_sites_grew', 'observed': 2, 'baseline': 1}]
branch B findings: [{'file': 'pkg/reader.py', 'rule': 'sqlite_degradation_sites_grew', 'observed': 2, 'baseline': 1}]
branch B against the baseline branch A raised to 2: []          <- B is GREEN
merged against branch A's raised baseline: [{... 'observed': 3, 'baseline': 2}]   <- master is RED

Branch A legitimately raises its file's entry from 1 to 2 for the handler it added. Branch B, rebased on that, is then green for a different handler it added — the raise A made for A's site covers B's site, because the ceiling cannot tell them apart. After both land, master carries 3 against a ceiling of 2. The merge is the first place anyone finds out. The count form also reports one aggregate sqlite_degradation_sites_grew for the merged file, never the two distinct sites that grew it.

This is the same shape verify_patterns.py moved away from in #4199, and docs/plans/layering-surface-baseline.json (a set of {target, file, import} triples) never had.

Solution

  • devtools/sqlite_degradation.py: census_sqlite_degradation_sites (file → int) becomes census_sqlite_degradation_anchors (Counter[(file, digest)]). The digest is sha1 over the handler's own source segment, whitespace-normalized — so a baseline entry survives reindentation, line wrapping, and unrelated edits elsewhere in the same file. load_sqlite_degradation_baseline returns the same Counter and rejects malformed entries (matching verify_patterns._baseline's strictness).
  • devtools/verify_layering.py: violations are observed - baseline, ratchet headroom is baseline - observed. Rule renamed sqlite_degradation_sites_grew → sqlite_degradation_site_added, carrying anchor/digest. Direction is unchanged: anchors may be removed, never added.
  • Baseline file: sites → anchors, a sorted list of {file, digest[, count]}. count appears only where one file repeats literally identical handler text (20 anchors, 47 sites); that residual count is per-anchor, not per-file, so it aggregates only sites that are the same text. The stale informational "total": 424 (the sites map actually summed to 411) is dropped rather than maintained.
  • Docstrings in manifest_models.py and the comment in layering.yaml state why anchors rather than counts.

Exactness proof

Script diffs what master's count baseline admits against what the committed anchor baseline admits, over the census at this head:

census sites at HEAD: 268 in 83 files (241 anchors)
refused by master's count baseline: none
refused by the anchor baseline:     none
ADDED admissions (site newly allowed): 0
DROPPED admissions (real site newly refused): 0
unusable ceiling headroom in master's baseline, not representable as an anchor: 143 across 58 files
RESULT: zero added, zero dropped
old = json.loads(git_show(f"master:{REF}"))                       # {"sites": {file: int}}
new_baseline = load_sqlite_degradation_baseline(root / REF)       # Counter[(file, digest)]
observed = census_sqlite_degradation_anchors(root, ("polylogue",))
obs_by_file = Counter()
for (f, _d), c in observed.items():
    obs_by_file[f] += c
admitted_before = {f: min(c, old["sites"].get(f, 0)) for f, c in obs_by_file.items()}
refused_before = {f: c - admitted_before[f] for f, c in obs_by_file.items() if c > admitted_before[f]}
refused_now = observed - new_baseline
assert not refused_before and not refused_now                     # zero added, zero dropped

devtools gate layering independently confirms it: "sqlite_degradation_shrunk":[] and count: 0, i.e. the anchor set is exactly the observed set.

No violation was pruned. What the conversion does not carry forward is 143 sites of unusable ceiling headroom across 58 files — entries whose integer exceeded the handlers actually present. Headroom is not a violation and has no source text to anchor; the count form already reported it as shrinkable debt. Its removal is strictly tightening, never loosening.

Verification

devtools gate layering        -> exit 0; count 0, sqlite_degradation_shrunk []
devtools gate patterns        -> exit 0
devtools verify --quick       -> exit 0 (all 15 gates ok)
devtools test tests/unit/devtools/test_sqlite_degradation_ratchet.py -> PASSED exit=0
devtools schema closure <each touched file> -> all six "out"

devtools schema closure on devtools/sqlite_degradation.py, devtools/verify_layering.py, devtools/manifest_models.py, tests/unit/devtools/test_sqlite_degradation_ratchet.py, docs/plans/layering.yaml, docs/plans/sqlite-degradation-baseline.json: every one reports out. No derived-schema identity moves; no reconvergence implied.

New test: test_two_disjoint_additions_to_one_file_are_both_reported builds the exact scenario above — two branches adding different handlers to one file — and asserts the merge reports two distinct sites, and that a baseline raised for branch A's site still refuses branch B's. test_an_unchanged_neighbour_edit_keeps_the_anchor asserts an anchor survives an unrelated edit to the same file.

Anti-vacuity, verified by mutation: reverting _sqlite_degradation_findings to the per-file count comparison (keeping the anchor census) turns the property test red:

>       assert [violation["rule"] for violation in merged] == [
            "sqlite_degradation_site_added",
            "sqlite_degradation_site_added",
        ]
E       AssertionError: assert ['sqlite_degr...n_site_added'] == ['sqlite_degr...n_site_added']
E         Right contains one more item: 'sqlite_degradation_site_added'
tests/unit/devtools/test_sqlite_degradation_ratchet.py:151: AssertionError

test_a_new_handler_fails_the_gate (KeyError: 'added') and test_a_converted_seam_is_reported_as_ratchet_headroom also go red under that mutation. devtools test reported FAILED exit=1 diagnosis=pytest_failed; the implementation was restored and re-verified green.

Residuals

  • 31 baseline files matched no census site at all and are dropped by the conversion — every entry they carried was headroom. They are follow-up material, listed here rather than investigated in a conversion PR: polylogue/archive/query/transaction.py, polylogue/cli/commands/demo.py, polylogue/cli/commands/embed.py, polylogue/cli/commands/maintenance/_migrate_tier.py, polylogue/cli/read_views/streaming_markdown.py, polylogue/context/preamble.py, polylogue/daemon/blob_gc_periodic.py, polylogue/daemon/embedding_backlog.py, polylogue/daemon/secret_scan_sweep.py, polylogue/demo/receipts.py, polylogue/maintenance/blob_disposition.py, polylogue/maintenance/blob_ref_liveness_reconciliation.py, polylogue/maintenance/corpus_fidelity.py, polylogue/maintenance/schema_inference_gate.py, polylogue/operations/durable_change_train.py, polylogue/operations/mutation_actuators.py, polylogue/security/secret_scan.py, polylogue/sources/revision_backfill.py, polylogue/sources/sqlite_snapshot.py, polylogue/storage/embeddings/generations.py, polylogue/storage/fts/drift_sampling.py, polylogue/storage/hook_payload_ref_reconciliation.py, polylogue/storage/search/runtime.py, polylogue/storage/search_providers/sqlite_vec_queries.py, polylogue/storage/sqlite/archive_tiers/schema_inventory.py, polylogue/storage/sqlite/archive_tiers/write.py, polylogue/storage/sqlite/archive_tiers/write_shard.py, polylogue/storage/sqlite/audit_leaf.py, polylogue/storage/sqlite/durable_change_train.py, polylogue/storage/sqlite/schema.py, polylogue/storage/sqlite/wal_checkpoint.py. Their handlers were converted or deleted at some point without the baseline being lowered — which the count form tolerated silently and the anchor form cannot.
  • 20 anchors carry count > 1 (47 sites): one file repeating byte-identical handler text. Two branches each adding the same text to the same file still sum on that anchor. This is the one residual case with the old shape, inherited from verify_patterns, and it is much narrower than per-file.
  • Digests are over normalized text, not semantics: reformatting a handler's body (not just its whitespace) moves its anchor and requires a baseline edit. That edit is visible in review, which is the point of the ratchet.
  • The baseline file grows from 121 to ~1000 lines. It is one line-range per anchor and sorted, so conflicts are local rather than a single shared integer.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

…ounts

The sqlite degradation baseline was a per-file integer ceiling. Per-file
counts are measured against whichever baseline a branch started from, so two
branches that each add one handler to the same file are both green against
the shared base and their merge sums past the ceiling: master goes red from
two separately green PRs, which has already cost this project a fix PR.

Convert the baseline and its verifier to the content-anchored form the repo
already implements in devtools/verify_patterns.py: a site is identified by
(file, sha1 of its normalized handler source) and new violations are a
Counter difference. Each branch's addition is then an anchor the shared
baseline does not contain, so each fails on its own, and raising the baseline
for one site never covers a different one.

The conversion is exact over the census at this head: 268 sites in 83 files,
zero newly admitted and zero newly refused. It deliberately admits no more
than the count form did; 143 sites of unusable ceiling headroom across 58
files have no anchor to carry and are reported for a follow-up rather than
pruned here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@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.

@Sinity Sinity changed the title fix: Anchor the sqlite degradation ratchet on content, not per-file counts fix: Anchor the sqlite degradation ratchet on content, not counts Sep 14, 2026
@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 31 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 489b308c-c726-4ec0-baac-923a702ca0b0

📥 Commits

Reviewing files that changed from the base of the PR and between 2b093b1 and 4614b8b.

📒 Files selected for processing (6)
  • devtools/manifest_models.py
  • devtools/sqlite_degradation.py
  • devtools/verify_layering.py
  • docs/plans/layering.yaml
  • docs/plans/sqlite-degradation-baseline.json
  • tests/unit/devtools/test_sqlite_degradation_ratchet.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 d568a01 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/sqlite-degradation-content-anchored branch September 14, 2026 16:50
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

`devtools gate patterns` reports one entry under `stale_matches`:

```
legacy-prose-logging polylogue/storage/raw_reconciler.py:85b335906ac0af77902886854638b6240bfe3049
```

`polylogue/storage/raw_reconciler.py` has **zero** current matches for
that rule — the prose logging it permitted is gone, but the baseline
still grants it. The ratchet therefore carries one unit of debt that
does not exist.

Found during security-finding triage, flagged as inherited from master
rather than introduced by that work.

## Solution

Delete the anchor. `gate patterns` now reports `stale_matches: []`.

This is a full prune, not a partial one. The distinction matters:
deleting an anchor whose matches have only *partly* disappeared would
turn the surviving matches into a new violation, because the anchor is
what permits them. That case wants a decremented count. Here the anchor
matches nothing at all, so the line goes.

## Verification

```
devtools gate patterns    → violations: 0, stale_matches: []
devtools verify --quick   → exit 0
```

## Residual

`polylogue-qai7u` tracks a larger instance of the same shape: 143 sites
of phantom headroom across 58 files in the sqlite-degradation baseline,
31 of which name files with no handler at all. That prune is separate
because it follows the count→content-anchor conversion in #5096.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Co-authored-by: Claude Opus 5 (1M context) <[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