Skip to content

fix(storage): bring blob orphan cleanup and integrity verification to honest closure (#818) - #1002

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/blob-integrity-honest-closure
May 10, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/blob-integrity-honest-closure

Conversation

@Sinity

@Sinity Sinity commented May 10, 2026 •

Copy link
Copy Markdown
Owner

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_blobs handler, orphaned_blobs maintenance 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 check orphan output, polylogue doctor --repair --target orphaned_blobs round-trip), nor a property test for the bounded-output invariant on detect_orphans. Any regression in any one wiring layer (paths, blob_store, repair, maintenance) could land silently.

Solution

Acceptance criteria matrix

AC What State after this PR
818-A1 detect_orphans returns count, bytes, sample; bounded output independent of N ✅ Implementation pre-existing; new property test in tests/property/test_blob_store_props.py asserts samples bounded by max_sample and counts/bytes match the disk-minus-DB set across hypothesis-generated (0–80 orphans, 1–20 max_sample) parameter space
818-A2 cleanup_orphans(dry_run=True) default opt-in safety ✅ Pre-existing; new property test asserts dry-run never deletes; new e2e test asserts TOCTOU race (blob vanished mid-cleanup) is no-op
818-A3 verify_all(max_failures) re-hashes blobs, no DB ✅ Pre-existing tests; integrity round-trip exercised in new e2e test
818-A4 Orphan detection in polylogue check operator output ✅ Pre-existing in cli/shared/check_workflow.py:142; tightened assertion in tests/unit/cli/test_check_support_runtime.py:191 to require "Orphaned: 1 blobs (4,096 bytes)" exact string + sample line
818-A5 polylogue check --deep runs verify_all ✅ Pre-existing at check_workflow.py:147; rendered in docs/cli-reference.md (regenerated in #1001)
818-A6 orphaned_blobs maintenance target wired through catalog → handler dict → handler ✅ Pre-existing wiring (maintenance/targets.py:237, repair.py:671/1144/1157); new e2e tests in TestRepairOrphanedBlobsHandler + TestOrphanedBlobsCatalogRouting exercise both the handler in isolation AND the catalog→handler dispatch path
818-A7 Regression tests for 1bd2f156 GC bug fixes ✅ tests/unit/storage/test_blob_gc.py covers both
818-A8 Daemon-side bounded verify_all ✅ daemon/health.py:639 uses max_failures=5
818-A9 End-to-end ingest → orphan → detect → dry-run → apply → verify ✅ New tests/integration/test_blob_lifecycle_e2e.py
818-A10 Closeout matrix in PR + issue comment ✅ This PR body + planned comment on #818
818-A11 Lease tables pending_blob_refs, gc_generations retain/remove decision ➡️ Out of scope, tracked at #1000 — the lease tables ARE used by blob_gc.py (lease acquire/release, generation tracking); the actual question is whether the lease-based GC design is still current vs. snapshot-based repair_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

$ pytest tests/unit/storage/test_blob_store.py \
         tests/unit/storage/test_blob_gc.py \
         tests/unit/cli/test_check_support_runtime.py \
         tests/integration/test_blob_lifecycle_e2e.py \
         tests/property/test_blob_store_props.py -q
84 passed in ~12s

$ devtools verify --quick
verify: all checks passed

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 commit 4a96e6e8 by adding TestOrphanedBlobsCatalogRouting with three tests covering spec resolution (mode/category/destructive flag), handler-dict entries (both _REPAIR_HANDLERS and _PREVIEW_HANDLERS), and end-to-end catalog→handler→archive cleanup.

Iteration 2 — found one borderline (mock field scanned_count doesn't exist on real OrphanDetectionResult) and one borderline (TOCTOU test scope clarity). Fixed mock field cleanup in commit 86f85e15. TOCTOU test docstring already explains scope; the "blob re-referenced before cleanup" path is caller-orchestration, not a BlobStore contract. Iteration 2 also flagged that the bounded-memory property test asserts output bound but not intermediate memory bound — dismissed because the implementation in blob_store.py:367-385 is structurally streaming (3 counters + a bounded list of max_sample), and the test asserts orphan_count/orphan_bytes are 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

  • Tests
    • Added comprehensive integration and property-based tests for blob orphan lifecycle management, including dry-run and live cleanup scenarios, idempotency validation, and catalog routing verification.
    • Updated test expectations for blob-store orphan reporting to align with current system behavior.

Review Change Stack

Copilot AI review requested due to automatic review settings May 10, 2026 01:40
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This 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.

Changes

Blob Orphan Lifecycle Testing

Layer / File(s) Summary
Test Setup & Fixtures
tests/integration/test_blob_lifecycle_e2e.py, tests/property/test_blob_store_props.py
Imports, type aliases (CliWorkspace), byte constants (_REFERENCED_BLOB, _ORPHAN_BLOB), and helper functions (_seed_raw_row, _store) for integration and property test suites.
Core Orphan Lifecycle
tests/integration/test_blob_lifecycle_e2e.py
End-to-end test exercising detect orphans, cleanup in dry-run and live modes, re-detection to confirm zero orphans, and verification of referenced blob integrity.
Cleanup Robustness & Idempotency
tests/integration/test_blob_lifecycle_e2e.py
Edge case test confirming cleanup does not raise and reports a no-op when the target orphan blob is already missing from disk.
Maintenance Handler Wiring
tests/integration/test_blob_lifecycle_e2e.py
Tests for repair_orphaned_blobs handler: validates dry-run reports would-be deletions, live mode deletes orphans while preserving referenced blobs, and clean state returns no-op.
Catalog Resolution & Dispatch
tests/integration/test_blob_lifecycle_e2e.py
Tests catalog resolution of orphaned_blobs target, handler dictionary routing, and full end-to-end dispatch from catalog through handler to orphan deletion.
Orphan Detection Invariants
tests/property/test_blob_store_props.py
Property-based tests validating detect_orphans returns exact counts/bytes, respects sample bounds, and cleanup_orphans dry-run never deletes while reporting accurate would-delete counts.
Unit Test Expectations
tests/unit/cli/test_check_support_runtime.py
Updates mocked detect_orphans return values by removing scanned_count and tightens console output assertions to require orphan summary with count, formatted bytes, and samples.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Sinity/polylogue#879: The main PR adds end-to-end and property tests that directly exercise the blob-store orphan detection/cleanup and maintenance routing APIs introduced in the retrieved PR.

Poem

🐰 A bunny hops through orphaned blobs with care,
Dry-running first—no deletions in the air!
When verified, the referenced blobs stay sound,
The catalog routes each cleanup all around.
Now property-tested, this logic's quite fair! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: bringing blob orphan cleanup and integrity verification to closure, with the issue number referenced.
Description check ✅ Passed The PR description comprehensively covers all required template sections: Summary, Problem, Solution (with acceptance criteria matrix), Verification, and detailed notes on adversarial review and scope.
Linked Issues check ✅ Passed All coding requirements from issue #818 are addressed: orphan detection [818-A1], dry-run safety [818-A2], integrity verification [818-A3], operator output [818-A4], catalog routing [818-A6], and end-to-end round-trip [818-A9] with new tests validating each requirement.
Out of Scope Changes check ✅ Passed All changes are scoped to test-only additions for #818 closure: new integration/property test files and tightened unit test assertions. The lease-table decision is explicitly deferred to #1000. No unrelated production code changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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-honest-closure

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread polylogue/operations/archive.py Resolved

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sinity and others added 4 commits May 10, 2026 12:58
)

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]>
@Sinity
Sinity force-pushed the feature/fix/blob-integrity-honest-closure branch from 86f85e1 to 0edee7c Compare May 10, 2026 11:01

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between aabb547 and 0edee7c.

📒 Files selected for processing (3)
  • tests/integration/test_blob_lifecycle_e2e.py
  • tests/property/test_blob_store_props.py
  • tests/unit/cli/test_check_support_runtime.py

Comment on lines +33 to +45
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

Comment on lines +49 to +60
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ 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.

@Sinity
Sinity merged commit c2f2c26 into master May 10, 2026
4 checks passed
@Sinity
Sinity deleted the feature/fix/blob-integrity-honest-closure branch May 10, 2026 11:07
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 68.F026 / P1: fixed-already at the checked revision: polylogue/api/archive.py:68 imports IndexStatus at runtime, outside TYPE_CHECKING. The current get_index_status route at lines 5576-5584 delegates to archive.index_status through a read transaction and has no undefined-name DatabaseError fallback.

Only the rows listed above are dispositioned. Held findings remain open.

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