Repository navigation
test(storage): pin blob-store + schema-policy invariants (#1185) - #1189
Conversation
Add two contract suites pinning the documented invariants from
docs/internals.md:
- tests/unit/storage/test_blob_store_contracts.py covers content-
addressing determinism (across all write methods + chunk
boundaries), prefix-shard layout (first hex byte = shard), the
iter_all walk's discipline against non-shard noise, write-once
semantics, dedup convergence, orphan-detection scoping, and the
GC concurrency model (DB-reference and lease predicates as
independent invariants, immediate-commit lease visibility,
generation tracking, link_group isolation in artifact_observations).
- tests/unit/storage/test_schema_policy_contracts.py covers the
fresh-first policy: SCHEMA_VERSION authority, fresh-init produces
the current version, matching version opens cleanly, future
versions are rejected, unknown older versions are rejected on
both sync and async paths, the read-only open path also rejects,
the bootstrap decision is explicitly version_mismatch, the
diagnostic message distinguishes newer from older, and fresh
init creates the canonical 6-trigger FTS set
(messages_fts_a{i,d,u}, action_events_fts_a{i,d,u}).
Each test cites the docs/internals.md section it pins in its
docstring so future doc/code drift is attributable.
Closes #1185
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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: 0e4ab52d8c
ℹ️ 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".
…1190) (#1318) ## Summary `run_blob_gc` now unlinks the correct sharded blob path (`{root}/{prefix}/{remainder}`), increments `deleted` only when an `unlink` actually removed a file, persists per-pass structured evidence into a new `gc_generations.evidence` column, supports `dry_run=True`, and exposes the evidence through a `polylogue maintenance gc-history` operator surface. ## Problem The previous implementation called `(blob_path / blob_hash).unlink(missing_ok=True)` — i.e. it targeted `{blob_dir}/{full_hash}`. Blobs live at the sharded path `{blob_dir}/{prefix}/{remainder}` (see `BlobStore.blob_path`), so the flat path never exists for a real blob. `missing_ok=True` silently swallowed the `ENOENT` and the `deleted` counter bumped anyway, so: - GC reports lied about reclamation. - Orphan blobs were never actually removed. - There was no audit trail beyond a row-count of completed generations. This was observed during PR #1189 implementation and tracked in #1190. ## Solution `polylogue/storage/blob_gc.py`: - Added `_sharded_blob_path(blob_root, blob_hash)` mirroring `BlobStore.blob_path` and use it as the unlink target. - Switched from `unlink(missing_ok=True)` to explicit `unlink()` with `FileNotFoundError` handling: missing files now bump `skipped_missing` instead of `deleted`. - Split `PermissionError`/`OSError` failures into a separate `skipped_unlink_error` counter; the `deleted` counter only bumps on a successful `unlink()` call. - Added a `GCRunEvidence` dataclass capturing inspected, deleted, per-reason skip counts (`skipped_referenced`, `skipped_leased`, `skipped_missing`, `skipped_unlink_error`), `dry_run`, `max_batch`, `previous_generation`, and the list of `deleted_hashes`. Serialised as sorted JSON. - Added `dry_run: bool = False` kwarg: counts would-be deletions on disk-present candidates, touches no file, and does NOT write a `gc_generations` row (no generation slot consumed by previews). - Added `read_gc_history(db_path, limit)` returning parsed history rows newest-first; pre-#1190 rows surface with `evidence=None` so they remain visible to operators. `polylogue/storage/sqlite/schema_ddl_archive.py` / `polylogue/storage/sqlite/schema_ddl.py`: - Added `evidence TEXT` column to `gc_generations`. - Bumped `SCHEMA_VERSION` 1 → 2. Per the no-migration-chain policy this is a deletes-then-defines edit: a mismatched DB triggers re-ingest (`polylogue reset --database && polylogued run`), no upgrade helper is added. The added column is nullable so existing in-place generations slot in cleanly under the new schema. `polylogue/cli/commands/maintenance.py`: - Added `polylogue maintenance gc-history` subcommand with `--limit` and `--output-format {plain,json}`. Reads `gc_generations.evidence` via `read_gc_history`; plain output shows generation, completion time, and the per-reason skip tallies. Tests: - `tests/unit/storage/test_blob_gc.py`: - `test_run_blob_gc_unlinks_sharded_path_and_increments_counter` plants an orphan via `BlobStore.write_from_bytes` (sharded path), backdates its mtime past `MIN_AGE_S`, runs GC, asserts the sharded file is gone AND counter == 1. - `test_run_blob_gc_does_not_increment_when_file_already_missing` patches `_candidate_blobs` to report a hash whose file was already removed; counter stays 0 and evidence records `skipped_missing >= 1`. - `test_run_blob_gc_dry_run_does_not_delete_or_record_generation` asserts dry-run preserves disk and consumes no generation slot. - `test_run_blob_gc_records_structured_evidence` validates the JSON shape, the deleted-hash list, and `skipped_referenced` accounting. - `test_read_gc_history_returns_recent_passes_newest_first` runs three GC passes and asserts newest-first ordering. - `tests/unit/storage/test_blob_gc_concurrency.py`, `tests/unit/storage/test_blob_store_contracts.py`: schema fixtures updated to include the new `evidence` column; the threaded acquire/commit/GC test gained a pre-thread sentinel lease — the prior code's no-op unlink masked a real startup race between thread spawn and the writer's first `acquire_blob_leases` call. Alternatives rejected: - Keeping `missing_ok=True` and post-hoc checking `target.exists()` before/after would still race with concurrent reclaimers. Using the `unlink()` return-status idiom (FileNotFoundError ⇒ no-op) is atomic and matches POSIX semantics directly. - Storing evidence in a sibling table was discarded as additional schema surface for no benefit; the evidence row is 1:1 with the generation and the JSON shape evolves more cheaply than columns. ## Verification ``` devtools verify --quick # exit_code: 0 pytest tests/unit/storage/test_blob_gc.py \ tests/unit/storage/test_blob_gc_concurrency.py \ tests/unit/storage/test_blob_store_contracts.py # 46 passed in 8.61s ``` Pre-existing CLI status test failures (`test_status_first_run_hint*`, `test_status_subprocess_no_archive`) reproduce on master without these changes — they read the host operator's 48.9 GB live archive instead of an isolated tmp workspace, unrelated to GC. Closes #1190
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Add two contract suites that pin the documented invariants of the blob store and the schema-version policy from
docs/internals.md, distinct from the happy-path CRUD coverage intest_blob_store.py/test_blob_gc.py/test_schema_upgrades.py.Problem
#997's closeout flagged the blob store and the schema-migration policy among uncovered domains. Existing storage tests cover specific behaviors (write paths, individual upgrade plans, GC regression bugs) but do not pin the documented invariants themselves. A refactor or accidental drift could change the contract without any test failing.
Solution
Two new test files, each docstring-citing the
docs/internals.mdsection it pins:tests/unit/storage/test_blob_store_contracts.py(16 tests, including a 6-variant parametrize) pins § "Blob Store Model" and § "GC concurrency model — leases plus snapshot reference check":write_from_bytes/write_from_fileobj/write_from_pathand across empty / single-byte / ASCII / multibyte UTF-8 / binary / multi-MiB chunked payloads.{root}/{hash[:2]}/{hash[2:]}, with the full 256-shard hex namespace permitted and non-shard noise (wrong-length dirs, scratch dirs) ignored byiter_all.acquire_blob_leasesare visible to fresh reader connections immediately (the immediate-commit contract the docs make explicit), generation rows are recorded on each GC cycle that has candidates, and a leased in-flight blob survives GC even when the snapshot reference check says "orphan".link_group_keyisolation onartifact_observations— the docs' "blob_links" vocabulary describes this same grouping table; group-A queries must not surface group-B rows, and null-group rows are not surfaced by either.tests/unit/storage/test_schema_policy_contracts.py(9 tests) pins § "Schema Versioning Model" and the canonical FTS trigger set from § "Daemon Convergence Evidence":SCHEMA_VERSIONexactly.SCHEMA_VERSION + 1(future) is rejected on the sync path.assert_readable_archive_layout) also rejects.decide_schema_bootstrapreturnsversion_mismatchaction for unknown versions — pins the policy decision, not just the side effect.messages_fts_a{i,d,u},action_events_fts_a{i,d,u}). A missing trigger is documented as an FTS index drift risk.Each test's docstring cites the specific
docs/internals.mdsection it pins so future doc/code drift is attributable.Verification
Closes #1185