Skip to content

fix(storage): add blob orphan detection, cleanup, and integrity verification (#818) - #879

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/blob-integrity-818
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/blob-integrity-818

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds three new BlobStore methods for blob integrity and maintenance, wires them into the polylogue doctor --blob check command, and registers orphaned_blobs as 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_referenced checking wrong table, _candidate_blobs missing 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 at max_failures for 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_run defaults to True for safety. Returns per-blob results and aggregate stats.
  • Four new result dataclasses: BlobVerifyFailure, BlobVerifyAllResult, OrphanDetectionResult, CleanupOrphansResult

Check command wiring (polylogue/cli/shared/check_workflow.py)

  • _run_blob_store_check now uses detect_orphans() for better orphan stats (byte totals)
  • When --deep is passed with --blob, also runs verify_all() for full content integrity re-hashing
  • Enhanced plain and JSON output includes byte totals and integrity results

Maintenance target (polylogue/maintenance/targets.py, polylogue/storage/repair.py)

  • orphaned_blobs registered as CLEANUP target (requires --deep, destructive)
  • repair_orphaned_blobs() and preview_orphaned_blobs() handlers
  • count_orphaned_blobs_sync() for debt collection
  • File-size budget bumped from 1100 to 1200 for repair.py (added 97 lines of blob cleanup logic)

Tests

  • test_blob_store.py (32 new tests): verify, verify_all (empty, pass, mismatch, max_failures, removed dirs), detect_orphans (none, some, all, max_sample), cleanup (dry-run reporting, apply deletion, invalid hash errors), remove, stats, iter_all filtering, blob_path validation, content-addressing invariants, result dataclass properties
  • test_blob_gc.py (19 tests, new file): _still_referenced regression (recognizes raw_id, rejects unknown, empty table), _candidate_blobs regression (finds blobs across multiple prefix dirs, respects older_than, skips dotfiles, skips non-prefix dirs), lease safety, _current_generation, run_blob_gc integration (empty store, preserves referenced, max_batch bound, nonexistent dir)

Verification

$ python -m pytest tests/unit/storage/test_blob_store.py tests/unit/storage/test_blob_gc.py -q
51 passed in 10.54s

$ ruff check <changed files>
All checks passed!

$ python -m mypy polylogue/storage/blob_store.py polylogue/cli/shared/check_workflow.py polylogue/storage/repair.py polylogue/maintenance/targets.py
Success: no issues found in 4 source files

$ devtools render-all --check
OK: all rendered surfaces in sync

$ python -m pytest tests/unit/storage/test_repair.py -q
5 passed

Closes #818

Co-Authored-By: Claude Opus 4.7 [email protected]

Summary by CodeRabbit

Release Notes

  • New Features

    • Added blob orphan detection and cleanup to maintenance operations via new orphaned_blobs target in polylogue doctor command.
    • Enhanced integrity verification for blob storage with deep validation capabilities.
  • Documentation

    • Updated CLI reference documenting new maintenance target options for blob management.
    • Updated verification catalogs and test quality documentation.
  • Tests

    • Added comprehensive test coverage for blob storage operations and garbage collection.

…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]>
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 782b9fde-2a84-44df-acf8-56d3b9d6e5bc

📥 Commits

Reviewing files that changed from the base of the PR and between b8d7970 and 7afba00.

📒 Files selected for processing (10)
  • docs/cli-reference.md
  • docs/plans/file-size-budgets.yaml
  • docs/test-quality-workflows.md
  • docs/verification-catalog.md
  • polylogue/cli/shared/check_workflow.py
  • polylogue/maintenance/targets.py
  • polylogue/storage/blob_store.py
  • polylogue/storage/repair.py
  • tests/unit/storage/test_blob_gc.py
  • tests/unit/storage/test_blob_store.py

📝 Walkthrough

Walkthrough

This PR adds orphan blob detection, cleanup, and integrity verification to the storage layer. It introduces new BlobStore methods (verify_all, detect_orphans, cleanup_orphans), repair helpers for cleanup orchestration, CLI workflow integration for deep integrity checks, a new maintenance target registration, and comprehensive test coverage for both blob GC safety invariants and blob store operations.

Changes

Blob Orphan Detection and Cleanup

Layer / File(s) Summary
Data Shapes & Result Types
polylogue/storage/blob_store.py, polylogue/maintenance/targets.py
Four new frozen dataclasses (BlobVerifyFailure, BlobVerifyAllResult, OrphanDetectionResult, CleanupOrphansResult) model operation results. New orphaned_blobs maintenance target added as a destructive archive cleanup target requiring deep readiness checks.
Blob Store Maintenance Methods
polylogue/storage/blob_store.py
Three new public methods: verify_all() re-hashes and validates on-disk blobs against filename hashes with bounded failure tracking; detect_orphans() scans disk for blobs not referenced by DB raw_ids and returns counts/bytes/samples; cleanup_orphans() deletes orphan hashes with dry-run safety.
Blob Store Public API Exports
polylogue/storage/blob_store.py
Updated __all__ to explicitly export new result dataclasses and maintenance methods as part of the public API surface.
Repair Module Helpers & Debt Status
polylogue/storage/repair.py
Added count_orphaned_blobs_sync() to count unreferenced blobs via DB scan, repair_orphaned_blobs() to delete with dry-run/error reporting, and preview_orphaned_blobs() for dry-run output. Extended collect_archive_debt_statuses_sync() to include orphaned blob counts.
Repair Handler Wiring & Exports
polylogue/storage/repair.py
Registered preview and repair handlers for orphaned_blobs target in _PREVIEW_HANDLERS and _REPAIR_HANDLERS orchestration registries. Updated __all__ exports to include new blob-related functions.
CLI Workflow Integration
polylogue/cli/shared/check_workflow.py
Updated _run_blob_store_check() to accept deep flag, use detect_orphans() for richer orphan output (byte totals, samples), and optionally run verify_all() for integrity verification when deep=True. CLI wiring updated to pass options.deep into the blob check.
Blob GC Safety Regression Tests
tests/unit/storage/test_blob_gc.py
New test suite covering fixed GC invariants: _still_referenced() blob detection, _candidate_blobs() prefix-directory traversal, _has_active_lease() lease tracking, _current_generation() generation management, and run_blob_gc() integration for empty stores, reference preservation, and max-batch adherence.
Blob Store Operations Tests
tests/unit/storage/test_blob_store.py
Expanded test coverage: write deduplication across methods, single/batch blob verification with hash-mismatch detection, orphan detection with sampling limits, cleanup dry-run and apply modes with error handling, plus foundational tests for remove/stats/iter_all/blob_path validation and content-addressing invariants.
Documentation & Configuration
docs/cli-reference.md, docs/plans/file-size-budgets.yaml, docs/test-quality-workflows.md, docs/verification-catalog.md
Updated CLI reference with new --target options, file-size budget exception for repair.py (ceiling 1200), test-quality workflows with uncovered target additions, and verification catalog with incremented subject/obligation counts for the new maintenance target.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Sinity/polylogue#687: Both modify polylogue/storage/repair.py to adjust archive-debt messaging and reporting; this PR adds orphan detection while the retrieved PR refines existing debt status output.
  • Sinity/polylogue#351: Both introduce maintenance target and proof obligation additions; the retrieved PR established the maintenance.target catalog foundation while this PR extends it with orphaned_blobs.
  • Sinity/polylogue#504: Both modify polylogue/storage/blob_store.py and BlobStore class; the retrieved PR rewrites write_from_path hashing while this PR adds verify/detect/cleanup operations.

Suggested labels

type:test, area:storage, area:cli, area:qa

Poem

🐇 Orphaned blobs scattered far and wide,
Now found with deep integrity's guide!
Verify, detect, and cleanup with care—
Dry-run first to tidy the air. ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/blob-integrity-818

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 and usage tips.

@Sinity
Sinity merged commit 1bc0d37 into master May 7, 2026
2 of 3 checks passed
Copilot AI review requested due to automatic review settings May 7, 2026 06:11
@Sinity
Sinity deleted the feature/fix/blob-integrity-818 branch May 7, 2026 06:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 BlobStore with verify_all(), detect_orphans(), and cleanup_orphans() plus typed result dataclasses.
  • Wire blob orphan stats + optional deep integrity re-hashing into the doctor --blob check workflow, and register orphaned_blobs as 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.

Comment on lines +137 to +143
# 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)

Comment on lines +696 to +713
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)"
),
)
Comment on lines +111 to +117
# 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}"
Comment on lines +283 to +350
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,
)
Comment on lines +405 to +433
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)
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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.
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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.
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.

fix(storage): clean orphan blobs and wire blob integrity checks

2 participants