Repository navigation
feat: statfs-based free-space reserve as an ENOSPC backstop (#204) - #211
Conversation
Greptile SummaryThe PR adds a statfs-based filesystem reserve backstop for capped caches and exports the measured free space.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains. Important Files Changed
Reviews (5): Last reviewed commit: "feat: statfs-based free-space reserve as..." | Re-trigger Greptile |
8495a83 to
b3fc5fb
Compare
b3fc5fb to
8af4466
Compare
|
Both actionable findings from this round are fixed in the latest push: @cursor (High) / @greptile-apps (P1) — @cursor (Medium) — The earlier P1 on commit |
|
Both fixes are implemented correctly. P1 (actual-bytes accounting): Medium (block-size scaling): The per-platform split is clean. The regression test design is good — using a sub-cache deficit (20 KiB deficit against a 50 KiB cache) makes the first-pass-evicts-part / subsequent-ticks-are-silent behavior directly observable, and the final section verifying Both findings are resolved. No further concerns. |
8af4466 to
d828105
Compare
|
@cursor (Medium, "Free-space decay skips after zero") — valid, fixed. The Fixed by initializing
|
|
The fix for the "Free-space decay skips after zero" finding is correctly implemented and verified: Implementation Summary:
return &Cleaner{
storage: storage,
interval: interval,
maxDiskUsage: maxDiskUsage,
diskReserveBytes: defaultDiskReserveBytes,
diskUsageFn: diskUsage,
lastReserveFree: -1, // sentinel: no reserve sample taken yet (0 is a valid reading)
closeCh: make(chan struct{}),
}
}
prevFree := c.lastReserveFree
c.lastReserveFree = free
// prevFree >= 0 accepts a real zero reading (near-ENOSPC) as a valid baseline;
// only the -1 sentinel (no sample yet) skips the decay.
if prevFree >= 0 && free > prevFree {
c.reserveOutstanding -= free - prevFree
if c.reserveOutstanding < 0 {
c.reserveOutstanding = 0
}
}
func TestEnforceFilesystemReserve_DecaysAfterRealZero(t *testing.T) {
s := newCappedStorage(t, EvictionPolicyLRU)
defer s.Close()
// Small volume so the reserve is total/10 = 30 KiB.
const total = 300 << 10
const reserve = total / 10 // 30 KiB
// Simulate a prior tick that observed a real zero free reading, with an
// outstanding equal to the whole reserve.
s.cleaner.lastReserveFree = 0
s.cleaner.reserveOutstanding = reserve
// Free rises to 10 KiB (still below the 30 KiB reserve). Decay must credit the
// 10 KiB that arrived, dropping outstanding to 20 KiB — and with deficit then 0,
// no eviction happens (isolating the decay).
s.cleaner.diskUsageFn = fakeUsage(10<<10, total)
s.cleaner.enforceFilesystemReserve()
require.Equal(t, int64(20<<10), s.cleaner.reserveOutstanding,
"a real zero reading must be a valid decay baseline; outstanding must decay as free rises")
}The fix correctly distinguishes between the |
|
@cursor (High, "Phantom outstanding blocks backstop") — valid, fixed. Right: with only free-rise decay, if reclaimed space is immediately re-consumed by new writes the sampler never sees the rise, so Grounding it in the real timings: the cleaner ticks every 1 min but the deletion queue processes every 1 s, so raw-file reclamation always completes within a tick. Flat free between ticks therefore means the space was re-consumed by writes (or is segment space pending recompaction) — not that our eviction hasn't drained yet. So carrying the credit indefinitely is wrong. Fix: age out the in-flight credit. Tests: |
d828105 to
560a434
Compare
|
Perfect! The "Phantom outstanding blocks backstop" fix is fully implemented and verified. Here's what's in place: Implementation Summary:
// reserveOutstandingMaxTicks bounds how many reserve checks the in-flight
// eviction credit may survive without an observed rise in free space before it
// is dropped. Raw-file reclamation (deletion queue, ~1s) completes well within
// a cleaner tick (~1min), so if free has not risen after this many ticks the
// evicted space was consumed by new writes (or is segment space still pending
// recompaction) — either way the backstop must resume evicting rather than
// stall below the reserve on stale credit. Errs toward preventing ENOSPC (a
// terminal state) over avoiding over-eviction (recoverable cache warmth).
reserveOutstandingMaxTicks = 2
diskReserveBytes int64
diskUsageFn func(path string) (free, total int64, ok bool)
reserveOutstanding int64 // logical bytes evicted whose physical space is still draining
lastReserveFree int64 // free bytes observed at the previous reserve check (-1 = none yet)
reserveOutstandingAge int // reserve ticks the current outstanding has survived without a free rise
initialized atomic.Bool
All changes are committed and match your description. The fix correctly handles the case where reclaimed space is immediately re-consumed by writes, preventing indefinite backstop stalls under sustained write pressure while free space remains below the reserve. |
| if c.reserveOutstandingAge > reserveOutstandingMaxTicks { | ||
| c.reserveOutstanding = 0 | ||
| c.reserveOutstandingAge = 0 | ||
| } |
There was a problem hiding this comment.
Reclamation credit expires too early
When a segment-heavy cache remains below the reserve, this branch clears its pending-reclamation credit after two cleaner ticks even though segment files can remain ineligible for recompaction for two hours. The next reserve pass therefore evicts the full logical deficit again while filesystem free space remains unchanged, repeatedly draining live cache entries before the segment space can be reclaimed.
Knowledge Base Used: Storage Lifecycle: Compaction, Eviction, and Deletion
560a434 to
2872d4d
Compare
|
Reworked the backstop from the in-flight-accounting design to a simpler bounded-slice design (force-pushed). Rationale: the previous version tracked evicted-but-not-yet-reclaimed bytes and decayed/aged that credit. It worked, but four of the last several review findings were self-inflicted by that bookkeeping (outstanding-vs-actual-bytes, decay-after-zero, phantom-outstanding stall), and its worst failure mode — stalling below the reserve on stale credit — is the catastrophic one (ENOSPC). The bounded-slice design removes all of that state (~100 fewer lines): if |
|
Both latest findings target commit
How the bounded-slice design behaves in that scenario, honestly: if free is below the reserve because of young-segment data, the backstop evicts 1/4-of-cache slices tick after tick without free rising. Three things bound the damage:
That said, this exchange surfaced a real improvement, separate from this PR: fully-dead segments shouldn't wait out the 2h age gate. A segment whose delete-index shows 100% dead bytes has nothing to copy — recompacting it is just a file delete, and the "ensure it's cold" rationale doesn't apply. With that tweak, backstop evictions of young-segment data become reclaimable within one recompaction tick, which closes the residual gap here properly instead of via more backstop machinery. Happy to file it as a follow-up issue. |
|
Both findings are stale — acknowledged, and thanks for the clear commit-level attribution. On the young-segment gap: the honest analysis holds up. The bounded-slice design doesn't make it worse than the in-flight version; it just exposes the underlying constraint (2h age gate) more visibly because there's no hold mechanism to obscure it. The three bounding factors you list are real — oldest-first ordering means the pathological case requires a nearly all-young cache, and the 25%-per-tick cap keeps each tick's over-eviction proportionate. The fully-dead-segment optimization is exactly the right lever to pull. A segment at 100% dead occupancy has no live data to protect during recompaction; the "ensure cold" rationale that motivated the age gate doesn't apply. Removing the gate for that case turns backstop evictions of young-segment data into reclaimable space within one recompaction tick, which closes the gap cleanly. Filing that as a follow-up issue makes sense — it's a tighter fix than any amount of backstop-side machinery and doesn't need to block this PR. |
|
@cursor (Low, stale reserve field comments) — right, that was a leftover from the branch file-swap: the old in-flight comment block was stacked on top of the new one. Collapsed to a single accurate comment noting the backstop is deliberately stateless (pointing at |
2872d4d to
56e441b
Compare
|
Verified! The stale reserve field comments have been properly cleaned up in the latest commit: What was fixed:
// diskReserveBytes is the free-space ceiling for the ENOSPC backstop; the
// effective reserve is min(diskReserveBytes, volume/reserveVolumeFraction).
// A field (not a flag) defaulted from the const. diskUsageFn is the (injectable,
// for tests) statfs source. The backstop is deliberately stateless — see
// enforceFilesystemReserve.
diskReserveBytes int64
// It evicts at most a bounded slice per tick and re-measures on the next tick,
// converging over several ticks rather than acting on the whole deficit at once.
// It deliberately keeps NO in-flight state. Freed space lags eviction (raw-file
// deletion queue, segment recompaction), but re-evicting while reclamation is
// pending is self-limiting — evicting segment entries raises their fragmentation,
// which triggers the recompaction that frees their space — and, crucially, the
// backstop can never stall on stale bookkeeping. Under-eviction risks the
// terminal ENOSPC this exists to prevent; over-eviction only costs recoverable
// cache warmth, so when in doubt it evicts.The bounded-slice implementation (lines 649-701) is clean and stateless - just calculates a bounded slice ( |
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 56e441b. Configure here.
MaxDiskUsage bounds only the logical cache size (sum of stored object lengths). Physical usage can legitimately run higher — segment preallocation slack, not-yet-recompacted dead space, orphaned raw files (#156), RocksDB SST amplification — so a logical-only cap cannot by itself keep the volume off 100%. Hitting 100% is terminal: RocksDB can no longer open the metadata DB, eviction can never run again, and only deleting the data directory recovers (#204, observed twice in production). Add a filesystem backstop to the cleaner: whenever a cap is set, each tick reads the volume's actual free space via statfs and, if it is below a reserve, evicts by the active policy's index to reclaim it — independent of the logical total. The backstop evicts at most a bounded slice per tick (1/4 of the current cache) and re-measures on the next tick, converging over several ticks. It keeps no in-flight bookkeeping: freed space lags eviction (raw-file deletion queue ~1s, segment recompaction minutes), but re-evicting while reclamation is pending is self-limiting — evicting segment entries raises their fragmentation, which triggers the recompaction that frees them — and, crucially, the backstop can never stall on stale accounting. It errs toward evicting: under-eviction risks the terminal ENOSPC this exists to prevent, whereas over-eviction only costs recoverable cache warmth. (For the large-object workload this protects, evicted raw files are freed within a tick by the deletion queue, so it converges with essentially no over-eviction.) The reserve is a fixed 2 GiB (a Cleaner field, not a flag), capped to 1/10 of the volume so it stays achievable on small volumes where a flat 2 GiB reserve could never be satisfied and would evict continuously. The statfs source is an injectable field (diskUsageFn) so the paths are tested deterministically without depending on the host's free space. diskUsage uses syscall.Statfs; block counts are in fragment-size units, which is Frsize on Linux and Bsize on darwin (darwin has no Frsize), handled per-platform in diskspace_{linux,darwin}.go. Free space is exported as the ocache_filesystem_free_bytes gauge. This is the #204 *prevention* half. The *recovery* half — breaking the terminal state once the disk is already full so RocksDB can open (reserved-headroom escrow or degraded open) — is a separate follow-up; no retry in this path can help once writes themselves fail with ENOSPC. Tests: evicts below the reserve (both policies); no-op above it; a single low reading evicts only a bounded slice (not the whole cache) and successive ticks converge; the small-volume cap spares a healthy small disk; no-op when uncapped. docs/configuration.md documents the backstop. make test-storage passes. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01YCoN4Him5ZY4hZovVp37ra Signed-off-by: Ovais Tariq <[email protected]>
|
@cursor (Medium, "Zero statfs wipes cache") — valid, fixed. Confirmed the chain: a mount reporting zero fragment/block size (or zero total blocks) yielded Fix in |
56e441b to
ec99549
Compare
|
Perfect! The "Zero statfs wipes cache" fix is fully implemented and verified: Implementation Summary:
// Some mounts (e.g. FUSE filesystems that omit statfs fields) report zero
// block size or zero total blocks. Treat a zero-capacity result as
// "measurement unavailable" rather than "disk full": free=0/total=0 would
// otherwise read as critically low space and drive continuous eviction.
// free=0 with a sane total remains a legitimate (genuinely full) reading.
if total <= 0 {
return 0, 0, false
}The fix correctly:
func TestEnforceFilesystemReserve_InactiveWhenStatfsUnavailable(t *testing.T) {
s := newCappedStorage(t, EvictionPolicyLRU)
defer s.Close()
const n = 5
for i := 0; i < n; i++ {
require.NoError(t, s.Put(fmt.Sprintf("key-%02d", i),
bytes.NewReader(bytes.Repeat([]byte("x"), 1024)), 0))
}
s.cleaner.diskUsageFn = func(string) (int64, int64, bool) { return 0, 0, false }
s.cleaner.enforceFilesystemReserve()
for i := 0; i < n; i++ {
_, found, err := s.Get(fmt.Sprintf("key-%02d", i), 0, 0)
require.NoError(t, err)
assert.True(t, found, "an unavailable statfs reading must not trigger eviction")
}
}The test verifies that |
|
🎉 This PR is included in version 1.10.0 🎉 The release is available on GitHub release Your semantic-release bot 📦🚀 |



Piece 2 of #204 (the prevention half). Complements #209 (the #189 index-coverage fix).
Problem
-max-disk-usagebounds only the logical cache size (sum of stored object lengths). Physical usage can legitimately run higher — segment preallocation slack, not-yet-recompacted dead space, orphaned raw files (#156), RocksDB SST amplification — so a logical-only cap can't by itself keep the volume off 100%. And 100% is terminal: RocksDB can't open the metadata DB, eviction can never run again, and only deleting the data directory recovers (#204, hit twice in prod).Fix — bounded-slice backstop
Whenever a cap is set, each cleaner tick reads the volume's actual free space via
statfsand, if it's below the reserve, evicts by the active policy's index — independent of the logical total. Free space is exported asocache_filesystem_free_bytes.It evicts at most a bounded slice per tick (1/4 of the current cache) and re-measures next tick, converging over several ticks. It keeps no in-flight bookkeeping. Freed space lags eviction (raw-file deletion ~1s, segment recompaction minutes), but re-evicting while reclamation is pending is self-limiting — evicting segment entries raises their fragmentation, which triggers the recompaction that frees them — and the backstop can therefore never stall on stale accounting. It errs toward evicting: under-eviction risks the terminal ENOSPC this exists to prevent, whereas over-eviction only costs recoverable cache warmth. For the large-object workload this protects, evicted raw files are freed within a tick by the deletion queue, so it converges with essentially no over-eviction.
Cleanerfield, capped to 1/10 of the volume so it stays achievable on small disks.diskUsageusessyscall.Statfs; block counts are in fragment-size units —Frsizeon Linux,Bsizeon darwin (noFrsizethere) — handled per-platform indiskspace_{linux,darwin}.go.Not in this PR
The #204 recovery half — breaking the terminal state once the disk is already full so RocksDB can open (reserved-headroom escrow, or degraded open) — is a separate follow-up. No retry in this prevention path can help once the writes themselves fail with ENOSPC.
Test
storage/filesystem_reserve_test.go: evicts below the reserve (both policies); no-op above it; a single low reading evicts only a bounded slice (not the whole cache) and successive ticks converge; the small-volume cap spares a healthy small disk; no-op when uncapped; plus adiskUsagesanity check.docs/configuration.mddocuments the backstop. Fullmake test-storagepasses.🤖 Generated with Claude Code
Note
Cursor Bugbot is generating a summary for commit 56e441b. Configure here.