Skip to content

fix(storage): release blob leases on failure and enforce GC generation gate - #1754

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/blob-gc-lease-durability
May 30, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/blob-gc-lease-durability

Conversation

@Sinity

@Sinity Sinity commented May 30, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes the two blob-GC durability defects from #1746: blob leases that leaked on any post-acquire write failure, and the run_blob_gc age gate that ignored the generation high-water mark its own docs promised.

Problem

commit_archive_write_effects acquired blob leases on a separate immediate-commit connection (so they're visible to a concurrent GC before the data transaction commits), but released them only on the success path with no try/finally. Any post-acquire exception — FTS repair raising, the commit failing — left the pending_blob_refs row for that operation_id forever. Because the lease was committed on its own connection, rolling back the main transaction could not undo it. The leaked lease permanently blocked GC of that blob and bloated the table on every failed write.

Separately, run_blob_gc fetched the generation high-water mark but never used it in the age computation. The module docstring, run_blob_gc's docstring, and docs/internals.md ("GC concurrency model", safety invariant #3) all claimed candidates must be "older than the previous completed GC generation plus MIN_AGE_S" — the documented defense-in-depth did not exist in code.

GC is currently manual-only (cli/commands/maintenance.py), so both were latent — but the lease leak still accumulated dead pending_blob_refs rows on every failed write.

Solution

  • archive/write_effects.py: wrap the acquire→commit→release lifetime in try/finally. On success the lease is released and lease_released is set; otherwise the finally runs _release_leases_on_failure, opening a fresh immediate-commit connection to drop the leaked lease. Any error there is logged and suppressed so it never masks the original exception.
  • storage/blob_gc.py: enforce older_than = max(MIN_AGE_S, now - prev_generation.completed_at) via _previous_generation_completed_at. Add sweep_orphaned_blob_leases(db_path, max_age_s=ORPHAN_LEASE_MAX_AGE_S=3600) reclaiming pending_blob_refs rows past the bound — the analogue of CursorStore._mark_interrupted_attempts.
  • daemon/cli.py: run the orphaned-lease sweep at startup (non-blocking via asyncio.to_thread).
  • docs/internals.md: document the try/finally release, startup sweep, and the now-enforced generation age gate.

Verification

nix develop -c pytest tests/unit/storage/test_blob_gc_lease_recovery.py -q   # 7 passed
nix develop -c python3 -m mypy tests/unit/storage/test_blob_gc_lease_recovery.py  # Success
nix develop -c devtools verify --quick                                       # exit 0

New regression tests (test_blob_gc_lease_recovery.py): a forced FTS-trigger failure mid-commit_archive_write_effects leaves zero residual leases; the success path also leaves zero; sweep_orphaned_blob_leases removes an aged lease and keeps a fresh one; run_blob_gc keeps a blob younger than the previous generation's completed_at then deletes it once aged past the boundary.

Closes #1746

Summary by CodeRabbit

  • New Features

    • Added orphaned blob-lease recovery sweep on daemon startup to reclaim resources from crashed operations.
  • Bug Fixes

    • Improved blob-lease durability to prevent leaks during write transaction failures.
  • Documentation

    • Updated blob storage garbage collection documentation with refined concurrency model details.
  • Tests

    • Added regression tests for blob-lease recovery and garbage collection safety guarantees.

Review Change Stack

…n gate

Problem: commit_archive_write_effects acquired blob leases on a separate
immediate-commit connection but released them only on the success path,
with no try/finally. Any post-acquire exception (FTS repair, commit) left
the pending_blob_refs row for that operation_id forever, blocking GC of the
blob and bloating the table. Separately, run_blob_gc fetched the generation
high-water mark but never used it in the age computation — the documented
"older than previous generation + MIN_AGE_S" defense-in-depth did not exist.

What changed:
- write_effects.py: wrap acquire/release in try/finally; on failure a fresh
  immediate-commit connection drops the leaked lease (_release_leases_on_failure).
- blob_gc.py: enforce older_than = max(MIN_AGE_S, now - prev_gen.completed_at);
  add sweep_orphaned_blob_leases() (ORPHAN_LEASE_MAX_AGE_S backstop).
- daemon/cli.py: run the orphaned-lease sweep at startup, mirroring
  CursorStore._mark_interrupted_attempts.
- docs/internals.md: document the try/finally release, startup sweep, and the
  now-enforced generation age gate.

Ref #1746

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR fixes two critical blob GC safety defects (#1746): leases permanently leaking on write-effects failures, and the GC age gate ignoring generation boundaries. It adds generation-aware eligibility gating, wraps lease lifecycle in try/finally for durability, introduces a daemon startup orphaned-lease sweep, and adds comprehensive regression tests and documentation updates.

Changes

Blob GC Safety Model Fixes

Layer / File(s) Summary
Generation-aware blob GC eligibility
polylogue/storage/blob_gc.py
run_blob_gc now computes older_than = max(MIN_AGE_S, now - previous_generation.completed_at) to enforce generation boundaries. sweep_orphaned_blob_leases removes stale pending_blob_refs rows by acquired_at age. New constant and function exported via __all__.
Write effects lease durability
polylogue/archive/write_effects.py
commit_archive_write_effects wraps blob lease acquire/release in try/finally keyed by operation_id. On FTS/commit failure, _release_leases_on_failure releases leases on a separate immediate-commit connection so the lease row does not persist if main transaction rolls back.
Daemon orphaned lease cleanup
polylogue/daemon/cli.py
Adds _sweep_orphaned_blob_leases_sync and async wrapper to call the GC sweep. Integrates sweep into daemon startup maintenance tasks so it runs on a background thread without blocking the event loop.
Documentation and regression tests
docs/internals.md, docs/plans/test-clock-allowlist.yaml, tests/unit/storage/test_blob_gc_lease_recovery.py
Internals.md documents try/finally lease handling, daemon cleanup backstop, and generation-aware age gate. Test allowlist exempts the new test (uses time.time() to backdate mtime/acquired_at). Comprehensive regression tests validate: (1) leases always release on write-effects failure/success, (2) orphaned-lease sweep filters by age while preserving young leases, (3) GC age eligibility enforces generation boundary, not just MIN_AGE_S.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#1206: Adds concurrency invariant tests covering how blob leases affect run_blob_gc deletion and release behavior; tightly connected to the lease lifecycle changes in this PR.

Poem

🐰 A lease in the void, forever adrift,
Now caught by try/finally—durability's gift!
With generation ghosts bounding each blade,
The GC sweeps clean what the daemon can't shade.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.26% 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 accurately summarizes the main changes: fixing blob lease release on failure and enforcing the GC generation age gate, which are the two primary defects addressed by the PR.
Description check ✅ Passed The PR description covers all required template sections: Summary, Problem, Solution, and Verification with concrete commands and test results. It provides clear context and rationale for all changes.
Linked Issues check ✅ Passed The PR comprehensively addresses all coding objectives from issue #1746: wrapping lease operations in try/finally [write_effects.py], enforcing the generation age gate [blob_gc.py], adding startup sweep [daemon/cli.py], and providing regression tests demonstrating all guarantees.
Out of Scope Changes check ✅ Passed All changes are directly scoped to addressing the two defects in #1746: lease leaks and generation-gate enforcement. Documentation updates clarify the implemented fixes, and test-clock allowlist addition appropriately supports the new test module.

✏️ 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-gc-lease-durability

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.

github-actions Bot pushed a commit that referenced this pull request May 30, 2026

@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: 4

🤖 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 `@polylogue/archive/write_effects.py`:
- Around line 118-128: The post-commit lease-release step can raise and cause
the function to report failure even though the archive commit is durable; wrap
the lease-release and its commit in a try/except so that exceptions from
release_operation_leases(...) or conn.commit() after the archive commit are
caught and logged but not re-raised, and ensure lease_released is set to True on
success or still set to True when you intentionally swallow the exception so
_release_leases_on_failure(db_path, operation_id) is not invoked for
already-committed work; reference release_operation_leases, conn.commit,
lease_released, has_lease, _release_leases_on_failure, operation_id and db_path
to locate and adjust the logic.
- Around line 75-79: The current logic sets has_lease = bool(blob_hashes and
operation_id) and silently skips acquire_blob_leases when db_path is missing;
add a fail-fast check so when blob_hashes and operation_id are present but
db_path is falsy you raise an explicit error (e.g., ValueError/RuntimeError)
before committing, and keep the existing call to acquire_blob_leases(db_path,
blob_hashes, operation_id) when all three (blob_hashes, operation_id, db_path)
are present; target the symbols has_lease, blob_hashes, operation_id, db_path
and the acquire_blob_leases call in archive/write_effects.py.

In `@polylogue/storage/blob_gc.py`:
- Around line 87-91: The helper that queries gc_generations returns the newest
row even if completed_at is NULL, causing previous-generation gating logic in
read_gc_history() / run_blob_gc() to treat an incomplete generation as no
previous gate; update the query in the helper (the SELECT that currently fetches
"completed_at FROM gc_generations ORDER BY generation DESC LIMIT 1") to filter
out incomplete rows (add "WHERE completed_at IS NOT NULL") so you only consider
completed generations, then keep the existing completed_at -> int conversion and
return behavior used by read_gc_history() and run_blob_gc().

In `@tests/unit/storage/test_blob_gc_lease_recovery.py`:
- Around line 36-45: The db_path fixture is using tmp_path but this storage test
must run inside the repository's isolated workspace; change the fixture to
accept the workspace_env fixture instead of tmp_path and derive the DB path from
the workspace environment (e.g., use workspace_env's temp or workspace root to
create "test.db"), then call open_connection(...) and _ensure_schema(...) as
before and return that Path; update the fixture signature from def
db_path(tmp_path: Path) to def db_path(workspace_env) and use workspace_env to
locate the test.db so the test runs under the workspace_env isolation.
🪄 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: 8579f4a9-5480-4850-8b4b-64f0b577dab7

📥 Commits

Reviewing files that changed from the base of the PR and between bcba9d1 and 155516b.

📒 Files selected for processing (6)
  • docs/internals.md
  • docs/plans/test-clock-allowlist.yaml
  • polylogue/archive/write_effects.py
  • polylogue/daemon/cli.py
  • polylogue/storage/blob_gc.py
  • tests/unit/storage/test_blob_gc_lease_recovery.py

Comment on lines +75 to 79
has_lease = bool(blob_hashes and operation_id)
if has_lease and db_path:
from polylogue.storage.blob_gc import acquire_blob_leases

acquire_blob_leases(db_path, blob_hashes, operation_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast when blob-lease inputs are incomplete.

If _blob_hashes and _operation_id are present but _db_path is missing, this path skips acquire_blob_leases() and still commits successfully. That silently reopens the GC race this change is meant to close.

Suggested fix
     has_lease = bool(blob_hashes and operation_id)
+    if blob_hashes and (not operation_id or not db_path):
+        raise ValueError("blob lease acquisition requires both _operation_id and _db_path")
     if has_lease and db_path:
         from polylogue.storage.blob_gc import acquire_blob_leases
 
         acquire_blob_leases(db_path, blob_hashes, operation_id)

As per coding guidelines, "Write paths that materialize blobs must acquire leases before committing via acquire_blob_leases() in archive/write_effects.py".

🤖 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 `@polylogue/archive/write_effects.py` around lines 75 - 79, The current logic
sets has_lease = bool(blob_hashes and operation_id) and silently skips
acquire_blob_leases when db_path is missing; add a fail-fast check so when
blob_hashes and operation_id are present but db_path is falsy you raise an
explicit error (e.g., ValueError/RuntimeError) before committing, and keep the
existing call to acquire_blob_leases(db_path, blob_hashes, operation_id) when
all three (blob_hashes, operation_id, db_path) are present; target the symbols
has_lease, blob_hashes, operation_id, db_path and the acquire_blob_leases call
in archive/write_effects.py.

Comment on lines +118 to +128
# Release blob GC leases after successful commit — the blob references
# are now durable and the GC can safely clean unreferenced blobs.
if has_lease:
from polylogue.storage.blob_gc import release_operation_leases

release_operation_leases(conn, operation_id)
conn.commit()
lease_released = True
finally:
if has_lease and not lease_released:
_release_leases_on_failure(db_path, operation_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't turn a post-commit lease cleanup error into a failed write.

Once Line 102 commits, the archive mutation is already durable. If release_operation_leases() or the follow-up conn.commit() raises here, the function propagates a failure even though the write succeeded, which can mislead callers into retrying already-committed work.

🤖 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 `@polylogue/archive/write_effects.py` around lines 118 - 128, The post-commit
lease-release step can raise and cause the function to report failure even
though the archive commit is durable; wrap the lease-release and its commit in a
try/except so that exceptions from release_operation_leases(...) or
conn.commit() after the archive commit are caught and logged but not re-raised,
and ensure lease_released is set to True on success or still set to True when
you intentionally swallow the exception so _release_leases_on_failure(db_path,
operation_id) is not invoked for already-committed work; reference
release_operation_leases, conn.commit, lease_released, has_lease,
_release_leases_on_failure, operation_id and db_path to locate and adjust the
logic.

Comment on lines +87 to +91
row = conn.execute("SELECT completed_at FROM gc_generations ORDER BY generation DESC LIMIT 1").fetchone()
if row is None:
return None
completed_at = row[0]
return int(completed_at) if completed_at is not None else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Filter out incomplete GC rows when computing the previous-generation gate.

read_gc_history() already models completed_at as nullable, so if the newest gc_generations row is incomplete this helper returns None and run_blob_gc() falls back to MIN_AGE_S only. That makes blobs eligible earlier than the last completed generation allows.

Suggested fix
-    row = conn.execute("SELECT completed_at FROM gc_generations ORDER BY generation DESC LIMIT 1").fetchone()
+    row = conn.execute(
+        "SELECT completed_at FROM gc_generations "
+        "WHERE completed_at IS NOT NULL "
+        "ORDER BY generation DESC LIMIT 1"
+    ).fetchone()
🤖 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 `@polylogue/storage/blob_gc.py` around lines 87 - 91, The helper that queries
gc_generations returns the newest row even if completed_at is NULL, causing
previous-generation gating logic in read_gc_history() / run_blob_gc() to treat
an incomplete generation as no previous gate; update the query in the helper
(the SELECT that currently fetches "completed_at FROM gc_generations ORDER BY
generation DESC LIMIT 1") to filter out incomplete rows (add "WHERE completed_at
IS NOT NULL") so you only consider completed generations, then keep the existing
completed_at -> int conversion and return behavior used by read_gc_history() and
run_blob_gc().

Comment on lines +36 to +45
@pytest.fixture
def db_path(tmp_path: Path) -> Path:
db = tmp_path / "test.db"
conn = open_connection(db)
try:
_ensure_schema(conn)
conn.commit()
finally:
conn.close()
return db

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 for this storage test module.

These tests exercise storage code and create archive-backed state, so they should run under the repository's isolated workspace fixture rather than only raw tmp_path setup.

As per coding guidelines, "Use workspace_env fixture from conftest.py for tests touching storage or pipeline - provides isolated XDG paths and archive root".

🤖 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/unit/storage/test_blob_gc_lease_recovery.py` around lines 36 - 45, The
db_path fixture is using tmp_path but this storage test must run inside the
repository's isolated workspace; change the fixture to accept the workspace_env
fixture instead of tmp_path and derive the DB path from the workspace
environment (e.g., use workspace_env's temp or workspace root to create
"test.db"), then call open_connection(...) and _ensure_schema(...) as before and
return that Path; update the fixture signature from def db_path(tmp_path: Path)
to def db_path(workspace_env) and use workspace_env to locate the test.db so the
test runs under the workspace_env isolation.

@Sinity
Sinity merged commit 2744076 into master May 30, 2026
7 checks passed
@Sinity
Sinity deleted the feature/fix/blob-gc-lease-durability branch May 30, 2026 16:42
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.

[bug] Blob GC lease leak on write failure; age gate ignores generation high-water mark

1 participant