Skip to content

fix(storage): run_blob_gc unlinks sharded path + dry-run + history (#1190) - #1318

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/blob-gc-unlink-1190
May 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/blob-gc-unlink-1190

Conversation

@Sinity

@Sinity Sinity commented May 18, 2026

Copy link
Copy Markdown
Owner

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-fix(storage): run_blob_gc unlinks wrong path, deleted counter inflated #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

Problem
- ``run_blob_gc`` unlinked ``{blob_dir}/{full_hash}`` rather than the
  sharded ``{blob_dir}/{prefix}/{remainder}`` where blobs actually live.
- ``missing_ok=True`` swallowed the inevitable ENOENT and the ``deleted``
  counter still incremented, so GC reports lied: counts said reclaimed,
  orphan blobs stayed on disk.

Solution
- ``polylogue/storage/blob_gc.py``: unlink the sharded path; treat
  FileNotFoundError as ``skipped_missing`` (do NOT bump deleted);
  separate PermissionError / OSError as ``skipped_unlink_error``.
- New ``GCRunEvidence`` dataclass captures
  inspected/deleted/skipped_referenced/skipped_leased/skipped_missing/
  skipped_unlink_error/dry_run/max_batch/previous_generation/
  deleted_hashes and is persisted as JSON in a new
  ``gc_generations.evidence`` column.
- New ``dry_run=True`` kwarg: counts would-be deletions without
  touching disk and without consuming a generation slot.
- New ``read_gc_history(db_path, limit)`` returns parsed history rows
  newest-first; rows without evidence (pre-#1190 or crashed passes)
  surface with ``evidence=None``.
- ``polylogue maintenance gc-history`` CLI surfaces the evidence rows
  (plain or JSON) so operators don't need bespoke SQLite tooling.
- Schema bumped to v2 (``gc_generations.evidence TEXT``); fresh-first
  policy applies — mismatch triggers re-ingest, no migration chain.

Tests
- New tests in ``tests/unit/storage/test_blob_gc.py``:
  ``test_run_blob_gc_unlinks_sharded_path_and_increments_counter`` and
  ``test_run_blob_gc_does_not_increment_when_file_already_missing``
  cover the AC pair from #1190; plus dry-run, evidence persistence,
  and history surface tests.
- Updated the existing concurrency test's pre-thread setup with a
  sentinel lease — the prior code's no-op unlink masked a race window
  between thread spawn and the writer's first ``acquire_blob_leases``.

Verification
  devtools verify --quick   # exit 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

Closes #1190
@Sinity
Sinity merged commit ef6a09a into master May 18, 2026
@coderabbitai

coderabbitai Bot commented May 18, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 41 minutes and 38 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 22153477-27bc-4fc1-84d3-036ddff7c4e3

📥 Commits

Reviewing files that changed from the base of the PR and between 9cfd585 and e6253b1.

📒 Files selected for processing (9)
  • docs/test-quality-workflows.md
  • docs/verification-catalog.md
  • polylogue/cli/commands/maintenance.py
  • polylogue/storage/blob_gc.py
  • polylogue/storage/sqlite/schema_ddl.py
  • polylogue/storage/sqlite/schema_ddl_archive.py
  • tests/unit/storage/test_blob_gc.py
  • tests/unit/storage/test_blob_gc_concurrency.py
  • tests/unit/storage/test_blob_store_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/blob-gc-unlink-1190

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 deleted the feature/fix/blob-gc-unlink-1190 branch May 18, 2026 15:07
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): run_blob_gc unlinks wrong path, deleted counter inflated

1 participant