Repository navigation
fix: backfill eviction-index coverage during metadata reconciliation (#189) - #209
Conversation
Greptile SummaryThe PR folds eviction-index backfilling into metadata reconciliation so capped caches can reclaim keys written while uncapped or under another policy.
Confidence Score: 4/5The PR is not yet safe to merge because startup reconciliation failures still allow serving to begin before size accounting and eviction-index coverage are reliable. The new pending flag retries failed reconciliation on the next cleanup tick, but batch-write and iterator failures are not returned from reconcileFromMetadata, and Start unconditionally marks initialization complete; the previously reported startup failure remains reachable during that interval. Files Needing Attention: storage/cleaner.go, storage/storage.go Important Files Changed
Reviews (5): Last reviewed commit: "fix: backfill eviction-index coverage du..." | Re-trigger Greptile |
5afac57 to
c959e82
Compare
c959e82 to
41f86e7
Compare
|
Addressed the review feedback in the latest push (force-updated the branch):
The previously One framing note: the residual "incomplete coverage" state is the pre-existing #189 bug this PR reduces — a partial backfill still indexes strictly more keys than the prior behavior (which indexed none on these histories), so it never leaves data more unreachable than before. The changes above make it converge to complete rather than depend on a clean single pass. |
41f86e7 to
852b694
Compare
|
@greptile-apps good catch on the retry latency — fixed in the latest push. The gap was real: the periodic reconcile only re-ran at the 1-hour Now an incomplete pass (a failed batch write, a Two bounding notes:
|
|
The The convergence path holds. One subtle nuance in the truncated-scan path: LRU timestamp granularity: all backfilled LRU keys in a single pass share the same
LGTM. The window reduction from "up to an hour" to "within one tick" is real, the convergence property under near-full disk is well-reasoned, and the clean-pass → revert-to-hourly cycle is correct. Tip: You can customize Greptile's behavior for this repo with |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 852b694. Configure here.
…189) putLow writes an eviction-index entry only when a cap is set at write time, and only for the policy active then. Nothing ever backfills, so keys written while uncapped — or under a different policy before an lru<->fifo switch — have no index entry and are permanently invisible to eviction: enforceDiskLimit finds zero candidates and the disk cap can never be met even though the keys are live and readable. This is the root of #189, and it is what fills the volume and feeds the terminal ENOSPC in #204 (once the disk is full RocksDB can no longer open, so eviction can never run again and only deleting the data directory recovers). Reproduces trivially: write keys with MaxDiskUsage:0, reopen with a cap, and every eviction tick logs "current" unchanged with zero processed. Fold the fix into the cleaner's metadata reconciliation. calculateTotalSize is generalized into reconcileFromMetadata, which — whenever a cap is set — also guarantees index coverage by merge-joining the metadata rows against the active policy's back-reference rows (both stored sorted by the same key suffix), advancing a second iterator in lockstep. Coverage is checked in O(1) memory with no per-key lookups, inside the scan the cleaner already runs; any live key missing a back-reference gets a fresh entry, covering every history (uncapped->capped, lru<->fifo). Orphan back-references (no metadata row) are skipped. Running on every reconcile (not just startup) makes coverage self-healing. To bound the window after a failed pass, an incomplete backfill (a failed batch write or a truncated scan) sets a backfillPending flag; while set, the cleanup loop re-runs the reconcile every tick instead of waiting for the hourly recalc, so uncovered keys become evictable within a tick rather than up to an hour. A concurrent put during a live pass can momentarily leave a duplicate/orphan index entry, which the eviction scan already validates against the back-reference and reclaims (FIFO goes through writeFifoIndexEntry so the stale entry is deleted, not duplicated); the size sum stays correct via the #205 snapshot-relative correction. Harden the scan itself: check the iterator's Err() after the loop and, on a truncated scan, skip the size correction (a partial sum would under-size the counter and weaken the very eviction this protects) and flag a fast retry; surface incomplete backfills (failed batches / back-reference scan errors) as warnings rather than a buried info log. Backfilled keys are stamped at scan time: their true write/access time is unrecorded, so the order among them is arbitrary (the documented non-fresh tradeoff), but they become evictable. Stamping at "now" also keeps lru-backfilled keys clear of cleanupOldBuckets, which prunes access rows older than 30 days without evicting. This makes warnIfUnindexedForFifo obsolete, so it is removed; docs/configuration.md is updated. The residual leftover-lru-access-rows cleanup on an lru->fifo switch is unchanged and still tracked by #189. Tests (backfill_eviction_index_test.go): the write-uncapped/reopen-capped state is reclaimed for both policies; a clean backfill clears backfillPending; reopen is idempotent (no duplicate FIFO entries); a reconciliation pass self-heals a key that lost its entry; and orphan back-references are skipped without derailing real-key backfill. make test-storage passes. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra Signed-off-by: Ovais Tariq <[email protected]>
852b694 to
3f58a3a
Compare
|
Reviewed the latest round of bot findings: @cursor (Medium, @greptile-apps Two stale findings (filed against superseded commits, already resolved):
|
|
The fix in
One small observation on if c.backfillPending.Load() || time.Since(lastSizeRecalc) > totalSizeRecalcInterval {
c.calculateTotalSize() // this is just a thin wrapper that calls reconcileFromMetadata()That's fine since The design rationale for leaving The stale findings acknowledgment is appreciated — clean accounting. LGTM on the |
|
🎉 This PR is included in version 1.10.0 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |
… review
High-effort review of the CAS branch surfaced ten defects; this addresses all of
them while keeping every change inside the CAS feature (no cleaner changes, no
plain-hot-path refactor). The design decision behind the fixes: CAS is
self-contained and does not coordinate with the TTL cleaner's unconditional
sweep, so an expired/deleted row reads as absent and recreate is put-if-absent.
Correctness:
- Resurrection of CAS-deleted keys (critical). The CAS_DELETE tombstone kept
the base's ValueType and RawFilePath/SegmentPath so the cleaner could reclaim
them, but that let an in-flight compactor/recompactor path-CAS operand
(matched on ValueType + path) revive the deleted key with its pre-delete
expiry. The tombstone is now REF-LESS ({Expiry:1, Version:stamp} only); with
no ValueType/path it can no longer satisfy the migration precondition.
DeleteIfVersion reclaims the backing bytes itself on its confirmed win.
- Version semantics unified in merge.EffectiveRowVersion(vm): a tombstone
(Expiry == 1) reads as 0 ("absent") regardless of its stamp. This fixes two
holes at once — the pre-existing no-base fallback sentinel (stored version 0)
no longer reads as VersionLegacy, so a stale legacy token can't pass CAS
across a delete; and a no-base CAS_DELETE's stamp no longer blocks
put-if-absent on a truly-absent key. GetWithVersion returns 0 for an
expired/deleted row (no recreate-token handout); recreate is expected == 0,
best-effort like a plain Put (the pre-existing cleaner-vs-write race is filed
separately, not newly introduced by CAS).
- PutIfVersion read-back error path now stages the spilled file before
returning (previously orphaned a up-to-256MB file on an indeterminate
read-back); plain Put's new nextVersion() step likewise stages its spill on
failure. Both are the #156 orphan class, worst for the large-object workload.
- Init ordering: loadVersionReservation now runs BEFORE the compactor and
deletion-queue goroutines start, so a failed !verhwm read returns a clean
init error instead of leaking background threads against an open DB the
caller believes never constructed.
- Under contention, only the confirmed winner reclaims the replaced value; a
loser reclaims only its own spill, never prev — eliminating the N-fold
segment delete-index over-credit.
- DeleteIfVersion frees disk immediately on win (reclaim + size decrement)
rather than waiting a cleanup interval, relieving disk-cap pressure near
ENOSPC for 256MB objects.
Regression tests: tombstone-not-resurrected-by-migration, ref-less tombstone
shape, recreate-over-tombstone via put-if-absent, tombstone-reads-as-absent,
and delete-reclaims-immediately. Full test-storage, test-server, test-race,
build, and lint pass.
Deliberately deferred (kept out of this PR for containment): the pre-existing
TTL-cleaner unconditional-delete race (filed separately) and extracting a
shared write-bookkeeping helper between putLow and finishWonCASPut (low-risk,
self-heals via the #209 reconcile).
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra
Signed-off-by: Ovais Tariq <[email protected]>

Fixes the core of #189. Also removes the most common way to reach the terminal-ENOSPC state in #204.
Problem
putLowwrites an eviction-index entry only when a cap is set at write time, and only for the policy active then — and nothing ever backfills. So keys written while uncapped, or under one policy before anlru↔fifoswitch, are permanently invisible to eviction:enforceDiskLimitfinds zero candidates and the cap can never be met. Reproduces trivially (write withMaxDiskUsage:0, reopen with a cap): every tick logscurrentunchanged,processed=0, while every key stays live. This is what filled Goldsky's volumes into the terminal ENOSPC of #204.Fix — folded into the metadata reconciliation, self-healing
calculateTotalSizeis generalized intoreconcileFromMetadata. Whenever a cap is set, the same scan that sumsvalue_lengthalso guarantees index coverage by merge-joining the!meta/<key>rows against the active policy's back-reference rows (!fifo_ref//!access_bucket_index/). Both are sorted by the same key suffix, so a second iterator advanced in lockstep decides coverage in a single linear pass — O(1) memory, no per-key lookups. Any live key with no back-reference gets a fresh entry (covers uncapped→capped andlru↔fifo); orphan back-references are skipped.It runs on every reconcile, not just startup, which makes coverage self-healing: a backfill left incomplete by a write error, iterator error, or a crash mid-scan is completed on a later pass instead of leaving keys unevictable until a restart. The merge is cheap when coverage is already complete. A concurrent put during a live pass can momentarily leave a duplicate/orphan entry, which the eviction scan already validates against the back-reference and reclaims (FIFO routes through
writeFifoIndexEntry, deleting the stale entry rather than duplicating); the size sum stays correct via the #205 snapshot-relative correction.Scan hardening: the loop now checks
it.Err()— on a truncated scan it skips the size correction (a partial sum would under-size the counter and weaken the eviction this protects) and retries next reconcile; incomplete backfills (failed batches / back-ref scan errors) are surfaced aswarns, not a buriedinfo.Ordering: backfilled keys have no recorded write/access time, so they're stamped at scan time and evicted in an arbitrary (but bounded) order among themselves. Stamping at
nowkeepslru-backfilled keys clear ofcleanupOldBuckets(prunes access rows >30d old without evicting).warnIfUnindexedForFifowarned about exactly the state this fixes, so it's removed;docs/configuration.mdupdated.Design notes
An earlier revision did a standalone startup pass with a per-key point-
Getand an in-memory set of indexed keys — both rejected for a generalized solution (O(N) memory / a random-read storm on every capped startup). The merge-join reuses the existing scan, is O(1) memory, and needs no lookups, so it's cheap enough to run on every reconcile and stay synchronous (cap effective the instant the node serves).Test
storage/backfill_eviction_index_test.go: write-uncapped/reopen-capped keys reclaimed (both policies); reopen idempotent (no duplicate FIFO entries); a reconciliation pass self-heals a key that lost its entry; and orphan back-references (before and after the real keys) are skipped without derailing real-key backfill. Fullmake test-storagepasses; vet/fmt clean.Scope
Piece 1 of the #189/#204 pair. Follow-ups (separate PRs): statfs high-water backstop (#204 prevention) and a reserved-headroom / degraded-open recovery path for ENOSPC-at-open (#204 recovery).
🤖 Generated with Claude Code
Note
Cursor Bugbot is generating a summary for commit 852b694. Configure here.