Repository navigation
fix(storage): release blob leases on failure and enforce GC generation gate - #1754
Conversation
…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]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
📝 WalkthroughWalkthroughThis PR fixes two critical blob GC safety defects ( ChangesBlob GC Safety Model Fixes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
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
📒 Files selected for processing (6)
docs/internals.mddocs/plans/test-clock-allowlist.yamlpolylogue/archive/write_effects.pypolylogue/daemon/cli.pypolylogue/storage/blob_gc.pytests/unit/storage/test_blob_gc_lease_recovery.py
| 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) |
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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().
| @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 |
There was a problem hiding this comment.
🛠️ 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.
Summary
Closes the two blob-GC durability defects from #1746: blob leases that leaked on any post-acquire write failure, and the
run_blob_gcage gate that ignored the generation high-water mark its own docs promised.Problem
commit_archive_write_effectsacquired 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 notry/finally. Any post-acquire exception — FTS repair raising, the commit failing — left thepending_blob_refsrow for thatoperation_idforever. 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_gcfetched the generation high-water mark but never used it in the age computation. The module docstring,run_blob_gc's docstring, anddocs/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 deadpending_blob_refsrows on every failed write.Solution
archive/write_effects.py: wrap the acquire→commit→release lifetime intry/finally. On success the lease is released andlease_releasedis set; otherwise thefinallyruns_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: enforceolder_than = max(MIN_AGE_S, now - prev_generation.completed_at)via_previous_generation_completed_at. Addsweep_orphaned_blob_leases(db_path, max_age_s=ORPHAN_LEASE_MAX_AGE_S=3600)reclaimingpending_blob_refsrows past the bound — the analogue ofCursorStore._mark_interrupted_attempts.daemon/cli.py: run the orphaned-lease sweep at startup (non-blocking viaasyncio.to_thread).docs/internals.md: document the try/finally release, startup sweep, and the now-enforced generation age gate.Verification
New regression tests (
test_blob_gc_lease_recovery.py): a forced FTS-trigger failure mid-commit_archive_write_effectsleaves zero residual leases; the success path also leaves zero;sweep_orphaned_blob_leasesremoves an aged lease and keeps a fresh one;run_blob_gckeeps a blob younger than the previous generation'scompleted_atthen deletes it once aged past the boundary.Closes #1746
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests