Skip to content

fix(storage): reclaim the replaced value's bytes on Put overwrite (#225) - #227

Closed
hawkaa wants to merge 2 commits into
tigrisdata:mainfrom
hawkaa:fix/put-overwrite-reclaim
Closed

hawkaa wants to merge 2 commits into
tigrisdata:mainfrom
hawkaa:fix/put-overwrite-reclaim

Conversation

@hawkaa

@hawkaa hawkaa commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #225.

Problem

putLow replaces the metadata row in place and reads only the previous row's ValueLength:

prevSize := s.existingValueLength(key, metaKey)
batch.Put(metaKey, val)

existingValueLength pulls value_length off the wire and discards the rest, so the replaced value's backing bytes never reach stageFileDeletion. Overwriting a key whose value lives in a segment (anything the compactor has already moved out of files/) therefore leaves the payload dead with no !delete:segment/ record at all — and RecompactFragmentedSegments reads that record via getDeleteIndexStats and continues on deletedEntries == 0, before any fragmentation math. 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 this exact call site — the reclamation half was left behind.

Fix

Decode the previous row's control fields with the existing unmarshalValueMessageSkippingData helper (so the inline payload is still not copied — the reason existingValueLength went to the wire in the first place), and stage its reclamation after the batch write commits:

prev := s.existingValue(key, metaKey)
...
if err := s.meta.Handle().Write(wo, batch); err != nil {
    return 0, err
}
if prev != nil {
    s.stageFileDeletion(prev)
}

Ordering matches evictByIndex.commit: the metadata row pointed at those bytes until the write landed, so reclaiming earlier would strand a live row over deleted data if the batch failed.

Self-deletion is not reachable: files.FileManager.Write names raw files with a fresh UUID per Put, and a new segment entry always lands at a new offset, so the replaced value is never the value just written.

Testing

Two new tests in storage:

  • TestPutOverwrite_CreditsReplacedSegmentBytes — plants the post-compaction state (a SEGMENT metadata row) and overwrites the key; expects 1 entry / 4096 bytes in the segment's delete index. On main: 0, 0.
  • TestPutOverwrite_ReclaimsReplacedRawFile — the raw-file analogue. Passes on main too (the compactor queues both raw files once copied), included to pin that the fix does not disturb it and to document that the leak is specifically segment dead-byte accounting.

go test ./... in storage/ — 11 packages green (go vet clean, gofmt clean). make test-storage was not usable locally (proto prerequisite needs protoc-gen-go), so module tests were run directly with the same CGO flags.

Production evidence

TAG v1.17.3 / ocache v1.10.0, TTL=720h, FIFO. Over a 54-hour window with zero cap evictions and zero recompactions on the pod:

pod 0
physical (kubelet_volume_stats_used_bytes) +93.8 GiB
live (ocache_disk_usage_bytes) +59.6 GiB
keys evicted by cap 0
keys expired ~400 / 6 h

~34 GiB of segment payload went dead with no deletions at all — TAG re-Puts the same object keys (revalidation, promoting a range read to a full body). files/ was 124 KiB and RocksDB 449 MiB throughout, so segments account for the whole gap.

Caveat

This prevents future orphaning; it cannot recover bytes already orphaned, which have no delete-index record and no metadata pointing at them and so are indistinguishable from live data. Existing deployments need a cache wipe for the backlog — same caveat as #218.

Independent of #224 (finalized segments reloading with size == 0); both are needed for physical reclaim to work across restarts.


Note

Medium Risk
Changes hot-path Put batching and hourly reconciliation that drives recompaction; mistakes could mis-credit segments (premature or missed recompaction) but logic is additive-only and snapshot-relative to limit regressions.

Overview
Put overwrite no longer leaves dead segment payload invisible to the recompactor. putLow decodes the previous row’s control fields (without copying inline data), merges !delete:segment/ credit in the same batch when the replaced value was segment-backed, and queues replaced raw files only after the metadata write commits—matching delete/eviction ordering.

Self-healing dead-byte accounting runs at the end of the cleaner’s pinned metadata scan: it tallies live references per segment path (wire extract of segment_path + value_length), compares footer entry/payload totals to that liveness and to delete-index credit at the snapshot, and Merges only additive deltas so concurrent credits aren’t stomped. Segments finalized after the snapshot or still open are skipped.

Supporting pieces: valueMessageSegmentRef, Segment.GetDataBytes, shared ParseCreationTime for recompactor age checks, plus tests for overwrite credit, raw-file reclaim, and idempotent reconcile.

Reviewed by Cursor Bugbot for commit cc5d9dd. Bugbot is set up for automated code reviews on this repo. Configure here.


Update (cc5d9dd) — review follow-up

Review raised two residual holes: staging after the commit can lose the only record of the dead bytes, and two overlapping same-key Puts can read the same previous row and leave the intermediate value uncredited. Neither is fixed by a lock — the identical read-then-write shape exists in DeleteKey, TTL cleanup and both eviction scans — so this applies the trade #205 settled for size accounting on this same call site: exact when uncontended, plus a snapshot-relative reconciliation that self-heals the contended and crash cases, with no new hot-path lock.

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. A replaced raw file stays queued after the commit: a lost queue row leaves a file a directory scan can still find (#156), whereas a lost segment credit is invisible forever, and queueing inside the batch would delete bytes a live row still references if the batch failed.

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 via valueMessageSegmentRef, still no payload decode — and corrects each finalized segment's delete index by Merge(derived - credited_at_snapshot). Snapshot-relative and additive-only, so a credit committed during the scan survives and the incremental path is never overruled. Segments that are still open, carry no footer totals, or were created after the snapshot are skipped: their live entries are not in the tally, and crediting them would recompact live data.

Because liveness is derived from the metadata rows themselves, this also recovers dead bytes orphaned before the incremental fix existed — the backlog the original description said needed a cache wipe. Effective reclaim of that backlog additionally requires #224/#226, since the recompactor's ratio divides by the segment size that PR restores.

Also folds the recompactor's inline fmt.Sscanf name parse into segment.ParseCreationTime, now shared with the reconciliation's snapshot guard.

New test TestReconcile_DerivesSegmentDeadBytesFromLiveness: fails without the reconcile (credits 0 instead of 2), asserts a fully live segment receives no credit, and asserts a second pass does not double-count. ./storage/... — 11 packages green.

…grisdata#225)

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 (tigrisdata#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]>
@greptile-apps

greptile-apps Bot commented Aug 18, 2026

Copy link
Copy Markdown

Greptile Summary

This PR decodes the complete prior metadata control fields during Put overwrites and stages reclamation after the replacement metadata commits.

  • Credits displaced segment bytes to the delete index.
  • Queues displaced raw files for asynchronous deletion.
  • Adds segment and raw-file overwrite regression tests.

Confidence Score: 3/5

This PR should not merge until overwrite reclamation remains correct under overlapping same-key Puts and is made durable or recoverable after metadata commit.

The sequential overwrite path is repaired, but concurrent overwrites can orphan an intermediate backing location, and a crash or staging-write failure after metadata commit can still permanently lose the only reclamation record.

Files Needing Attention: storage/storage.go

Important Files Changed

Filename Overview
storage/storage.go Adds overwrite reclamation, but stale previous-row reads and non-atomic best-effort staging still permit permanent orphaning.
storage/put_overwrite_reclaim_test.go Covers sequential segment and raw-file overwrites, but does not exercise overlapping same-key Puts or reclamation-staging failure windows.

Reviews (1): Last reviewed commit: "fix(storage): reclaim the replaced value..." | Re-trigger Greptile

Comment thread storage/storage.go
// The replaced value's backing bytes must also be reclaimed (segment dead-byte
// credit / raw-file deletion), or an overwrite orphans them with no
// `!delete:segment/` record and the recompactor can never see them.
prev := s.existingValue(key, metaKey)

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 Concurrent overwrites orphan intermediate bytes

If two Puts for the same non-inline key overlap after reading the original metadata, both stage reclamation for that original location even though the later commit also displaces the first Put's backing location, causing the intermediate raw file or segment entry to remain permanently orphaned.

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.

Real, and addressed the way #205 settled the same shape on this call site rather than with a lock — cc5d9dd.

The read-then-write window is not specific to reclamation: DeleteKey, TTL cleanup and both eviction scans all read a row and then act on it outside any lock, so serializing putLow alone would not close it, and serializing all five would put a per-key lock on the write hot path. #205 chose exactness in the uncontended case plus a snapshot-relative reconciliation that self-heals the contended and crash cases; this now does the same.

reconcileFromMetadata already scans every metadata row on a pinned snapshot, so it also tallies per-segment live entries/payload bytes (O(segments) memory, one extra wire field per row, still no payload decode) and corrects each finalized segment's delete index by Merge(derived - credited_at_snapshot). So the intermediate value your scenario orphans is discovered by liveness — nothing references those bytes, so they show up as dead on the next pass — instead of depending on the incremental credit being exact. Corrections are snapshot-relative and additive-only, so a credit committed during the scan survives and the incremental path is never overruled.

Residual window is now one reconcile interval of unclaimed credit for the contended case, not a permanent leak. Test: TestReconcile_DerivesSegmentDeadBytesFromLiveness (fails without the reconcile, and asserts a fully live segment gets no credit and that a second pass does not double-count).

Comment thread storage/storage.go Outdated
Comment on lines +1206 to +1207
if prev != nil {
s.stageFileDeletion(prev)

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 Reclamation record is not durable

When the process exits after the metadata commit or the subsequent deletion-queue Put/delete-index Merge fails, stageFileDeletion cannot report the failure or retry it, causing the displaced raw file or segment bytes to lose their only reclamation record permanently.

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.

Fixed for the case where the loss is permanent — cc5d9dd.

A replaced segment value's delete-index Merge now rides the same WriteBatch as the metadata row that supersedes it, so the credit and the supersede commit atomically; there is no window in which the row is replaced but the credit is missing.

A replaced raw file deliberately stays queued after the commit. The asymmetry is the recoverability of each failure: a lost queue row leaves a file in files/ that a directory scan can still find (#156), while a lost segment credit is invisible forever — the segment looks identical to a live one. Queueing the file inside the batch would also mean deleting bytes a live metadata row still references if the batch failed, which is the ordering evictByIndex.commit exists to avoid.

And for anything still missed — crash between the two, or the concurrent case in the sibling thread — the new liveness reconciliation re-derives the segment's dead bytes from the metadata rows themselves, so the delete index is no longer the only record.

@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 cc5d9dd. Configure here.

Comment thread storage/storage.go Resolved
…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
hawkaa force-pushed the fix/put-overwrite-reclaim branch from cc5d9dd to 9c1c2f4 Compare August 18, 2026 10:51
@hawkaa

hawkaa commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

On the build failure in the previous run ([lru] Protection semantics)

It was read-old survived=2 against a >= 3 threshold in tests/e2e/eviction_test.sh — the check #192 was already written to stabilise. I did not want to assume flake, so I pinned down whether this commit can influence that test at all:

  • The suite creates no segments. It runs with -threshold 1000 -compact-threshold 1500 and 2–3 KB values, and putLow queues a value for compaction only when bytesWritten > inlineThreshold && bytesWritten <= compactThreshold. Every value in the suite is above both, so it stays a raw file for life and no segment is ever built. Both segment paths this commit adds — the in-batch delete-index Merge and reconcileSegmentDeleteIndex — are therefore unreachable in that run.
  • The one code path the suite does exercise is the reconciliation scan's switch from valueMessageValueLength to valueMessageSegmentRef, which feeds totalSize and so could in principle move the eviction threshold. Now covered by TestValueMessageSegmentRef_MatchesFullDecode, a differential test against a full proto.Unmarshal across empty / inline-64 KiB / raw-file / segment / segment-with-expiry+checksum shapes, plus the malformed case. It agrees exactly, so the total is unchanged.
  • Locally the suite passes — 3 consecutive runs of tests/e2e/eviction_test.sh on this branch, lru and fifo protection green in all three.

The previous run of this same branch (before this commit) passed the same job, and main has independent failures of this workflow today, so I read the one failure as the known CI timing sensitivity of that assertion rather than a regression here. Happy to be corrected if you have data suggesting otherwise — a re-run of the job would settle it, and I cannot trigger one from a fork.

Also in the amended commit

  • Tightened the reconciliation guard. Previously it skipped segments by creation stamp; now it skips any segment whose file mtime is after the snapshot. Creation time does not tell you when writing stopped, so a segment created before the snapshot but finalized during the scan could have had entries the scan never saw counted as dead — an over-credit that would recompact live data. mtime closes that, and the next pass (whose snapshot covers those writes) corrects the segment.
  • Dropped the segment.ParseCreationTime helper and the recompactor refactor that came with it. With the mtime guard the helper has no user here, and storage/compaction/recompactor.go and storage/segment/builder.go are now untouched by this PR.

@ovaistariq

Copy link
Copy Markdown
Contributor

Thank you for this — both the issue reports and the PR are exceptional, and the core fix is exactly right. We've carried this forward in #228: your two commits land there unchanged (authorship preserved), including the atomic in-batch segment credit, which is a genuinely nice refinement.

The one change is to the reconciliation pass. Reviewing it against the compactor's commit discipline surfaced a window it can't be safe in: the file compactor finalizes destination segments mid-run but commits all its metadata merges once at end-of-run — under the new compaction I/O budget that gap spans minutes — so an hourly reconcile snapshot landing inside it derives a fully-live segment as fully dead, and the additive-only clamp makes that credit permanent. Racing same-key Puts similarly leave over-credit that an additive pass can never withdraw. #228 moves the pass to a single synchronous call at startup, before any background worker runs: that window is single-threaded, so the rewrite can be absolute (over-credit withdrawn, orphan rows removed) while still healing the pre-existing backlog you measured — meaning a restart, not a wipe, recovers it.

Closing this in favor of #228 — please take a look there if you get a chance; review from you would be very welcome. #226 is already merged.

@ovaistariq ovaistariq closed this Aug 18, 2026
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.

storage: Put over an existing key orphans the replaced value's segment bytes with no delete-index credit (invisible to the recompactor)

2 participants