Repository navigation
feat(devtools): content-anchored pattern baselines - #4199
Conversation
…seline-anchors # Conflicts: # devtools/patterns/baselines/exclusive-create-write.txt # devtools/patterns/baselines/sqlite-error-default.txt
|
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f424a284b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
) ## 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 ``` ```python 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.com/claude-code) https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…#5802) ## Summary Salvages ChatGPT fleet worker 15 (Codex review debt, beads polylogue-1tyq5.45, .47, .48, .51, .52: devtools parts 4/6/7, docs, nix). Of 79 findings: 13 fixed here, 56 already fixed on master, 4 stale, 6 not reached. The worker's patch was built on snapshot `e1510b53ea`, not master. It was ported hunk by hunk onto current master, keeping the newer OOM attribution and trusted-parent work in `verify.py`, `verify_runs.py`, `run_tests.py` and `pytest_slot.py`. ## Problem - `devtools test --outliers` globbed `last-pytest-*.json` shards. No verifier writes these any more: each pytest step's report is rebound into its run step directory, and only `last-pytest.json` is projected. The command therefore read nothing or stale files (45.01, 45.02). - A focused `devtools test` that got SIGTERM died in `subprocess.run`. It wrote no terminal receipt, history or evidence (45.06). - Queued slot interruptions dropped the start-time worktree provenance (45.08). - When a selected directory was missing, pytest exited 4 (usage error). The missing-path diagnostic only ran on exit 5 (45.10). - The focused verdict printed a checkout-relative receipt path. `main()` has `chdir`ed to ROOT, so the path did not resolve from the caller's directory (45.12). - `canonical_verification_receipt` preferred `final_git_head`. It attributed passing tests to a head that moved under the run and was never executed (45.14). - The verifier's interruption handlers did not cover selection, admission or verdict assembly. A signal there left the run `running` (47.03). - A refused affected plan returned before any static gate ran (47.21). - The Home Manager readiness lane required the removed role-ladder expressions. It rejected the intact module and could not detect a dropped capability switch (47.22). - Pattern help and docs advertised `path:sha1[:count]`, but the parser requires `path:sha1:context_sha1[:count]` (48.01). The SHA-1 anchors used the security-default constructor (48.03). - Reconciliation retried publication only for abandoned runs adopted as failure. A run adopted as success whose first publication was interrupted never reached history (48.20). ## Solution - `print_outliers` selects every pytest lane of the newest completed `--all` receipt (tier `all`, status `success`, `complete_corpus_covered`). It refuses when a lane report is missing. The shard glob, its constant and the verifier's `_clear_full_run_shards` are removed. - `devtools test` installs a SIGTERM handler around the launch. The slot's own handler chains into it after it stops the child. The run finishes with exit 143 and `termination_reason=sigterm`, and the prior handler is restored. - Both slot interruption writers pass the captured `worktree_provenance`. - The missing-path diagnostic runs on exit 4 and exit 5. The "every path exists" hint stays exit-5 only. - Receipt and artifact paths print absolute. - `source_revision` is set only when the ending head equals the executed head. It is also unset when the tree is unknown or dirty. - `_main` runs selection, admission, steps and verdict assembly inside the interruption handlers. Publication (`_finish_and_record_verification`) stays outside so a signal cannot finish a run twice. A refused plan now runs the quick gates through the same path, keeps the first failing gate's exit and diagnosis, and otherwise returns exit 2 with `affected_admission_refused`. - The HM lane checks the three `cfg.mcpEnable*` mappings. - The pattern gate hashes with `usedforsecurity=False`. The help, catalog, regenerated `docs/devtools.md` and `docs/structured-logging.md` name the context-anchor format. - Reconciliation retries publication for abandoned runs adopted as success too. The existing per-run dedup keeps it idempotent. Diverges from the worker: its 47.03 change put publication inside the handler. That could append a second history row for a run already finished. Publication is kept outside, and crash-consistent publication stays with 47.12 (not reached). Its 47.25 change is dropped because master already rejects malformed registries more strictly. ## Verification All through AgentCTL on the pushed head's tree or its immediate predecessor: - `agentctl job start polylogue verify_quick --workspace /realm/worktrees/salvage-w15 --wait`: job 2319 on `75059a9ddc` (rebased head): `verify: PASSED exit=0`. - `agentctl job start polylogue pytest_focused --workspace /realm/worktrees/salvage-w15 --wait -- tests/unit/devtools/test_verification_terminal_receipts.py tests/unit/devtools/test_verify.py tests/unit/devtools/test_run_tests.py tests/unit/devtools/test_verify_patterns.py tests/unit/devtools/test_agent_integration_module.py tests/unit/devtools/test_verify_runs.py tests/unit/devtools/test_verification_evidence_lane.py tests/unit/devtools/test_pytest_slot.py`: job 2300 on `4e72110e57`: `2 failed`, both inherited (see residuals); everything else passed. - After the mypy typing commit: job 2312, `pytest_focused -- tests/unit/devtools/test_verification_terminal_receipts.py tests/unit/devtools/test_verify_patterns.py tests/unit/devtools/test_run_tests.py`: `devtools test: PASSED exit=0`. - Red on master: job 2242 ran the new and changed tests in a detached master worktree (`e14b47662d`) with production code unchanged. Every new regression failed: 13 in `test_verification_terminal_receipts.py`, the sha1 pattern test, the HM lane pass case, both `test_affected_admission_refuses_without_launching_pytest` params and the adapted outliers test. The `ending == executed head` canonical parameter passed there as expected. The same job reproduced the two inherited failures. - Derived-identity closure: scratch job 2202 ran `python -m devtools schema closure` on all 8 changed production files, and every one reported `out`. The same job regenerated `docs/devtools.md` with `devtools render devtools-reference`. ## Self-review - **Sibling sites.** The artifacts line got the same absolute-path fix as the receipt (45.12). `docs/structured-logging.md` carried the same stale anchor spelling (48.01). Both slot interruption writers are fixed (45.08). The verifier's shard clearing was the other half of the dead shard protocol and is removed with the reader. - **Cancellation and shutdown.** The focused SIGTERM handler is installed after the temp-tree guard and restored in `finally`. The held slot's handler restores it and re-signals, so the two chain. Verifier publication is outside the handler, which avoids double finishing. - **Unbounded reads.** The outliers reader globs `runs/*/run.json`, which retention already bounds (8 successful runs). - **Fail-open fallbacks.** Outliers refuse on a missing or malformed lane rather than fall back to older reports. An unknown ending head yields no `source_revision`. - **Compatibility shims.** None. The shard constant and clearing are deleted, not kept alongside. - **Removed symbols.** `PYTEST_PARALLEL_REPORT_PATTERN` and `_clear_full_run_shards` have no remaining references in code, tests or docs. - **Production route.** The tests drive `run_tests.main`, `verify.main`, `pytest_slot._run_launch`, `reconcile_and_record_abandoned_verify_runs`, `verify_patterns.main` and the real lane function. Only host observations (Git, processes, signals) are replaced. ## Findings | key | disposition | evidence | test | |---|---|---|---| | 45.01 #4162 run_tests.py:116 | fixed | shards unwritten since per-step report binding (`verify._bind_pytest_reports_to_step`) | test_verification_terminal_receipts.py::test_outliers_read_all_lanes_of_one_completed_receipt, ::test_outliers_refuse_a_missing_lane_instead_of_falling_back_to_older_reports | | 45.02 #4162 run_tests.py:116 | fixed (same change; worker had fixed-already via shard clearing, which cleared names nobody writes) | receipt-bound selection | ::test_outliers_read_all_lanes_of_one_completed_receipt | | 45.06 #4267 run_tests.py:352 | fixed | no SIGTERM handling on master | ::test_focused_sigterm_finishes_receipt_and_publications | | 45.08 #5544 run_tests.py:427 | fixed | `_write_interrupted_result` lacked provenance | ::test_queued_interruption_keeps_start_time_worktree_provenance | | 45.10 #4343 run_tests.py:485 | fixed | `if rc == 5` only | ::test_focused_missing_directory_has_a_path_specific_usage_diagnostic | | 45.12 #4726 run_tests.py:626 | fixed | `run.relative_run_dir` printed | ::test_focused_verdict_receipt_is_absolute_from_a_nested_invocation | | 45.14 #5544 run_tests.py:649 | fixed | `final_git_head or git_head` | ::test_canonical_receipt_never_attributes_an_untested_ending_head | | 47.03 #4109 verify.py:505 | fixed (publication kept outside; see 47.12) | selection/tail outside `try` | ::test_verifier_finalizes_interruptions_outside_the_step_loop | | 47.21 #4898 verify.py:1019 | fixed | early `return 2` before `build_verify_steps` | ::test_refused_affected_admission_still_executes_static_gates; test_verify.py::test_affected_admission_refuses_without_launching_pytest | | 47.22 #4266 verify_agent_integration.py:472 | fixed | role-ladder tokens absent from module | test_agent_integration_module.py::test_home_manager_lane_checks_independent_capability_switches | | 47.25 #4161 verify_patterns.py:37 | fixed-already (worker claimed fixed) | `_rules` raises on every malformed shape, verify_patterns.py:36-63; test_verify_patterns.py::test_malformed_pattern_registry_fails_closed | none | | 48.01 #4199 verify_patterns.py:59 | fixed | help said `path:sha1[:count]` | generated reference refreshed | | 48.03 #4199 verify_patterns.py:113 | fixed | default-security `hashlib.sha1` | test_verify_patterns.py::test_pattern_entrypoint_marks_sha1_as_non_security_use | | 48.20 #5299 verify_runs.py:1282 | fixed | retry branch matched `status == "failed"` only | ::test_successful_abandoned_adoption_retries_an_interrupted_publication | | 45.22, 45.25, 47.12, 48.05, 48.06, 48.17 | not reached | still open; need design (receipt-bound config, resumable GC, crash-consistent publication, stale-baseline policy, located violations, unknown duration) | none | | 47.08, 47.10, 47.15, 47.20 | stale | code paths removed (`--recompute`/`--commit`, bootstrap selection, parent-root refusal, graph publication) | none | | remaining 55 | fixed-already | worker's line evidence, spot-checked on current master | none | ## Derived-identity closure None. All 8 changed production files are outside the closure (`devtools schema closure`, job 2202). ## Residuals - These two failures reproduce on master `e14b47662d` (job 2242) and are unrelated to this change: - `tests/unit/devtools/test_verification_evidence_lane.py::test_reconciled_abandoned_run_joins_the_durable_lane`: the relocated-cache evidence target conflicts with the test's durable-lane expectation. - `tests/unit/devtools/test_verify.py::test_zero_exit_without_a_report_is_a_failed_pytest_step`: pytest-benchmark options are unrecognized in the free-threaded venv. - A signal that arrives during publication itself still escapes. That is 47.12. - Abandoned runs with no recorded ending head now publish no `source_revision`. This is intended: the head was never observed at the end. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
Pattern-gate baselines move from
path:linetopath:sha1(normalized-first-match-line)with multiset count suffixes for duplicates. Line displacement — the source of 7 merge conflicts and ~8 manual baseline rebases in one night — no longer invalidates entries; stale/new become pure set operations. All 124 existing match instances preserved in the one-shot migration; shrink-only ratchet semantics unchanged. Also removes a stray.quick.logthat reached master through a conflict-resolutiongit add -A(#4184).Verification
7 focused verify_patterns tests (incl. new displacement + multiset anti-vacuity),
devtools verify patterns, quick gate, oracle-integrity — all green, re-run after merging current master over the migrated format.🤖 Generated with Claude Code
https://claude.ai/code/session_014BQsaB1NBY8mTR6yZByfMA