Skip to content

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

Merged
ovaistariq merged 6 commits into
mainfrom
fix/put-overwrite-reclaim-v2
Aug 19, 2026
Merged

ovaistariq merged 6 commits into
mainfrom
fix/put-overwrite-reclaim-v2

Conversation

@ovaistariq

@ovaistariq ovaistariq commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #227 (fixes #225), building directly on @hawkaa's work — the first two commits are theirs, cherry-picked with authorship intact.

What this PR now carries

  • putLow decodes the previous row (wire-level, no inline-payload copy) and reclaims the replaced value: segment credit merged atomically in the same batch as the row replacement (a crash cannot orphan the credit), raw files queued after commit
  • Regression tests for both overwrite paths, plus the wire-extractor tests
  • Segment.GetDataBytes and the segment-ref wire extractor (used by the follow-up below)

What moved out (design evolution)

The scan-based delete-index reconciliation (both the original hourly version and the interim startup-only version) is dropped from this PR after design review: the recompactor already derives exact per-segment liveness from a segment's own entry keys + metadata point lookups, so a lazy per-segment audit inside the recompaction loop supersedes any global metadata scan — no extra startup pass, no restart dependence, continuous healing of both under- and over-credit, and the existing per-entry CRC32 enables an integrity-scrub tier that can safely invalidate-and-refetch corrupted entries (cache upstream is authoritative). That lands as a follow-up PR with an RFC.

Merging this PR alone fixes the ongoing overwrite leak (#225). Historical backlog healing arrives with the audit follow-up. Pairs with #226 (merged).

🤖 Generated with Claude Code

https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9


Note

Cursor Bugbot is generating a summary for commit d4364dd. Configure here.

hawkaa and others added 3 commits August 18, 2026 10:04
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]>
…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]>
… background workers

The scan-derived reconciliation is only sound when nothing runs
concurrently: the file compactor finalizes destination segments mid-run
while its metadata batch commits only at end-of-run (a window that spans
minutes under the compaction I/O budget), so an hourly reconcile
snapshot inside that window derives a fully-live segment as fully dead —
and additive-only corrections make the false credit permanent. Racing
same-key Puts similarly leave over-credit no additive pass can withdraw,
and a reconcile racing the recompactor can resurrect the index row of a
segment that no longer exists.

Move the pass to a single synchronous call in NewStorageWithConfig,
after metadata and segments load and before the compactor, cleaner, or
any request path starts. That single-threaded window makes an absolute
rewrite safe: over-credit is withdrawn, under-credit is filled in
(including backlog orphaned before the incremental path existed), and
index rows for segments no longer on disk are removed. Steady-state
drift between restarts stays bounded — the recompactor re-verifies every
entry against metadata before copying — and is corrected at the next
restart.

The hourly cleaner scan returns to summing sizes only; the atomic
Put-overwrite credit from the previous commits is unchanged.

Co-authored-by: Håkon Åmdal <[email protected]>

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[email protected]>
efirs
efirs previously approved these changes Aug 18, 2026
@greptile-apps

greptile-apps Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR reclaims backing storage when a Put replaces an existing value.

  • Atomically credits replaced segment payload bytes in the metadata replacement batch.
  • Queues replaced raw files for asynchronous deletion after the replacement commits.
  • Adds wire-level metadata extraction, segment payload accounting access, and overwrite regression tests.

Confidence Score: 5/5

The PR appears safe to merge because no blocking failure remains within the scope of the prior review thread.

The startup reconciliation associated with the previous finding was dropped, so its partial-state error path no longer exists at the current head.

Important Files Changed

Filename Overview
storage/storage.go Adds overwrite-time segment credit and post-commit raw-file deletion; the previously reported startup reconciliation pass is no longer present.
storage/segment/segment.go Exposes synchronized access to a segment’s total payload-byte count.
storage/value_wire.go Adds a wire-level extractor for segment path and value length without copying inline payload data.
storage/put_overwrite_reclaim_test.go Covers reclamation of replaced segment bytes and raw files.
storage/value_wire_test.go Verifies segment-reference extraction across stored-value shapes and malformed input.

Reviews (3): Last reviewed commit: "refactor(storage): drop the scan-based r..." | Re-trigger Greptile

Comment thread storage/storage.go Resolved
Comment thread storage/storage.go Resolved
A truncated metadata scan yields an incomplete live tally, and an
absolute rewrite from partial knowledge would mark unseen live entries
dead — persisted over-credit and pointless recompaction until the next
successful restart. Check both iterators' Err() and abort the pass on
any failure; a failed batch write likewise stops further corrections
(each committed batch holds whole per-segment Delete+Merge corrections,
so partial application across segments is individually consistent).
Doing nothing is safe; rewriting from a short scan is not. Flagged by
Greptile and Cursor Bugbot.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[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.

Reviewed by Cursor Bugbot for commit 1faba50. Configure here.

Comment thread storage/storage.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

ovaistariq and others added 2 commits August 18, 2026 10:36
The shared batch rarely reaches the flush threshold, so aborting on a
delete-index scan error was discarding already-derived per-segment
corrections that do not depend on that scan. Commit them between the
two phases; the abort then skips only orphan cleanup. Flagged by
Cursor Bugbot.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[email protected]>
… recompaction loop

Design review concluded the metadata-scan approach is the wrong shape:
the recompactor already derives exact per-segment liveness from the
segment's own entry keys plus point lookups, so a lazy per-segment
audit in the recompaction loop supersedes any global scan (startup or
hourly) — no third metadata pass, no restart dependence, continuous
healing, and the entry-header CRC32 enables an integrity-scrub tier.
That lands as a follow-up PR with an RFC; this PR now carries only the
overwrite-reclaim fix and its atomic-credit refinement.

The wire-level segment-ref extractor and Segment.GetDataBytes stay:
both are tested and the audit follow-up uses them.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[email protected]>
@ovaistariq ovaistariq changed the title fix(storage): reclaim replaced bytes on Put overwrite, with startup-only index reconciliation fix(storage): reclaim the replaced value's bytes on Put overwrite Aug 18, 2026
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@ovaistariq
ovaistariq merged commit cfc3cf4 into main Aug 19, 2026
13 checks passed
@ovaistariq
ovaistariq deleted the fix/put-overwrite-reclaim-v2 branch August 19, 2026 00:15
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.11.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

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 over an existing key orphans the replaced value's segment bytes with no delete-index credit (invisible to the recompactor)

4 participants