Skip to content

fix: backfill eviction-index coverage during metadata reconciliation (#189) - #209

Merged
ovaistariq merged 1 commit into
mainfrom
fix/189-backfill-eviction-index
Aug 14, 2026
Merged

ovaistariq merged 1 commit into
mainfrom
fix/189-backfill-eviction-index

Conversation

@ovaistariq

@ovaistariq ovaistariq commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the core of #189. Also removes the most common way to reach the terminal-ENOSPC state in #204.

Problem

putLow writes 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 an lru↔fifo switch, are permanently invisible to eviction: enforceDiskLimit finds zero candidates and the cap can never be met. Reproduces trivially (write with MaxDiskUsage:0, reopen with a cap): every tick logs current unchanged, 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

calculateTotalSize is generalized into reconcileFromMetadata. Whenever a cap is set, the same scan that sums value_length also 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 and lru↔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 as warns, not a buried info.

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 now keeps lru-backfilled keys clear of cleanupOldBuckets (prunes access rows >30d old without evicting).

warnIfUnindexedForFifo warned about exactly the state this fixes, so it's removed; docs/configuration.md updated.

Design notes

An earlier revision did a standalone startup pass with a per-key point-Get and 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. Full make test-storage passes; 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.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR folds eviction-index backfilling into metadata reconciliation so capped caches can reclaim keys written while uncapped or under another policy.

  • Adds a snapshot-based merge join between metadata and active-policy back-references.
  • Retries incomplete backfills on cleanup ticks and avoids applying truncated size scans.
  • Adds coverage for policy backfill, idempotence, self-healing, and orphan back-references.
  • Updates configuration guidance and removes the obsolete FIFO warning.

Confidence Score: 4/5

The 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

Filename Overview
storage/cleaner.go Adds reconciliation-driven index backfill and fast retries, but startup still completes when reconciliation fails.
storage/storage.go Delegates startup coverage repair to Cleaner while continuing to return storage after Cleaner.Start completes.
storage/backfill_eviction_index_test.go Adds focused successful-path coverage for both policies, idempotence, periodic repair, and orphan back-references.
docs/configuration.md Documents automatic startup backfill and policy-switch behavior.

Reviews (5): Last reviewed commit: "fix: backfill eviction-index coverage du..." | Re-trigger Greptile

Comment thread storage/storage.go Resolved
@ovaistariq
ovaistariq force-pushed the fix/189-backfill-eviction-index branch from 5afac57 to c959e82 Compare August 14, 2026 19:38
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@ovaistariq
ovaistariq force-pushed the fix/189-backfill-eviction-index branch from c959e82 to 41f86e7 Compare August 14, 2026 20:00
@ovaistariq ovaistariq changed the title fix: backfill eviction-index coverage at startup (#189) fix: backfill eviction-index coverage during metadata reconciliation (#189) Aug 14, 2026
@ovaistariq

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in the latest push (force-updated the branch):

  1. Iterator errors are now propagated. reconcileFromMetadata checks it.Err() after the scan; on a truncated scan it skips the size correction (a partial sum would under-size the counter — which weakens eviction, the opposite of the intent) and retries on the next reconcile. This also fixes a latent gap that predated this PR in calculateTotalSize.
  2. Backfill errors are surfaced, not swallowed. Failed batch writes and back-reference scan errors are logged as warn with counts, and…
  3. …coverage is now self-healing. Backfill runs on every capped reconcile, not just startup — so an incomplete backfill (write error, iterator error, crash mid-scan) is completed on a later pass rather than leaving keys unevictable until a restart. The merge-join is O(1) memory / no per-key reads, so this is cheap even when coverage is already complete. Concurrent-put duplicates are reclaimed by the existing eviction-scan validation (FIFO routes through writeFifoIndexEntry to delete rather than duplicate).

The previously startup-only behavior — and its test — are replaced accordingly (TestReconcile_HourlyPathSelfHealsMissingCoverage). make test-storage green.

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.

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/cleaner.go Resolved
@ovaistariq
ovaistariq force-pushed the fix/189-backfill-eviction-index branch from 41f86e7 to 852b694 Compare August 14, 2026 20:18
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@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 totalSizeRecalcInterval gate, so a failed startup backfill left uncovered keys unevictable for up to an hour while enforceDiskLimit ran every tick but couldn't see them.

Now an incomplete pass (a failed batch write, a backrefIt error, or a truncated scan via it.Err()) sets a backfillPending flag, and the cleanup loop re-runs the reconcile every tick while it's set — so uncovered keys become evictable within a cleaner tick instead of up to an hour. A clean pass clears the flag and it reverts to the hourly cadence. This also helps partial recovery: if writes are failing because the disk is near-full, each successful batch makes more keys evictable, enforceDiskLimit frees space, and subsequent batches succeed — the loop converges rather than giving up.

Two bounding notes:

make test-storage green; added an assertion that a clean backfill leaves backfillPending false.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026

Copy link
Copy Markdown

The backfillPending design is sound. A few observations now that the full implementation is visible:

The convergence path holds. writeErrs is per-reconcile-call and batch.Clear() is called after each failed write, so failed entries are re-staged from scratch on the next tick — no stale batch accumulation. The merge-join correctly skips already-indexed keys, so partial progress is preserved across retries.

One subtle nuance in the truncated-scan path: flush() is called before it.Err() is checked, so any batches that accumulated before the truncation are written. On the next pass those entries show up in the backref iterator and are correctly skipped by advanceBackrefTo. That's fine and idempotent.

LRU timestamp granularity: all backfilled LRU keys in a single pass share the same now timestamp, so they land in the same access bucket and evict as a group. That matches the "arbitrary but bounded order" description and is consistent with cleanupOldBuckets behavior (30d threshold, same bucket → all pruned or all kept together). No issue there.

lastSizeRecalc is always updated, even during fast-retry ticks. That prevents the hourly gate from redundantly firing alongside backfillPending, which is correct — the fast-retry already did the work.

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 .greptile/rules.md and .greptile/config.json.

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

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

Comment thread storage/cleaner.go Resolved
Comment thread storage/cleaner.go Resolved
…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]>
@ovaistariq
ovaistariq force-pushed the fix/189-backfill-eviction-index branch from 852b694 to 3f58a3a Compare August 14, 2026 20:29
@ovaistariq

Copy link
Copy Markdown
Contributor Author

Reviewed the latest round of bot findings:

@cursor (Medium, advanceBackrefTo re-stamps indexed keys on a back-ref read error) — valid, fixed. You were right: on a backrefIt error, ValidForPrefix went false and advanceBackrefTo returned "not covered" for every remaining key, so writeFifoIndexEntry would delete and re-stamp their real entries at scan time, rewriting eviction order for the tail. Fixed in 3f58a3a: advanceBackrefTo now returns (covered, ok), distinguishing a genuine end-of-range from an iterator error via it.Err(). On error the caller sets backrefBroken and stops backfilling for the rest of the pass (no re-stamping), and backfillPending triggers a clean full retry on the next tick. (The error path isn't cleanly unit-testable without RocksDB fault injection; the normal covered/uncovered/orphan paths remain covered by the existing tests through the new signature.)

@greptile-apps cleaner.go:80 ("incomplete startup reconciliation accepted") — acknowledged, by design. With the fast-retry, the window is now one cleaner tick (not an hour), and it self-heals. The only case where that one-tick window can actually reach ENOSPC is when the volume is already full so RocksDB can't write the index entries at all — which no retry cadence in this path can fix, and which is exactly the #204 recovery piece (statfs backstop / degraded-open / reserved-headroom escrow), the tracked follow-up. Making Start block or fail on an incomplete pass would risk the crash-loop #204 is about, so I'm intentionally not doing that here.

Two stale findings (filed against superseded commits, already resolved):

  • storage.go:1262 "backfillEvictionIndex" — that method was removed; the backfill is folded into reconcileFromMetadata.
  • cleaner.go:407 "does not retry until hourly" — resolved by the backfillPending fast-retry (retries every tick).

make test-storage green; vet/fmt clean.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026

Copy link
Copy Markdown

The fix in advanceBackrefTo looks correct and well-reasoned. The (covered, ok) return split cleanly separates the two distinct states:

  1. !ok → iterator error: coverage unknown, backrefBroken set, backfill halted — no re-stamping risk
  2. ok && !covered → genuine end-of-range or key missing: safe to backfill

One small observation on cleanupLoop — the fast-retry path still calls calculateTotalSize() rather than reconcileFromMetadata() directly:

if c.backfillPending.Load() || time.Since(lastSizeRecalc) > totalSizeRecalcInterval {
    c.calculateTotalSize()  // this is just a thin wrapper that calls reconcileFromMetadata()

That's fine since calculateTotalSize is just a passthrough now, but backfillPending is only cleared inside reconcileFromMetadata, so the fast-retry does correctly re-run the backfill each tick. No issue — just worth noting the indirection.

The design rationale for leaving Start() non-blocking is sound. Blocking or failing on an incomplete initial pass could create the very crash-loop that #204's recovery path is meant to address, and the one-tick window is acceptable given backfillPending will drive a clean retry immediately.

The stale findings acknowledgment is appreciated — clean accounting.

LGTM on the advanceBackrefTo fix and the overall reconcile approach. Ready to merge pending the #204 follow-ups.

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@ovaistariq
ovaistariq merged commit c23fab7 into main Aug 14, 2026
11 checks passed
@ovaistariq
ovaistariq deleted the fix/189-backfill-eviction-index branch August 14, 2026 22:35
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.10.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

ovaistariq added a commit that referenced this pull request Sep 6, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants