Skip to content

feat(storage): walk-gated recompaction (RFC-009) - #229

Merged
ovaistariq merged 8 commits into
mainfrom
feat/segment-audit-scrub
Aug 19, 2026
Merged

ovaistariq merged 8 commits into
mainfrom
feat/segment-audit-scrub

Conversation

@ovaistariq

@ovaistariq ovaistariq commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Implements RFC-009 (included). Design evolved through review: a scan-based reconciliation and then a separate audit-corrects-index mechanism were both prototyped and rejected in favor of this simpler unification.

The change

Recompaction is no longer gated by the delete index. Each pass walks a budget of candidate segments (default 8/pass, hint-prioritized, staleness-rotated) and derives dead bytes from ground truth — footer totals minus the entries whose metadata rows still point at the segment, the exact liveness test recompactSegment already applies before copying. The derivation gates the rewrite directly, in the same pass.

The delete index demotes to a prioritization hint. Its credits order which segments get walked first (hot churn reclaims fast; rotation covers the rest in hours). No correctness depends on it anymore: the historical orphan backlog (the ORD and customer ENOSPC incidents), credits lost to any future bug, and inflated credits from racing writers are all absorbed by the walk within one rotation. A wrong hint costs one ~ms walk instead of leaked or rewritten data.

Why walks are cheap enough to be the gate: only objects above the 64 KiB inline threshold reach segments, so a 256 MiB segment holds ≤ ~4,096 entries (typically ~256 at TAG's 1 MiB blocks) — a header-hop plus that many point lookups is single-digit milliseconds.

Also in this PR

  • Strict derivation failure handling: only ErrMetadataNotFound counts dead; transient lookup failures abort the walk — and the same fix is applied to recompactSegment's copy loop, where the pre-existing error-as-deleted pattern could drop a live entry (Bugbot finding, data-loss-adjacent). Truncated segments are caught by a walk-vs-footer cross-check (the iterator reads truncation as clean EOF).
  • Atomic hint credits: DeleteKey (staged before commit — wrong direction) and the TTL cleaner (staged after — crash window) now merge segment credit in the same batch as the metadata delete, matching fix(storage): reclaim the replaced value's bytes on Put overwrite #228's putLow discipline.
  • Deferred by design: the CRC scrub tier (headers already store per-entry CRC32s; the walk is its natural host later — see RFC Future Work).

Testing

  • TestWalkGatedRecompaction_ReclaimsWithoutAnyCredit — the headline: dead bytes with no credit at all are derived and reclaimed
  • TestWalkGatedRecompaction_IgnoresInflatedHint — a bogus hint cannot rewrite a live segment
  • TestWalk_AbortsOnTruncatedSegment, TestWalk_IntervalBoundsRewalks
  • Full existing recompaction suite passes unchanged under the new gate; ./storage/... 11 packages green, vet clean

Pairs with #226 + #228 (merged): together they restore end-to-end dead-byte reclaim with no dependence on incremental-counter perfection.

🤖 Generated with Claude Code

https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9


Note

Cursor Bugbot is generating a summary for commit 3731a07. Configure here.

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 replaces delete-index-gated recompaction with rate-limited segment liveness walks and uses delete-index credits only for prioritization.

  • Derives dead bytes by comparing segment entries with authoritative metadata.
  • Commits compactor metadata before segment finalization and makes delete credits atomic with metadata deletion.
  • Publishes recompacted metadata through a conditional merge so concurrent replacements win.
  • Adds metrics, RFC documentation, and regression coverage for walk gating, truncation, publication ordering, and metadata CAS behavior.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; the previous audit invalidation races are no longer reachable, and the recompaction metadata CAS preserves concurrent replacements while safely removing the old segment.

Important Files Changed

Filename Overview
storage/compaction/recompactor.go Recompaction now walks eligible segments to derive fragmentation and conditionally publishes copied entries without clobbering concurrent replacements.
storage/compaction/walker.go Adds strict, rate-limited liveness derivation with metadata-error and truncated-segment safeguards.
storage/merge/operator.go Extends metadata CAS from raw-to-segment migration to segment-to-segment recompaction while preserving newer metadata.
storage/compaction/compactor.go Publishes metadata at segment rollover before finalization and queues source deletion only after the corresponding commit.
storage/storage.go Makes segment deletion credits atomic with foreground metadata deletion.
storage/cleaner.go Makes TTL-driven segment credits atomic with expired metadata deletion while retaining post-commit raw-file cleanup.
storage/compaction/walker_test.go Covers uncredited dead-byte reclamation, inflated hints, truncation handling, and walk-interval behavior.
docs/rfcs/RFC-009-walk-gated-recompaction.md Documents the walk-gated recompaction design, ordering invariants, costs, and failure handling.

Reviews (6): Last reviewed commit: "fix(storage): publish compaction metadat..." | Re-trigger Greptile

Comment thread storage/compaction/auditor.go Resolved
Comment thread storage/compaction/auditor.go Resolved
Base automatically changed from fix/put-overwrite-reclaim-v2 to main August 19, 2026 00:15
@ovaistariq
ovaistariq dismissed efirs’s stale review August 19, 2026 00:15

The base branch was changed.

@ovaistariq
ovaistariq force-pushed the feat/segment-audit-scrub branch from 95aebc4 to 8f5ef1f Compare August 19, 2026 00:16
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/compaction/auditor.go Resolved
@ovaistariq
ovaistariq force-pushed the feat/segment-audit-scrub branch from 24b927d to 654136d Compare August 19, 2026 01:48
@ovaistariq ovaistariq changed the title feat(storage): segment audit and scrub in the recompaction loop (RFC-009) feat(storage): walk-gated recompaction (RFC-009) Aug 19, 2026
Comment thread storage/compaction/recompactor.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/compaction/recompactor.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/compaction/recompactor.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

ovaistariq and others added 7 commits August 18, 2026 21:54
The delete index — an incremental counter every historical credit bug
corrupted permanently — no longer decides recompaction. Each pass walks
a budget of candidate segments (hint-prioritized, staleness-rotated) and
derives dead bytes from ground truth: footer totals minus the entries
whose metadata rows still point at the segment, the same liveness test
recompactSegment applies before copying. The derivation gates the
rewrite directly; the index is only a prioritization hint, so a wrong
hint costs one ~ms walk instead of leaked or rewritten data. Walks are
cheap by construction: only objects above the 64 KiB inline threshold
reach segments, capping entries per segment at ~4,096 (typically ~256).

Strict derivation failure handling: only ErrMetadataNotFound counts
dead (transient lookup failures abort the walk — also applied to
recompactSegment's copy loop, where the old error-as-deleted pattern
could drop a live entry); the iterator reads truncation as clean EOF,
so the walk cross-checks its entry count against the footer and aborts
on damage. Orphaned dead bytes with no credit at all — the invisible
case behind the ORD and customer ENOSPC incidents — are reclaimed
within one rotation.

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

DeleteKey staged reclamation BEFORE its delete committed (a failed
write left credit and a queued file for a still-live row) and the TTL
cleaner staged it after (a crash between commit and staging lost the
credit forever). Both now merge a segment value's delete-index credit
in the SAME batch as the metadata delete, while raw files keep
post-commit queueing. Credits are prioritization hints under RFC-009,
so this is a quality-of-ordering fix, not a correctness dependency.

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

Three refinements from CI and review:

- Hint growth since a segment's last walk bypasses the re-walk interval,
  so credited deletions are re-derived on the very next pass (the old
  gate's reactivity); the interval only bounds re-walks when the hint is
  unchanged. Fixes the integration recompaction tests, where deletions
  after a first clean walk waited out the full interval.
- A derived-fragmented segment whose rewrite fails is retried next pass
  instead of being parked for the interval — reclaim matters most under
  the disk pressure that makes rewrites fail (Cursor Bugbot).
- Walk reads draw from the shared compaction I/O limiter (one ~4 KiB
  page cost per entry visited — header and key share a page), so walks,
  compaction, and recompaction together stay under the configured
  budget and a burst of small walk reads is paced instead of landing as
  an IOPS spike.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[email protected]>
With walk reads charged to the shared compaction I/O limiter, the count
cap was redundant for I/O safety: even a whole-fleet pass (first after
restart, or hourly re-expiry) is paced by the budget rather than bursty,
and hint-priority ordering means reclaim-worthy segments are handled
first regardless. Walk volume is governed by two mechanisms instead of
three: the re-walk interval (with hint-growth bypass) and the limiter.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01L5DLvDTo9dhD38YQXhHpU9
Signed-off-by: Ovais Tariq <[email protected]>
Without a count cap a rate-limited whole-fleet pass can outlast the
walk interval; pass-start timestamps would then expire retained
derivations prematurely and re-walk the fleet every pass. 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]>
…nal Put

copyEntry marshalled the ValueMessage it read at walk time and wrote it
with wb.Put at the end of the (rate-limited, minutes-long) segment pass.
A Put that replaced the key inside that window was clobbered: the row
rolled back to the recompacted copy of the OLD bytes and the newly
written value became unreachable — silent data loss on a concurrent
overwrite, pre-existing on main and widened by the I/O budget.

Publish through the same compare-and-swap merge the file compactor uses
for raw -> segment migrations, extended to accept a SEGMENT base whose
SegmentPath matches the operand's precondition (closed segments are
append-only, so a path match proves the row is unchanged since the
copy's read; raw and segment paths live in disjoint directories, so the
two preconditions cannot cross-match). On mismatch the operand is
dropped, the newer write wins, and the copied bytes become dead space
the walk-gated recompactor reclaims. Flagged by Greptile.

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 force-pushed the feat/segment-audit-scrub branch from c8aaa4c to a37c6db Compare August 19, 2026 04:55

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

Comment thread storage/compaction/walker.go Resolved
A CompactFiles run iterates the whole compaction index with no per-run
byte cap, committing its metadata batch only at the end. Destination
segments are finalized along the way, so under a large backlog and a
rate-limited copy those segments became closed — recompaction- and
walk-eligible — while every entry inside them still had metadata
pointing at a raw file. A liveness derivation reads such a segment as
fully dead, copies nothing, and removes it; the run's later commit then
publishes rows referencing a deleted file. The 2 h age gate does not
bound this: the finalize-to-commit window is the run's duration, which
at 16 MiB/s over a 200 GB backlog is hours.

Commit before finalizing instead, so 'closed segment implies published
metadata' is structural rather than a timing assumption. commit() syncs
the segment before writing metadata, preserving sync-before-publish;
source raw files are queued for deletion only after their replacement
metadata is durable, at rollover as at end of run. Crash recovery also
improves: less work lost and fewer orphaned segment bytes per crash.

TestCompactFiles_PublishesBeforeFinalizingSegment pins the invariant by
observing a rollover mid-run; it fails without this change ('holds 1
entries but only 0 have published metadata'). 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]>
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@ovaistariq
ovaistariq merged commit 5566683 into main Aug 19, 2026
11 checks passed
@ovaistariq
ovaistariq deleted the feat/segment-audit-scrub branch August 19, 2026 05:34
@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.

3 participants