Repository navigation
perf: rate limit compaction payload reads - #219
Conversation
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 SummaryAdds a shared, configurable source-read rate limit across ordinary file compaction and segment recompaction while preserving safe segment publication and deletion ordering.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains. Important Files Changed
Reviews (3): Last reviewed commit: "fix: keep the old segment on an incomple..." | Re-trigger Greptile |
…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
left a comment
There was a problem hiding this comment.
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 —
filesToDeleteAfterCommitflushed strictly after commit is correct on every path I traced (commit success → queue; commit failure/cancel → not queued, entries retried). WriteEntryrollback (truncate + seek tostartOffsetunders.mu) keeps failed/interrupted entries unpublished;s.sizeonly advances on success. VerifiedReadEntrytakes the fd-cache's per-file lock on a separate read-only descriptor — nots.mu— so a slow rate-limited copy never blocks foreground reads. No priority inversion.- The limiter itself is clean: shared
x/time/rateacross file-compaction workers and the recompactor (so-compaction-threadsdoesn't multiply the budget), chunk clamped to burst beforeWaitN(noWaitN > bursterror), workerctxplumbed so shutdown aborts the wait → rollback. benchio/read-gate indirection is zero-cost in production — all no-op identity functions outside theocache_benchmarkbuild 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:
Test_CompactionLoop_Performancefailed 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 becauseCompactFilescommits 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.)- No way to disable throttling:
-compaction-bytes-per-second 0silently became the default — inconsistent with-max-disk-usage, where 0 means unlimited. - Embedded/library users silently throttled:
embedded.Configdoesn'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
evictByIndexdoes 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.
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 db3478e. Configure here.
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]>
|
Follow-up from a second (cross-session) adversarial review of Rate-limit waits convoyed the manager lock, stalling all segment-resident serving reads. Fix: probe with Regression test Also from that review:
|
…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]>
|
Cross-session re-review of |
…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]>
|
Follow-up on the Greptile P1 ("Cancellation drops live entries", recompactor.go:358) — its stated scenario is refuted (the loop-top 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 2. Regression test Full |
|
🎉 This PR is included in version 1.10.2 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |

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'andmake test-integration-compactionGOFLAGS='-tags=ocache_benchmark' make test-server TEST=TestCompactionServingGetScheduleandBenchmarkCacheServiceGetDuringCompactionmake lintandmake license-checkWorkload:
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 45scompaction-MB/sGenerated 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.
AcquireOpenSegmentWithReservationskips busy segments withTryRLockinstead 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 optionalocache_benchmarkread 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.