Skip to content

fix: subtract the replaced value's size when Put overwrites a key (#203) - #205

Merged
ovaistariq merged 3 commits into
tigrisdata:mainfrom
hawkaa:fix/put-overwrite-size-accounting
Aug 14, 2026
Merged

ovaistariq merged 3 commits into
tigrisdata:mainfrom
hawkaa:fix/put-overwrite-size-accounting

Conversation

@hawkaa

@hawkaa hawkaa commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #203.

Problem

putLow overwrites the metadata row in place (batch.Put(metaKey, val)) while Put unconditionally calls s.notifyPut(bytesWritten). Nothing reads the row being replaced, so on every overwrite the old ValueLength stays in the cleaner's totalSize forever. The only correction is calculateTotalSize(), which runs once at startup.

Consequence: totalSize (and ocache_disk_usage_bytes / ocache_disk_usage_ratio) inflates monotonically, and enforceDiskLimit chases bytes that do not exist — once the phantom excess passes MaxDiskUsage, eviction deletes live entries every pass until the cache is empty and keeps deleting whatever is written next. The issue has the production numbers (running gauge 211 GiB vs. a 1.4 GB rescan on the same volume).

Fix

Issue fixes 1 and 2, in three commits.

1. Subtract the replaced row's size (5aa7ec9). putLow returns the ValueLength of the row it replaced (0 for a new key) and Put applies the net delta, on both the inline and raw-file paths. That makes totalSize a fixpoint under repeated Puts of the same key.

The previous-row lookup reuses the shared, process-lifetime ReadOptions that the FIFO back-reference read already uses (renamed fifoBackrefReadOpts -> putPointReadOpts, since both hot-path point reads now share it), so the hot path keeps a single point read per Put and no per-write native allocation. Under FIFO this is the same access pattern the backref lookup already had.

2. Re-derive the total periodically (41eb7f1). The cleaner re-runs calculateTotalSize() hourly, before enforceDiskLimit, mirroring the existing accessBucketCleanupInterval gate. This covers the two drift sources the delta alone cannot: a crash between the metadata batch write and the accounting update, and two concurrent Puts of the same key both reading the same previous row (raised by Greptile — the thread has why exactness there would mean locking DeleteKey, TTL cleanup and both eviction scans too, and would still leave #188's orphaned raw file on that same race).

3. Make that rescan safe under live traffic (077c801). calculateTotalSize used to Store its scanned sum, which is fine at startup but on a live run stomps the delta of anything committed during the scan (raised by Bugbot and Greptile). It now pins the scan to a RocksDB snapshot and applies Add(scanned - tracked), with tracked read after the snapshot — so a write the scan cannot see keeps its accounting. It also logs the drift it corrected, which is the signal that would have surfaced this leak in production.

Test

storage/put_overwrite_size_test.go — TestPut_Overwrite_TotalSizeStaysExact: 10 overwrites of one inline key and one large raw-file key, asserts the running total equals the exact content size, that it is a fixpoint against a full rescan (which is what a restart does), and that injected drift is absorbed by a rescan instead of persisting.

  • Before: expected: 9192, actual: 91920 (10x inflation, both paths).
  • After: passes; full make test-storage, make test-server and make test-e2e-eviction green locally (built against the bundled rocksdb-static 10.4.2 artifact).

Deliberately not in this PR

Issue fix 3 — statfs-based cap enforcement as an ENOSPC backstop — is a separate, larger call and is left out to keep this diff to the root cause.

Also unchanged: an LRU overwrite still leaves an orphan access-bucket entry (already noted in storage/eviction_policy_test.go and #188), and ocache_keys_total still has no writer.

…grisdata#203)

putLow overwrote the metadata row in place while Put unconditionally added
the new value's bytes to the cleaner's totalSize, so every overwrite leaked
the old value's ValueLength into the tracked total. The only correction was
calculateTotalSize() at startup, so the gauge (and enforceDiskLimit's target)
inflated monotonically for the life of the process: eviction then chased
bytes that no longer existed and deleted live entries until the cache was
empty.

putLow now returns the ValueLength of the row it replaced (0 for a new key)
and Put applies the net delta, making totalSize a fixpoint under repeated
Puts of the same key on both the inline and raw-file paths. The lookup reuses
the shared process-lifetime ReadOptions that the FIFO back-reference read
already uses, so the hot path keeps one point read and no per-write native
allocation.

Signed-off-by: Håkon Åmdal <[email protected]>
@hawkaa
hawkaa force-pushed the fix/put-overwrite-size-accounting branch from cd947f7 to 5aa7ec9 Compare August 14, 2026 05:36
@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR corrects overwrite accounting by subtracting the replaced metadata row’s value length and adds an hourly metadata rescan intended to bound residual drift.

  • Applies net size deltas for inline and raw-file overwrite paths.
  • Reuses shared RocksDB read options for Put-time point reads.
  • Adds overwrite regression coverage and periodic total-size reconciliation.

Confidence Score: 4/5

The PR is not yet safe to merge because periodic reconciliation can itself corrupt live size accounting during concurrent Put or DeleteKey operations.

The cleaner scans into a local total and then stores it without coordinating with concurrent incremental updates, so an in-flight request delta can be discarded and disk-limit enforcement can act on an incorrect value for up to another reconciliation interval.

Files Needing Attention: storage/cleaner.go

Important Files Changed

Filename Overview
storage/storage.go Put now reads the replaced row’s ValueLength and applies a net accounting delta on both storage paths.
storage/cleaner.go The hourly reconciliation can overwrite concurrent request-path accounting deltas before disk-limit enforcement.
storage/put_overwrite_size_test.go The test covers sequential inline and raw-file overwrites, but not overlap between recalculation and live mutations.

Reviews (2): Last reviewed commit: "fix: re-derive the tracked total size pe..." | Re-trigger Greptile

Comment thread storage/storage.go Resolved
…g drift

The incremental total is exact in the common case, but two writers can still
skew it: a crash between the metadata batch write and the accounting update,
or two concurrent Puts of the same key both reading the same previous row.
Re-running the startup metadata scan on a cleaner tick (hourly) keeps any such
drift bounded and self-healing instead of accumulating for the process
lifetime, and it runs before enforceDiskLimit so enforcement acts on the
corrected total.

Signed-off-by: Håkon Åmdal <[email protected]>

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

Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 41eb7f1. Configure here.

Comment thread storage/cleaner.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor

@greptile

Comment thread storage/cleaner.go
case <-ticker.C:
// Correct any accumulated drift before enforcement acts on the total.
if time.Since(lastSizeRecalc) > totalSizeRecalcInterval {
c.calculateTotalSize()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Recalculation discards concurrent deltas

If a Put or DeleteKey updates totalSize while the hourly metadata scan is running, calculateTotalSize unconditionally stores its locally accumulated result over that concurrent delta. The resulting overcount or undercount persists for up to another hour, causing disk-limit enforcement to evict live entries unnecessarily or permit usage beyond the configured cap.

Knowledge Base Used:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Seems better than nothing though, this race condition is bounded because it will self correct every hour?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Yes, exactly. The race is bounded — calculateTotalSize does an atomic Store which can stomp a concurrent delta, but at most that lost delta persists until the next hourly recalc. The system won't spiral like the original bug (monotonically inflating forever).

The PR description already explicitly acknowledges this tradeoff, and given that fixing it precisely would require locking across DeleteKey, TTL cleanup, and both eviction scans, the hourly self-healing scan is the right call here. I'm satisfied with this approach.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 077c801 rather than left bounded: the scan is now pinned to a RocksDB snapshot and applied as totalSize.Add(scanned - tracked), where tracked is read after the snapshot is taken. Any write the scan cannot see therefore has its incremental delta applied after tracked was sampled, so the delta survives the correction instead of being stomped by a Store.

Residual window is now a write whose RocksDB commit and its UpdateSize both fall between the snapshot and the Load (microseconds), rather than anything committed during the whole scan. The rescan also logs the drift it corrected, which is the signal that would have surfaced the original leak.

Startup behaviour is unchanged: tracked is 0 and there is no traffic, so the correction equals the old store.

calculateTotalSize stored its scanned sum, which was safe at startup (no
traffic) but not on the periodic run: a Put or delete committing during the
scan had its incremental delta stomped, and the resulting skew persisted until
the next pass.

The scan is now pinned to a RocksDB snapshot and applied as a delta against
the counter value read after that snapshot was taken, so writes the scan
cannot see keep their accounting. The scan also logs the drift it corrected,
which is the signal that would have exposed the overwrite leak.

Signed-off-by: Håkon Åmdal <[email protected]>
@ovaistariq

Copy link
Copy Markdown
Contributor

Looks good

@ovaistariq
ovaistariq merged commit a0b4846 into tigrisdata:main Aug 14, 2026
12 checks passed
ovaistariq added a commit that referenced this pull request Aug 14, 2026
…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: a
backfill left incomplete — by a batch write error, an 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 an hourly 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 (applying a partial sum would under-size
the counter and weaken the very eviction this protects) and retry on the next
reconcile; 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, which is the invariant that matters.
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 (it warned about exactly the state
backfill now fixes), 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; 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 added a commit that referenced this pull request Aug 14, 2026
…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 added a commit that referenced this pull request Aug 14, 2026
…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 added a commit that referenced this pull request Aug 14, 2026
…189) (#209)

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.
@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 📦🚀

hawkaa added a commit to hawkaa/ocache that referenced this pull request Aug 18, 2026
…ness (tigrisdata#225)

Review flagged two residual holes in the overwrite fix: staging the
reclamation after the metadata commit can lose the only record of the dead
bytes, and two overlapping Puts of one key can read the same previous row and
leave the intermediate value uncredited. Locking the write path is not the
answer — the same read-then-write shape exists in DeleteKey, TTL cleanup and
both eviction scans, and tigrisdata#205 settled that trade for size accounting: exact in
the uncontended case, plus a snapshot-relative reconciliation that self-heals
the contended and crash cases, with no new hot-path lock.

Apply that pattern here.

Atomic where loss is permanent: a replaced SEGMENT value's delete-index merge
now rides the same WriteBatch as the metadata row that supersedes it, so the
credit cannot be lost between them. A replaced raw file stays queued after the
commit — a lost queue row leaves a file a directory scan can still find,
whereas a lost segment credit is invisible forever.

Self-healing: reconcileFromMetadata already scans every metadata row on a
pinned snapshot, so it now also tallies per-segment live entries and payload
bytes (O(segments) memory, one extra wire field per row, no payload decode) and
corrects each finalized segment's delete index by
Merge(derived - credited_at_snapshot). Corrections are snapshot-relative and
additive-only, so a credit committed during the scan survives and the
incremental path is never overruled. Segments still open, without footer
totals, or created after the snapshot are skipped: their live entries are not
in the tally and crediting them would recompact live data.

This also recovers dead bytes orphaned before the incremental fix existed,
which have no delete-index record and were otherwise unreclaimable without
wiping the cache.

Signed-off-by: Håkon Åmdal <[email protected]>
hawkaa added a commit to hawkaa/ocache that referenced this pull request Aug 18, 2026
…ness (tigrisdata#225)

Review flagged two residual holes in the overwrite fix: staging the
reclamation after the metadata commit can lose the only record of the dead
bytes, and two overlapping Puts of one key can read the same previous row and
leave the intermediate value uncredited. Locking the write path is not the
answer — the same read-then-write shape exists in DeleteKey, TTL cleanup and
both eviction scans, and tigrisdata#205 settled that trade for size accounting: exact in
the uncontended case, plus a snapshot-relative reconciliation that self-heals
the contended and crash cases, with no new hot-path lock.

Apply that pattern here.

Atomic where loss is permanent: a replaced SEGMENT value's delete-index merge
now rides the same WriteBatch as the metadata row that supersedes it, so the
credit cannot be lost between them. A replaced raw file stays queued after the
commit — a lost queue row leaves a file a directory scan can still find,
whereas a lost segment credit is invisible forever.

Self-healing: reconcileFromMetadata already scans every metadata row on a
pinned snapshot, so it now also tallies per-segment live entries and payload
bytes (O(segments) memory, one extra wire field per row, no payload decode) and
corrects each finalized segment's delete index by
Merge(derived - credited_at_snapshot). Corrections are snapshot-relative and
additive-only, so a credit committed during the scan survives and the
incremental path is never overruled. Segments still open, without footer
totals, or created after the snapshot are skipped: their live entries are not
in the tally and crediting them would recompact live data.

This also recovers dead bytes orphaned before the incremental fix existed,
which have no delete-index record and were otherwise unreclaimable without
wiping the cache.

Signed-off-by: Håkon Åmdal <[email protected]>
ovaistariq pushed a commit that referenced this pull request Aug 19, 2026
putLow replaces the metadata row in place and reads only the previous row's
ValueLength (existingValueLength) for size accounting, so the value that row
pointed at is never staged for reclamation. Overwriting a key whose value
lives in a segment therefore leaves the payload dead with no !delete:segment/
record at all: the recompactor reads that record via getDeleteIndexStats and
continues when deletedEntries == 0, so those bytes are never reclaimed and
never even counted. DeleteKey and evictByIndex both stage the deletion; Put
was the one mutation path that dropped it (#205 fixed the accounting half of
the same call site).

Decode the previous row's control fields with the existing wire helper (the
inline payload is still not copied) and stage its reclamation after the batch
write commits — the ordering evictByIndex.commit uses, so a failed write never
strands a live metadata row over deleted bytes. Raw-file paths are UUIDs and a
new segment entry always lands at a fresh offset, so the replaced value can
never be the value just written.

Observed on a TAG fleet (TTL 720h, FIFO): over 54 hours with zero cap
evictions and zero recompactions, physical usage grew 93.8 GiB while live
bytes grew 59.6 GiB — ~34 GiB of segment payload went dead purely from
re-Puts of existing keys.

Signed-off-by: Håkon Åmdal <[email protected]>
ovaistariq pushed a commit that referenced this pull request Aug 19, 2026
…ness (#225)

Review flagged two residual holes in the overwrite fix: staging the
reclamation after the metadata commit can lose the only record of the dead
bytes, and two overlapping Puts of one key can read the same previous row and
leave the intermediate value uncredited. Locking the write path is not the
answer — the same read-then-write shape exists in DeleteKey, TTL cleanup and
both eviction scans, and #205 settled that trade for size accounting: exact in
the uncontended case, plus a snapshot-relative reconciliation that self-heals
the contended and crash cases, with no new hot-path lock.

Apply that pattern here.

Atomic where loss is permanent: a replaced SEGMENT value's delete-index merge
now rides the same WriteBatch as the metadata row that supersedes it, so the
credit cannot be lost between them. A replaced raw file stays queued after the
commit — a lost queue row leaves a file a directory scan can still find,
whereas a lost segment credit is invisible forever.

Self-healing: reconcileFromMetadata already scans every metadata row on a
pinned snapshot, so it now also tallies per-segment live entries and payload
bytes (O(segments) memory, one extra wire field per row, no payload decode) and
corrects each finalized segment's delete index by
Merge(derived - credited_at_snapshot). Corrections are snapshot-relative and
additive-only, so a credit committed during the scan survives and the
incremental path is never overruled. Segments still open, without footer
totals, or created after the snapshot are skipped: their live entries are not
in the tally and crediting them would recompact live data.

This also recovers dead bytes orphaned before the incremental fix existed,
which have no delete-index record and were otherwise unreclaimable without
wiping the cache.

Signed-off-by: Håkon Åmdal <[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.

storage: Put on an existing key leaks the old value's size into totalSize — cap enforcement runs against phantom bytes and evicts the whole cache

3 participants