Repository navigation
fix(storage): add blob orphan detection, cleanup, and integrity verification (#818) - #879
Conversation
…ication (#818) Add three new BlobStore methods with bounded output and dry-run safety: - verify_all(): batch content-hash verification (filesystem-only) - detect_orphans(): mark-and-sweep orphan counting with byte totals - cleanup_orphans(): bulk orphan deletion with dry_run=True default Wire blob integrity into polylogue doctor --blob (now with --deep for full re-hash verification) and register orphaned_blobs as a destructive cleanup maintenance target under --cleanup --deep. Add 51 tests: round-trip, dedup, single/blob verify, verify_all (empty, all-pass, hash-mismatch, max-failures), orphan detection (no orphans, some orphans, all orphans, max_sample), cleanup (dry-run reporting, apply deletion, invalid hash errors), plus regression tests for fixed GC bugs (_still_referenced checks raw_conversations.raw_id, _candidate_blobs walks all 256 prefix directories). Closes #818 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
📝 WalkthroughWalkthroughThis PR adds orphan blob detection, cleanup, and integrity verification to the storage layer. It introduces new BlobStore methods ( ChangesBlob Orphan Detection and Cleanup
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
✨ 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.
Pull request overview
Adds blob-store integrity verification, orphan detection/cleanup, and wires these capabilities into doctor --blob and the maintenance target registry to support safer operational maintenance of on-disk blobs.
Changes:
- Extend
BlobStorewithverify_all(),detect_orphans(), andcleanup_orphans()plus typed result dataclasses. - Wire blob orphan stats + optional deep integrity re-hashing into the
doctor --blobcheck workflow, and registerorphaned_blobsas a destructive cleanup target. - Add/expand unit tests and update CLI/docs/catalog artifacts to reflect the new maintenance target and behaviors.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
polylogue/storage/blob_store.py |
Adds batch integrity verification, orphan detection, and cleanup APIs with result dataclasses. |
polylogue/cli/shared/check_workflow.py |
Updates doctor --blob path to report orphan byte totals and optionally run deep integrity checks. |
polylogue/storage/repair.py |
Adds orphaned blob debt counting and repair/preview handlers for the new maintenance target. |
polylogue/maintenance/targets.py |
Registers orphaned_blobs as a destructive CLEANUP maintenance target requiring --deep. |
tests/unit/storage/test_blob_store.py |
Adds extensive unit coverage for new blob-store behaviors and invariants. |
tests/unit/storage/test_blob_gc.py |
Adds regression tests for previously fixed GC bugs and some light integration checks. |
docs/cli-reference.md |
Documents the new orphaned_blobs maintenance target in CLI reference output. |
docs/verification-catalog.md |
Updates generated catalog counts for the new maintenance target/obligations. |
docs/test-quality-workflows.md |
Updates workflow registry snapshot to include orphaned_blobs as uncovered. |
docs/plans/file-size-budgets.yaml |
Adjusts file-size budget exception for polylogue/storage/repair.py. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Missing: DB references without disk blobs | ||
| disk_hashes = set(blob_store.iter_all()) | ||
| missing = sorted(db_raw_ids - disk_hashes) | ||
| orphaned = sorted(disk_hashes - db_raw_ids) | ||
|
|
||
| # Orphans: disk blobs without DB references (with byte totals) | ||
| orphan_result = blob_store.detect_orphans(db_raw_ids) | ||
|
|
| orphan_hashes = set(detect_result.orphan_samples) | ||
| # For the real cleanup we need all orphans, not just the sample. | ||
| # Re-walk to build the full set. | ||
| if not dry_run: | ||
| orphan_hashes = {h for h in blob_store.iter_all() if h not in db_raw_ids} | ||
|
|
||
| cleanup_result = blob_store.cleanup_orphans(orphan_hashes, dry_run=dry_run) | ||
|
|
||
| if dry_run: | ||
| return _repair_result( | ||
| "orphaned_blobs", | ||
| repaired_count=cleanup_result.would_delete_count, | ||
| success=True, | ||
| detail=( | ||
| f"Would: delete {cleanup_result.would_delete_count} orphaned blobs " | ||
| f"({cleanup_result.would_delete_bytes:,} bytes)" | ||
| ), | ||
| ) |
| # Verify blobs are spread across multiple prefix dirs | ||
| prefix_dirs = {h[:2] for h in hashes} | ||
| assert len(prefix_dirs) >= 1 # At least one prefix dir | ||
|
|
||
| candidates = _candidate_blobs(blob_root, older_than=0) | ||
| found_hashes = {h for h, _ in candidates} | ||
| assert found_hashes == hashes, f"Candidate walk missed blobs: expected {hashes}, got {found_hashes}" |
| def verify_all( | ||
| self, | ||
| *, | ||
| max_failures: int = 10, | ||
| heartbeat: Heartbeat | None = None, | ||
| ) -> BlobVerifyAllResult: | ||
| """Re-hash every blob on disk and verify content integrity. | ||
|
|
||
| Reads and hashes each blob in 1 MiB chunks. Stops after | ||
| *max_failures* failures to keep output bounded. Returns a | ||
| summary with count, bytes checked, and failure details. | ||
|
|
||
| This is intentionally a filesystem-only integrity check — it | ||
| does not consult the database. That keeps it usable even when | ||
| the database is unavailable or corrupted. | ||
| """ | ||
| checked = 0 | ||
| checked_bytes = 0 | ||
| failures: list[BlobVerifyFailure] = [] | ||
|
|
||
| for hash_hex in self.iter_all(): | ||
| checked += 1 | ||
| path = self.blob_path(hash_hex) | ||
| try: | ||
| file_size = path.stat().st_size | ||
| checked_bytes += file_size | ||
| except OSError: | ||
| failures.append(BlobVerifyFailure(hash=hash_hex, reason="stat_failed")) | ||
| if len(failures) >= max_failures: | ||
| break | ||
| continue | ||
|
|
||
| hasher = hashlib.sha256() | ||
| try: | ||
| with builtins_open(path, "rb") as f: | ||
| while True: | ||
| chunk = f.read(_CHUNK_SIZE) | ||
| if not chunk: | ||
| break | ||
| hasher.update(chunk) | ||
| except OSError as exc: | ||
| failures.append(BlobVerifyFailure(hash=hash_hex, reason="read_error", detail=str(exc))) | ||
| if len(failures) >= max_failures: | ||
| break | ||
| continue | ||
|
|
||
| actual = hasher.hexdigest() | ||
| if actual != hash_hex: | ||
| failures.append( | ||
| BlobVerifyFailure( | ||
| hash=hash_hex, | ||
| reason="hash_mismatch", | ||
| detail=f"expected {hash_hex[:16]}..., got {actual[:16]}...", | ||
| ) | ||
| ) | ||
| if len(failures) >= max_failures: | ||
| break | ||
|
|
||
| if heartbeat is not None: | ||
| with suppress(Exception): | ||
| heartbeat() | ||
|
|
||
| return BlobVerifyAllResult( | ||
| checked=checked, | ||
| checked_bytes=checked_bytes, | ||
| failures=tuple(failures), | ||
| truncated=len(failures) >= max_failures, | ||
| ) |
| for hash_hex in orphan_hashes: | ||
| if not _VALID_HEX.match(hash_hex): | ||
| continue | ||
| path = self.blob_path(hash_hex) | ||
| if path.exists(): | ||
| would_delete_count += 1 | ||
| with suppress(OSError): | ||
| would_delete_bytes += path.stat().st_size | ||
| return CleanupOrphansResult( | ||
| deleted_count=0, | ||
| deleted_bytes=0, | ||
| errors=0, | ||
| error_details=(), | ||
| dry_run=True, | ||
| would_delete_count=would_delete_count, | ||
| would_delete_bytes=would_delete_bytes, | ||
| ) | ||
|
|
||
| deleted_count = 0 | ||
| deleted_bytes = 0 | ||
| errors = 0 | ||
| error_details: list[str] = [] | ||
|
|
||
| for hash_hex in orphan_hashes: | ||
| if not _VALID_HEX.match(hash_hex): | ||
| errors += 1 | ||
| error_details.append(f"invalid hash: {hash_hex[:32]}...") | ||
| continue | ||
| path = self.blob_path(hash_hex) |
Closes #818. The blob store had zero integrity verification, orphan detection was naive set-subtraction without byte totals, and there was no safe cleanup path. The two fatal GC bugs (`_still_referenced` checking the wrong table, `_candidate_blobs` missing prefix directories) had already been fixed in `1bd2f156` but had no regression tests. - `polylogue/storage/blob_store.py`: - `verify_all()` — batch content-hash verification (filesystem-only, no DB), bounded by `max_failures`. - `detect_orphans(db_referenced_ids)` — memory-bounded orphan counting with byte totals and representative sample hashes; walks one blob at a time. - `cleanup_orphans(orphan_hashes, dry_run=True)` — bulk orphan deletion; `dry_run` defaults to True for safety. - Four new result dataclasses: `BlobVerifyFailure`, `BlobVerifyAllResult`, `OrphanDetectionResult`, `CleanupOrphansResult`. - `polylogue/cli/shared/check_workflow.py`: `_run_blob_store_check` now uses `detect_orphans()`; `--deep --blob` also runs `verify_all()`. - `polylogue/maintenance/targets.py`, `polylogue/storage/repair.py`: registers `orphaned_blobs` as a CLEANUP target (`--deep`, destructive); `repair_orphaned_blobs()`, `preview_orphaned_blobs()`, `count_orphaned_blobs_sync()`. - 51 new tests across roundtrip, dedup, integrity failure, orphan detection, and GC regression. Closes #818
Direct, no-PR. `tests/unit/storage/test_backend.py` accumulated regression cases from the FK / quarantine / FTS / blob waves (PRs #879/#881/#882/#903/#911) and exceeded its previous LOC budget. Bumps `docs/plans/file-size-budgets.yaml` to 1750 so `devtools verify-file-budgets` passes; the tests stay grouped in one place rather than splitting along an arbitrary cut.
Closes #818. The blob store had zero integrity verification, orphan detection was naive set-subtraction without byte totals, and there was no safe cleanup path. The two fatal GC bugs (`_still_referenced` checking the wrong table, `_candidate_blobs` missing prefix directories) had already been fixed in `1bd2f156` but had no regression tests. - `polylogue/storage/blob_store.py`: - `verify_all()` — batch content-hash verification (filesystem-only, no DB), bounded by `max_failures`. - `detect_orphans(db_referenced_ids)` — memory-bounded orphan counting with byte totals and representative sample hashes; walks one blob at a time. - `cleanup_orphans(orphan_hashes, dry_run=True)` — bulk orphan deletion; `dry_run` defaults to True for safety. - Four new result dataclasses: `BlobVerifyFailure`, `BlobVerifyAllResult`, `OrphanDetectionResult`, `CleanupOrphansResult`. - `polylogue/cli/shared/check_workflow.py`: `_run_blob_store_check` now uses `detect_orphans()`; `--deep --blob` also runs `verify_all()`. - `polylogue/maintenance/targets.py`, `polylogue/storage/repair.py`: registers `orphaned_blobs` as a CLEANUP target (`--deep`, destructive); `repair_orphaned_blobs()`, `preview_orphaned_blobs()`, `count_orphaned_blobs_sync()`. - 51 new tests across roundtrip, dedup, integrity failure, orphan detection, and GC regression. Closes #818
Direct, no-PR. `tests/unit/storage/test_backend.py` accumulated regression cases from the FK / quarantine / FTS / blob waves (PRs #879/#881/#882/#903/#911) and exceeded its previous LOC budget. Bumps `docs/plans/file-size-budgets.yaml` to 1750 so `devtools verify-file-budgets` passes; the tests stay grouped in one place rather than splitting along an arbitrary cut.
Summary
Adds three new
BlobStoremethods for blob integrity and maintenance, wires them into thepolylogue doctor --blobcheck command, and registersorphaned_blobsas a destructive cleanup maintenance target. Includes 32 new blob store tests and 19 regression tests for the already-fixed GC bugs from 1bd2f15.Problem
Per #818, the blob store had zero integrity verification, orphan detection was limited to simple set subtraction without byte totals, and there was no safe cleanup path. The two fatal GC bugs (
_still_referencedchecking wrong table,_candidate_blobsmissing prefix directories) were already fixed in 1bd2f15 but had no regression tests.Solution
BlobStore enhancements (
polylogue/storage/blob_store.py)verify_all()— batch content-hash verification (filesystem-only, doesn't need DB). Stops atmax_failuresfor bounded output.detect_orphans(db_referenced_ids)— memory-bounded orphan counting with byte totals and representative sample hashes. Walks one blob at a time, no full-directory load.cleanup_orphans(orphan_hashes, dry_run=True)— bulk orphan deletion.dry_rundefaults toTruefor safety. Returns per-blob results and aggregate stats.BlobVerifyFailure,BlobVerifyAllResult,OrphanDetectionResult,CleanupOrphansResultCheck command wiring (
polylogue/cli/shared/check_workflow.py)_run_blob_store_checknow usesdetect_orphans()for better orphan stats (byte totals)--deepis passed with--blob, also runsverify_all()for full content integrity re-hashingMaintenance target (
polylogue/maintenance/targets.py,polylogue/storage/repair.py)orphaned_blobsregistered as CLEANUP target (requires--deep, destructive)repair_orphaned_blobs()andpreview_orphaned_blobs()handlerscount_orphaned_blobs_sync()for debt collectionTests
_still_referencedregression (recognizes raw_id, rejects unknown, empty table),_candidate_blobsregression (finds blobs across multiple prefix dirs, respects older_than, skips dotfiles, skips non-prefix dirs), lease safety,_current_generation,run_blob_gcintegration (empty store, preserves referenced, max_batch bound, nonexistent dir)Verification
Closes #818
Co-Authored-By: Claude Opus 4.7 [email protected]
Summary by CodeRabbit
Release Notes
New Features
orphaned_blobstarget inpolylogue doctorcommand.Documentation
Tests