Repository navigation
fix(storage): reclaim the replaced value's bytes on Put overwrite - #228
Conversation
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]>
Greptile SummaryThe PR reclaims backing storage when a Put replaces an existing value.
Confidence Score: 5/5The 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
Reviews (3): Last reviewed commit: "refactor(storage): drop the scan-based r..." | Re-trigger Greptile |
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]>
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 1faba50. Configure here.
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]>
|
🎉 This PR is included in version 1.11.0 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |

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
putLowdecodes 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 commitSegment.GetDataBytesand 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.