Repository navigation
Conversation
…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 SummaryThis PR decodes the complete prior metadata control fields during Put overwrites and stages reclamation after the replacement metadata commits.
Confidence Score: 3/5This 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
Reviews (1): Last reviewed commit: "fix(storage): reclaim the replaced value..." | Re-trigger Greptile |
| // 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) |
There was a problem hiding this comment.
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:
There was a problem hiding this comment.
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).
| if prev != nil { | ||
| s.stageFileDeletion(prev) |
There was a problem hiding this comment.
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:
There was a problem hiding this comment.
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.
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.
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.
…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]>
cc5d9dd to
9c1c2f4
Compare
On the
|
|
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. |

Fixes #225.
Problem
putLowreplaces the metadata row in place and reads only the previous row'sValueLength:existingValueLengthpullsvalue_lengthoff the wire and discards the rest, so the replaced value's backing bytes never reachstageFileDeletion. Overwriting a key whose value lives in a segment (anything the compactor has already moved out offiles/) therefore leaves the payload dead with no!delete:segment/record at all — andRecompactFragmentedSegmentsreads that record viagetDeleteIndexStatsandcontinues ondeletedEntries == 0, before any fragmentation math. Those bytes are never reclaimed and never even counted.DeleteKeyandevictByIndexboth stage the deletion;Putwas 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
unmarshalValueMessageSkippingDatahelper (so the inline payload is still not copied — the reasonexistingValueLengthwent to the wire in the first place), and stage its reclamation after the batch write commits: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.Writenames raw files with a fresh UUID perPut, 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 (aSEGMENTmetadata row) and overwrites the key; expects 1 entry / 4096 bytes in the segment's delete index. Onmain:0, 0.TestPutOverwrite_ReclaimsReplacedRawFile— the raw-file analogue. Passes onmaintoo (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 ./...instorage/— 11 packages green (go vetclean,gofmtclean).make test-storagewas not usable locally (protoprerequisite needsprotoc-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:kubelet_volume_stats_used_bytes)ocache_disk_usage_bytes)~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.
putLowdecodes 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, sharedParseCreationTimefor 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 inDeleteKey, 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
SEGMENTvalue's delete-indexMergenow rides the sameWriteBatchas 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.
reconcileFromMetadataalready 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 viavalueMessageSegmentRef, still no payload decode — and corrects each finalized segment's delete index byMerge(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.Sscanfname parse intosegment.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.