Skip to content

perf: rate limit compaction payload reads - #219

Merged
ovaistariq merged 6 commits into
mainfrom
perfloop-pr-open-t4b9f94ktg
Aug 18, 2026
Merged

ovaistariq merged 6 commits into
mainfrom
perfloop-pr-open-t4b9f94ktg

Conversation

@perfloop

@perfloop perfloop Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Problem

File compaction and segment recompaction copy source payloads without a shared bound, so background reads can compete with serving reads on throughput-capped volumes.

Fix

Add -compaction-bytes-per-second, a shared 16 MiB/s source-read budget for file compaction and recompaction. It admits reads in 64 KiB chunks, so adding workers does not increase the total copy rate. The setting applies at startup; segment writes are not throttled.

The cap intentionally slows backlog drain to leave capacity for serving reads. Raw files are queued for deletion only after the segment is synced and metadata commits, and interrupted segment entries are rolled back.

Test

  • make test-storage TESTRUN='CompactFiles\|CopyFileIntoSegment\|CompactionLoop\|ConcurrentCompaction\|SegmentRecompaction\|SegmentRotation\|Manager_WriteEntry\|NewCompactionRateLimiter\|NewCompactorShares\|RateLimitedReader\|NewStorageWithConfig_CompactionBytes\|Commit\|Queue' and make test-integration-compaction
  • GOFLAGS='-tags=ocache_benchmark' make test-server TEST=TestCompactionServingGetSchedule and BenchmarkCacheServiceGetDuringCompaction
  • make lint and make license-check

Workload: under GOMAXPROCS=4, five default-Storage ordinary file-compaction cycles of 64 KiB+1, 512 KiB, 4 MiB, and 64 MiB raw values (one worker, 256 MiB segments, enabled but ineligible recompaction) drain through a shared 96 MiB/s direct-source and foreground raw/segment payload-read lane while two warm CacheService.Get clients spend a fixed six-second active interval repeating four 64 KiB inline reads per round, 64 KiB raw/segment range reads, one 64 MiB+1 raw full read, and periodic 2 MiB segment full reads; C caps shared compaction source reads at 16 MiB/s, validates at least 1,000 inline samples at <1ms p99, verifies every migrated payload after source deletion, and requires drain within 45s

Metric Before After Change
compaction-MB/s 38.09 14.9 60.9% lower
Checks: 1 passed.

Generated by Perfloop. Measurements and checks.


Note

Medium Risk
Changes core compaction I/O, deletion ordering, and segment manager locking on the hot read path; behavior shifts for deployments relying on old defaults or unbounded compaction throughput.

Overview
Adds -compaction-bytes-per-second (default 16 MiB/s on the server) as a shared payload-read budget for file compaction and segment recompaction. Reads are admitted in 64 KiB chunks via a token bucket, so extra compaction workers do not raise total copy throughput; embedded/library storage stays unthrottled unless a limit is set explicitly.

Safety and latency: Raw source files are queued for deletion only after the segment is synced and metadata commits, avoiding deletion of files still referenced during long rate-limited copies. Failed or interrupted segment writes roll back partial entries. AcquireOpenSegmentWithReservation skips busy segments with TryRLock instead of blocking on segment locks while holding the manager lock, so foreground segment reads are not stalled behind slow compaction copies.

Documentation updates several compaction defaults (e.g. compact threshold 64 MiB, one worker, recompaction tuning). Adds a benchmark build target and BenchmarkCacheServiceGetDuringCompaction (with optional ocache_benchmark read gating) to measure serving latency while compaction drains under a shared I/O cap.

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

Exercise default file compaction against a shared benchmark payload-read lane and bound its backlog drain.

Signed-off-by: Perfloop Agent <[email protected]>
Share one bounded payload-read budget across file compaction and recompaction. Keep source files until synchronized segment metadata is published.

Signed-off-by: Perfloop Agent <[email protected]>
@greptile-apps

greptile-apps Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Greptile Summary

Adds a shared, configurable source-read rate limit across ordinary file compaction and segment recompaction while preserving safe segment publication and deletion ordering.

  • Introduces a server-level compaction byte-rate setting and shared token-bucket limiter.
  • Reads compaction payloads in bounded chunks and makes rate-limit waits cancellation-aware.
  • Keeps old segments registered after incomplete recompaction passes so live metadata remains readable and later passes can retry.
  • Adds compaction-serving benchmarks, focused lifecycle tests, and updated configuration documentation.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
storage/compaction/recompactor.go Shares the payload limiter with file compaction and safely retains the old segment whenever copying or iteration leaves the recompaction pass incomplete.
storage/compaction/compactor.go Applies the shared source-read limiter to ordinary compaction without increasing aggregate throughput as workers are added.
storage/compaction/ratelimiter.go Implements cancellation-aware, chunked token admission for compaction payload reads.
storage/segment/manager.go Adjusts segment acquisition and reservation behavior to avoid blocking foreground reads behind slow compaction work.
storage/storage.go Wires the configured shared limiter into storage initialization while retaining unthrottled library behavior when no limit is supplied.
server/main.go Exposes and forwards the server’s compaction-bytes-per-second setting.
server/compaction_serving_bench_test.go Adds a benchmark workload that validates serving latency and migrated-payload integrity while a bounded compaction backlog drains.

Reviews (3): Last reviewed commit: "fix: keep the old segment on an incomple..." | Re-trigger Greptile

Comment thread storage/compaction/recompactor.go Resolved
Comment thread storage/compaction/compactor.go Resolved
…the storage layer

The storage-layer clamp (<= 0 -> 16 MiB/s) had three consequences:

- No way to disable throttling: -compaction-bytes-per-second 0 silently became
  the default, unlike -max-disk-usage where 0 means unlimited.
- Embedded/library users were silently throttled: embedded.Config does not set
  the field, so every embedded deployment would inherit a 16 MiB/s compaction
  cap from a library upgrade with no knob to change it.
- Test_CompactionLoop_Performance failed deterministically: the integration
  config leaves the field unset, the clamp applied 16 MiB/s, and the test's
  53.7 MB backlog needs ~3.4s to copy — longer than its 3s wait — so the
  single end-of-pass metadata commit had not happened when it asserted that
  the raw-file count dropped.

Move the default to where the policy belongs: the server flag keeps its
16 MiB/s default (server deployments are throttled by default, as intended),
while the storage layer treats a non-positive value as unthrottled, matching
the 0-disables convention. -compaction-bytes-per-second 0 now genuinely
disables the budget, embedded storage keeps its historical behavior unless a
budget is set via Storage.CompactionBytesPerSecond, and the integration suite
runs unthrottled as its timings assume.

make test-storage, make test-integration-compaction, and make lint pass.

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

@ovaistariq ovaistariq left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against source and executed locally (targeted storage/compaction/segment tests, full make test-storage, make test-integration-compaction, make lint). Verdict: the mechanism is solid and two parts of this PR are genuinely excellent — but the review found one deterministic test failure and two policy gaps, all three rooted in the same line. Fixed directly in db3478e (details below), after which everything passes locally.

What's good — and worth calling out

  • The deferred source deletion is a real correctness fix, not just throttle support. The old code queued raw files for deletion inside the loop, before the end-of-pass metadata commit; a failed or cancelled commit could let the 1s deletion queue delete files still referenced by live metadata (the dangling-raw-file class that the purge machinery papers over). Rate limiting widened that window enough to force the proper fix — filesToDeleteAfterCommit flushed strictly after commit is correct on every path I traced (commit success → queue; commit failure/cancel → not queued, entries retried).
  • WriteEntry rollback (truncate + seek to startOffset under s.mu) keeps failed/interrupted entries unpublished; s.size only advances on success. Verified ReadEntry takes the fd-cache's per-file lock on a separate read-only descriptor — not s.mu — so a slow rate-limited copy never blocks foreground reads. No priority inversion.
  • The limiter itself is clean: shared x/time/rate across file-compaction workers and the recompactor (so -compaction-threads doesn't multiply the budget), chunk clamped to burst before WaitN (no WaitN > burst error), worker ctx plumbed so shutdown aborts the wait → rollback.
  • benchio/read-gate indirection is zero-cost in production — all no-op identity functions outside the ocache_benchmark build tag.
  • Docs table changes are catch-up to current main defaults, not scope creep (verified against origin/main).

The findings (all fixed in db3478e)

Root cause: NewStorageWithConfig clamped CompactionBytesPerSecond <= 0 to the 16 MiB/s default at the storage layer. Three consequences:

  1. Test_CompactionLoop_Performance failed deterministically ("100" is not less than "100" — Compaction should reduce raw file count). The integration config leaves the field unset → clamp applies 16 MiB/s → the test's 53.7 MB backlog needs ~3.4 s to copy, longer than its 3 s wait — and because CompactFiles commits the whole pass in one end-of-pass batch, nothing was visible when it asserted. (The PR patched the ThresholdBehavior test's budget but missed this suite.)
  2. No way to disable throttling: -compaction-bytes-per-second 0 silently became the default — inconsistent with -max-disk-usage, where 0 means unlimited.
  3. Embedded/library users silently throttled: embedded.Config doesn't set the field, so every embedded deployment would inherit a 16 MiB/s compaction cap from a library upgrade, with no knob. With the 64 MB compact threshold, a sustained medium-object ingest above 16 MiB/s grows the raw-file backlog without bound — for the embedded large-object workload that's a regression risk we shouldn't ship as a silent default.

Fix: the 16 MiB/s default now lives where the policy belongs — the server flag (server deployments throttled by default, exactly as this PR intends). The storage layer treats non-positive as unthrottled (matching the 0-disables convention), so 0 genuinely disables, embedded keeps historical behavior unless Storage.CompactionBytesPerSecond is set explicitly, and the integration suite runs unthrottled as its timings assume. Docs + flag help updated; the storage config test now asserts the no-clamp contract.

Non-blocking observations (fine as follow-ups)

  • Single end-of-pass commit + throttle = long visibility latency. A large backlog pass at 16 MiB/s can hold the whole metadata batch (and its RocksDB iterator pinning) open for minutes; compacted entries aren't readable from segments (and raw files aren't reclaimable) until the entire pass drains. A periodic mid-pass commit (as evictByIndex does per 1000 ops) would bound this — reasonable follow-up, not needed for correctness.
  • The backlog has no feedback valve: if ingest exceeds the budget the raw-file backlog grows without bound (docs are honest about this). If it ever bites in practice, a pressure escape (e.g. ignore the budget while the #211 free-space backstop is active) would compose well.

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

Comment thread storage/storage.go Resolved
With the compaction I/O budget, Segment.WriteEntry holds seg.mu exclusively
for the whole rate-limited payload copy — seconds per entry at the 16 MiB/s
default, vs tens of milliseconds before. AcquireOpenSegmentWithReservation
held the manager-wide sm.mu writer lock while taking seg.mu.RLock() on every
open segment, so probing a mid-copy segment blocked for the entire copy while
holding sm.mu — and every Manager.ReadEntry (the foreground GET path for all
segment-resident objects) queued behind it. Net effect: multi-second serving
stalls on every throttled entry, recreating via lock convoy the exact symptom
the I/O budget exists to prevent. Both compaction workers and the recompactor
re-acquire on ~100ms loops, so the convoy re-formed continuously for a whole
backlog pass.

Fix: probe open segments with seg.mu.TryRLock() and skip on failure. An
exclusively-locked segment is necessarily mid-copy by its reserving owner, so
it could not have been handed to this caller anyway — skipping is semantically
identical to the reservedBy check that would have rejected it, without the
blocking. Acquire was the only sm.mu holder that nested seg.mu
(RefreshMetrics already snapshots specifically to avoid this), and
Segment.Reserve cannot block on a mid-copy segment (a copy requires a
reservation, and a competing reservation cannot be taken while this caller
holds sm.mu), so this single change breaks the convoy chain.

Regression test: TestAcquireSkipsBusySegmentWithoutBlocking holds a segment's
lock (as a rate-limited copy does) and asserts a second caller's Acquire and
the Manager.ReadEntry path complete promptly. Verified to fail with the
pre-fix code (Acquire blocks until timeout) and pass with the fix.

Also from review: RateLimitBytesPerSecond() on the Compactor so the storage
config test can assert the configured budget actually reaches the compactor's
limiter (not just that the input config is preserved), and a help entry for
build-bench-compaction-serving-reads.

make test-storage and make lint pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra
Signed-off-by: Ovais Tariq <[email protected]>
@ovaistariq

Copy link
Copy Markdown
Contributor

Follow-up from a second (cross-session) adversarial review of db3478e — one critical finding confirmed and fixed in 056c2a0:

Rate-limit waits convoyed the manager lock, stalling all segment-resident serving reads. Segment.WriteEntry holds seg.mu exclusively for the whole payload copy — seconds per entry under the 16 MiB/s budget, vs tens of ms before. AcquireOpenSegmentWithReservation held the manager-wide sm.mu writer lock while taking seg.mu.RLock() on every open segment, so probing a mid-copy segment blocked for the entire copy while holding sm.mu — and every Manager.ReadEntry (the foreground GET path for all segment-resident objects) queued behind it. Both the compaction worker and the recompactor re-acquire on ~100 ms loops, so the convoy re-formed on every throttled entry: multi-second serving stalls, recreating via locks the exact symptom the I/O budget exists to prevent. (My earlier review verified Segment.ReadEntry doesn't take seg.mu and stopped there — the manager-level coupling was the missed link. Credit to the second review for catching it.)

Fix: probe with seg.mu.TryRLock() and skip busy segments. An exclusively-locked segment is necessarily mid-copy by its reserving owner, so it could not have been handed to this caller anyway — skipping is semantically identical to the reservedBy rejection, minus the blocking. Verified this is sufficient: Acquire is the only sm.mu holder that nests seg.mu (RefreshMetrics already snapshots specifically to avoid this), and Reserve can't block on a mid-copy segment (a copy requires a reservation, and a competing reservation can't be taken while this caller holds sm.mu).

Regression test TestAcquireSkipsBusySegmentWithoutBlocking holds a segment lock (as a throttled copy does) and asserts a second caller's Acquire + the ReadEntry path complete promptly — verified to fail against the pre-fix code (blocks to timeout) and pass with the fix.

Also from that review: Compactor.RateLimitBytesPerSecond() accessor + the storage config test now asserts the budget actually reaches the compactor's limiter (not just that the input config is preserved), and a help entry for build-bench-compaction-serving-reads.

make test-storage and make lint pass at 056c2a0.

…ts cannot convoy the manager lock

ReleaseAllSegments held sm.mu.RLock while calling seg.Release (which takes
seg.mu.Lock) on every open segment — the same held-manager-lock-blocks-on-
busy-segment coupling fixed in AcquireOpenSegmentWithReservation. It has no
non-test callers today, but a future caller would silently resurrect the
serving-read convoy under the compaction I/O budget. Snapshot the open set
under sm.mu and release outside it (the RefreshMetrics pattern).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra
Signed-off-by: Ovais Tariq <[email protected]>
@ovaistariq

Copy link
Copy Markdown
Contributor

Cross-session re-review of 056c2a0 came back clean — all three findings resolved, convoy fix confirmed sufficient (exhaustive audit of every sm.mu-held region). One last non-blocking item from it, addressed in 9faa7ac: ReleaseAllSegments nested seg.Release (takes seg.mu.Lock) under sm.mu.RLock — dead code today, but a future caller would silently resurrect the serving-read convoy. Fixed with the snapshot pattern (kept rather than deleted: it's exported API on the published storage module). Segment/reservation tests green. Every finding from both review rounds is now closed; head 9faa7ac.

@ovaistariq

Copy link
Copy Markdown
Contributor

@greptile

…e WriteEntry's failure paths actually fail

Two coupled fixes surfaced by the Greptile P1 on this PR ("cancellation drops
live entries" — whose stated scenario is refuted, but whose neighborhood hid
real bugs):

1. Incomplete-pass guard (recompactor). A live entry whose copy fails (or a
   segment read error that hides everything beyond it) previously did not stop
   the post-loop removal: the old segment was unconditionally removed and
   queued for deletion while the failed entry's metadata still pointed into
   it — permanently unreadable data. Pre-existing on main; #219's rate-limited
   copies widen the exposure window. Now any failed entry keeps the old
   segment tracked (delete index preserved) for a later pass; already-copied
   entries are committed and skipped as moved on the retry. The
   all-entries-dead case still removes the segment.

2. WriteEntry's failure paths silently succeeded (pre-existing on main).
   utils.WrapError(msg, path, nil) returns nil, so three failure branches —
   invalid value type, closed segment file, and the copied-bytes/ValueLength
   mismatch — returned (0, nil): success at offset 0. A short source read
   (e.g. a truncated segment) therefore "succeeded", the caller published
   metadata at offset 0 of the new segment, and reads decoded another entry's
   bytes — silent data corruption, reproduced deterministically by the new
   regression test before this fix. On main the same hole is worse: with no
   rollback, s.size is not advanced over the partial bytes, skewing every
   subsequent entry offset in the segment. All three branches now return real
   errors (the mismatch wraps io.ErrUnexpectedEOF).

Regression test TestSegmentRecompaction_IncompletePassKeepsOldSegment builds a
segment, truncates the last entry's payload mid-way, runs a recompaction pass,
and asserts: no error surfaced, the old segment file and manager tracking
survive, intact entries remain readable, and nothing was queued for deletion.
Before these fixes it demonstrated the full corruption chain (victim entry
committed pointing at another entry's bytes).

make test-storage and make lint pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra
Signed-off-by: Ovais Tariq <[email protected]>
@ovaistariq

Copy link
Copy Markdown
Contributor

Follow-up on the Greptile P1 ("Cancellation drops live entries", recompactor.go:358) — its stated scenario is refuted (the loop-top ctx.Err() guard returns before the removal code, so cancellation loses nothing), but investigating its neighborhood uncovered two real bugs, one of them silent data corruption. Both fixed in f247149.

1. Incomplete recompaction pass removed the old segment (pre-existing; #219 widens the window). A live entry whose copy fails — or a mid-scan read error that hides everything beyond it — used to continue/break into the unconditional post-loop removal: old segment removed + queued for deletion while the failed entry's metadata still pointed into it → permanently unreadable. Now any failed entry keeps the old segment tracked (delete index preserved) for a later pass; committed copies are skipped as moved on retry; the all-entries-dead case still removes.

2. WriteEntry's failure paths have never failed (pre-existing on main). utils.WrapError(msg, path, nil) returns nil, so three failure branches — invalid value type, closed segment file, and the copied-bytes/ValueLength mismatch check — returned (0, nil): success at offset 0. Writing the regression test for #1 exposed the full chain deterministically: truncate a segment mid-payload → the short copy "succeeds" → metadata committed pointing at offset 0 of the new segment → reads decode another entry's bytes. On main the same hole is worse — no rollback, so s.size skew corrupts every subsequent entry offset. All three branches now return real errors (the mismatch wraps io.ErrUnexpectedEOF).

Regression test TestSegmentRecompaction_IncompletePassKeepsOldSegment: builds a segment, truncates the last entry's payload, runs a pass, asserts the old segment survives (file + manager tracking + intact entries readable) and nothing is queued for deletion. Before the fixes it reproduced the corruption end-to-end (victim entry served with a neighbor's bytes).

Full make test-storage + make lint green at f247149.

@ovaistariq

Copy link
Copy Markdown
Contributor

@greptile

@ovaistariq
ovaistariq merged commit 587d865 into main Aug 18, 2026
11 checks passed
@ovaistariq
ovaistariq deleted the perfloop-pr-open-t4b9f94ktg branch August 18, 2026 04:58
@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.10.2 🎉

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