Repository navigation
fix(storage): bring blob orphan cleanup and integrity verification to honest closure (#818) - #1002
Conversation
📝 WalkthroughWalkthroughThis PR adds comprehensive test coverage for blob orphan detection, cleanup, and maintenance routing across three test modules: integration tests for round-trip lifecycle and handler wiring, property-based tests validating BlobStore invariants, and updated unit test expectations for mock return values. ChangesBlob Orphan Lifecycle Testing
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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: 4d1b778020
ℹ️ 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".
) Strengthens the existing operator-visible blob check output assertion so a future refactor that drops the bytes total or the sample-hash listing fails loud. Without this, the check could degrade to "Orphaned: 1" with no operator context and the unit test would still pass. Ref #818-A4 — orphan detection wired into operator-visible surface. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…#818) Adds two protective layers around the blob orphan/integrity contract that unit tests cover only by example. tests/integration/test_blob_lifecycle_e2e.py exercises the full operator loop against a real BlobStore and SQLite — write referenced + orphan blobs, detect, dry-run, apply, re-detect, verify_all — through both the direct BlobStore API and the maintenance-target handler (repair_orphaned_blobs). This pins the wire-up between paths/_roots, blob_store, and storage/repair so a silent disconnect in any layer fails loud. Includes a TOCTOU regression covering concurrent ingest racing against a cleanup pass. tests/property/test_blob_store_props.py asserts that detect_orphans samples are always bounded by max_sample, that orphan counts and bytes match the on-disk-minus-DB set exactly, and that dry-run cleanup never deletes regardless of input shape. Ref #818-A1, #818-A2, #818-A6, #818-A9. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adversarial review of the original closure flagged 818-A6 as
unverified: the maintenance handler was tested in isolation, but the
dispatch path that actually runs in production —
``MaintenanceTargetCatalog.resolve_name("orphaned_blobs")`` →
``_REPAIR_HANDLERS["orphaned_blobs"]`` → handler call — had no
test. A regression that drops the spec, drops the handler dict
entry, or forgets the destructive flag would have shipped silently.
Adds a TestOrphanedBlobsCatalogRouting class with three tests:
1. Catalog spec lookup returns the correct mode/category/destructive
flag.
2. Both _REPAIR_HANDLERS and _PREVIEW_HANDLERS dispatch the
orphaned_blobs name to the right callables.
3. End-to-end: catalog → handler dict → real archive cleanup.
Ref #818-A6.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adversarial review iteration 2 noticed three test mocks for ``OrphanDetectionResult`` carry a ``scanned_count`` attribute that doesn't exist on the real dataclass. SimpleNamespace accepts arbitrary fields and the production code path doesn't read it, so the mocks have been silently noisy rather than wrong. Cleaning up so the test reflects the real shape. Ref #818-A4. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
86f85e1 to
0edee7c
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/integration/test_blob_lifecycle_e2e.py`:
- Around line 33-45: Replace the direct SQL INSERT in _seed_raw_row with the
project test-record builders: use ConversationBuilder (from
tests/infra/storage_records.py) or the make_conversation()/make_message()
helpers to create and persist a raw_conversations row with the same values
(raw_id, provider_name="test", source_path, blob_size, acquired_at); remove the
sqlite3.execute INSERT and call the builder/factory method that writes into the
test DB (ensuring you pass/commit to the same db_path connection) so the test
uses the standard fluent builders instead of raw SQL.
In `@tests/property/test_blob_store_props.py`:
- Around line 49-60: The test
test_detect_orphans_count_and_bytes_match_disk_minus_db currently creates an
ad-hoc tempdir with tempfile.TemporaryDirectory(), bypassing the shared
workspace_env fixture; update the test (and the similar block at lines 98-108)
to accept and use the workspace_env fixture instead of creating a tempfile root,
and construct the store via the provided workspace_env (e.g. use
workspace_env.archive_root or workspace_env.tmp_dir as the Path passed into
_store) so XDG/archive paths are isolated consistently; ensure the test
signature includes workspace_env and remove the tempfile
import/TemporaryDirectory usage.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 4504e079-b975-4bc5-b2fc-6d62c4f47bf8
📒 Files selected for processing (3)
tests/integration/test_blob_lifecycle_e2e.pytests/property/test_blob_store_props.pytests/unit/cli/test_check_support_runtime.py
| def _seed_raw_row(db_path: Path, raw_id: str, source_path: Path, blob_size: int) -> None: | ||
| """Insert a minimum-viable raw_conversations row pointing at *raw_id*.""" | ||
| with sqlite3.connect(db_path) as conn: | ||
| conn.execute( | ||
| """ | ||
| INSERT INTO raw_conversations ( | ||
| raw_id, provider_name, source_path, blob_size, acquired_at | ||
| ) VALUES (?, ?, ?, ?, ?) | ||
| """, | ||
| (raw_id, "test", str(source_path), blob_size, "2026-05-10T00:00:00Z"), | ||
| ) | ||
| conn.commit() | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Replace manual raw_conversations inserts with test record builders.
Direct SQL seeding here bypasses the project’s storage-record test utilities and increases schema-coupling brittleness. Please seed with ConversationBuilder (or make_conversation()/make_message() where appropriate) instead of handwritten INSERTs.
As per coding guidelines, tests/**/*.py: Use ConversationBuilder from tests/infra/storage_records.py for populating test databases with a fluent builder pattern. Use make_message() and make_conversation() from tests/infra/storage_records.py for quick factories creating model instances without database setup.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/integration/test_blob_lifecycle_e2e.py` around lines 33 - 45, Replace
the direct SQL INSERT in _seed_raw_row with the project test-record builders:
use ConversationBuilder (from tests/infra/storage_records.py) or the
make_conversation()/make_message() helpers to create and persist a
raw_conversations row with the same values (raw_id, provider_name="test",
source_path, blob_size, acquired_at); remove the sqlite3.execute INSERT and call
the builder/factory method that writes into the test DB (ensuring you
pass/commit to the same db_path connection) so the test uses the standard fluent
builders instead of raw SQL.
| def test_detect_orphans_count_and_bytes_match_disk_minus_db( | ||
| tmp_path_factory: object, referenced: int, orphans: int, max_sample: int | ||
| ) -> None: | ||
| """For any (referenced, orphan) split, detect_orphans returns the right | ||
| count and a bounded sample. | ||
| """ | ||
| # Hypothesis runs many examples — give each its own tmp path so blobs | ||
| # don't collide across runs. | ||
| import tempfile | ||
|
|
||
| with tempfile.TemporaryDirectory() as tmpdir: | ||
| store = _store(Path(tmpdir)) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Use workspace_env instead of ad-hoc tempfile roots for storage property tests.
These tests exercise real storage behavior but bypass the shared isolation fixture policy. Please switch to workspace_env so archive/XDG paths are consistently isolated the same way as the rest of storage tests.
As per coding guidelines, tests/**/*.py: Use workspace_env fixture for tests that touch storage or pipeline. It provides isolated XDG paths and archive root in tmp_path.
Also applies to: 98-108
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/property/test_blob_store_props.py` around lines 49 - 60, The test
test_detect_orphans_count_and_bytes_match_disk_minus_db currently creates an
ad-hoc tempdir with tempfile.TemporaryDirectory(), bypassing the shared
workspace_env fixture; update the test (and the similar block at lines 98-108)
to accept and use the workspace_env fixture instead of creating a tempfile root,
and construct the store via the provided workspace_env (e.g. use
workspace_env.archive_root or workspace_env.tmp_dir as the Path passed into
_store) so XDG/archive paths are isolated consistently; ensure the test
signature includes workspace_env and remove the tempfile
import/TemporaryDirectory usage.
|
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
Brings #818 (blob orphan cleanup and integrity verification) to actual closure by adding the test layers that pin the contract end-to-end. The implementation surface (
BlobStore.detect_orphans/cleanup_orphans/verify_all,repair_orphaned_blobshandler,orphaned_blobsmaintenance target, daemon-side health integration) was already complete on master — what was missing was an integration test that fails loud if any layer disconnects, plus property coverage for the bounded-orphan invariant, plus a tighter assertion on the operator-visible orphan output, plus catalog-routing tests added during adversarial review.Closes #818.
Depends on #1001 (verify baseline restoration) — merge that first; this branch rebases on it.
Problem
#818 was reopened during the 2026-05-09 closed-issue audit because the close-out language ("core implementation landed; remaining edges are incremental") matched the abandonment pattern flagged in
feedback_close_discipline.md. The audit confirmed: implementation existed, but the test surface only covered unit-level slices — there was no end-to-end test pinning the contract operators rely on (polylogue checkorphan output,polylogue doctor --repair --target orphaned_blobsround-trip), nor a property test for the bounded-output invariant ondetect_orphans. Any regression in any one wiring layer (paths, blob_store, repair, maintenance) could land silently.Solution
Acceptance criteria matrix
detect_orphansreturns count, bytes, sample; bounded output independent of Ntests/property/test_blob_store_props.pyasserts samples bounded bymax_sampleand counts/bytes match the disk-minus-DB set across hypothesis-generated (0–80 orphans, 1–20 max_sample) parameter spacecleanup_orphans(dry_run=True)default opt-in safetyverify_all(max_failures)re-hashes blobs, no DBpolylogue checkoperator outputcli/shared/check_workflow.py:142; tightened assertion intests/unit/cli/test_check_support_runtime.py:191to require"Orphaned: 1 blobs (4,096 bytes)"exact string + sample linepolylogue check --deeprunsverify_allcheck_workflow.py:147; rendered indocs/cli-reference.md(regenerated in #1001)orphaned_blobsmaintenance target wired through catalog → handler dict → handlermaintenance/targets.py:237,repair.py:671/1144/1157); new e2e tests inTestRepairOrphanedBlobsHandler+TestOrphanedBlobsCatalogRoutingexercise both the handler in isolation AND the catalog→handler dispatch path1bd2f156GC bug fixestests/unit/storage/test_blob_gc.pycovers bothverify_alldaemon/health.py:639usesmax_failures=5tests/integration/test_blob_lifecycle_e2e.pypending_blob_refs,gc_generationsretain/remove decisionblob_gc.py(lease acquire/release, generation tracking); the actual question is whether the lease-based GC design is still current vs. snapshot-basedrepair_orphaned_blobs. Separate architectural review.Files changed
tests/integration/test_blob_lifecycle_e2e.py(NEW; 7 tests across 3 classes; ~280 LoC)tests/property/test_blob_store_props.py(NEW; 2 hypothesis tests; ~120 LoC)tests/unit/cli/test_check_support_runtime.py(tightened orphan-output assertion; +5/-7 lines net after mock cleanup)No production code changes — implementation was already complete; this PR is purely additive test coverage that pins the closure.
Verification
Adversarial review notes
The plan called for an adversarial subagent loop iterating until no legitimate gaps remained, capped at 5 iterations. The loop converged at iteration 3.
Iteration 1 — found one real gap (818-A6: catalog routing tested only at handler level, not through
MaintenanceTargetCatalog.resolve_name→_REPAIR_HANDLERS[name]dispatch path) and one borderline (818-A1 scale). Fixed in commit4a96e6e8by addingTestOrphanedBlobsCatalogRoutingwith three tests covering spec resolution (mode/category/destructive flag), handler-dict entries (both_REPAIR_HANDLERSand_PREVIEW_HANDLERS), and end-to-end catalog→handler→archive cleanup.Iteration 2 — found one borderline (mock field
scanned_countdoesn't exist on realOrphanDetectionResult) and one borderline (TOCTOU test scope clarity). Fixed mock field cleanup in commit86f85e15. TOCTOU test docstring already explains scope; the "blob re-referenced before cleanup" path is caller-orchestration, not aBlobStorecontract. Iteration 2 also flagged that the bounded-memory property test asserts output bound but not intermediate memory bound — dismissed because the implementation inblob_store.py:367-385is structurally streaming (3 counters + a bounded list ofmax_sample), and the test assertsorphan_count/orphan_bytesare correct independent of N, which structurally requires the function to not buffer all of N. An instrumented memory-watcher would be gold-plating against the same structural guarantee.Iteration 3 — independent review: "No legitimate gaps found across all 11 ACs after iteration 3 review." Confirmed all assertions catch their regressions, all commit messages reference specific ACs without hedging language, #1000 exists with real scope.
Loop exited clean. Total: 4 #818 commits (3 substantive + 1 mock cleanup), 3 adversarial iterations, 1 documented dismissal.
🤖 Generated with Claude Code
Summary by CodeRabbit