Skip to content

feat: statfs-based free-space reserve as an ENOSPC backstop (#204) - #211

Merged
ovaistariq merged 1 commit into
mainfrom
fix/204-statfs-reserve-backstop
Aug 15, 2026
Merged

ovaistariq merged 1 commit into
mainfrom
fix/204-statfs-reserve-backstop

Conversation

@ovaistariq

@ovaistariq ovaistariq commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Piece 2 of #204 (the prevention half). Complements #209 (the #189 index-coverage fix).

Problem

-max-disk-usage 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 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 statfs and, if it's below the reserve, evicts by the active policy's index — independent of the logical total. Free space is exported as ocache_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.

  • Fixed reserve, no flag (per the ask): 2 GiB Cleaner field, capped to 1/10 of the volume so it stays achievable on small disks.
  • diskUsage uses syscall.Statfs; block counts are in fragment-size units — Frsize on Linux, Bsize on darwin (no Frsize there) — handled per-platform in diskspace_{linux,darwin}.go.

Note: this replaced an earlier in-flight-accounting design (track evicted-but-not-yet-reclaimed bytes, decay by free-rise, age-out). That version worked but required ~100 more lines of stateful control-loop logic whose failure mode was the catastrophic one (stalling below reserve → ENOSPC). The bounded-slice design is simpler, has no such state, and by construction cannot exhibit that class of bug — at the cost of accepting bounded, recoverable over-eviction during reclamation lag.

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 a diskUsage sanity check. docs/configuration.md documents the backstop. Full make test-storage passes.

🤖 Generated with Claude Code


Note

Cursor Bugbot is generating a summary for commit 56e441b. Configure here.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR adds a statfs-based filesystem reserve backstop for capped caches and exports the measured free space.

  • Adds platform-specific filesystem-capacity measurement for Linux and Darwin.
  • Adds reserve-driven LRU/FIFO eviction with a per-tick target.
  • Documents the reserve and adds coverage for reserve thresholds, policies, unavailable measurements, and uncapped caches.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
storage/cleaner.go Adds statfs-driven reserve enforcement to the cleaner using the active eviction policy.
storage/diskspace.go Adds filesystem free-space and total-capacity measurement with unavailable-result handling and integer clamping.
storage/diskspace_linux.go Uses Linux fragment size, with block size as a fallback, for statfs byte conversion.
storage/diskspace_darwin.go Uses Darwin statfs block size for byte conversion.
storage/filesystem_reserve_test.go Covers reserve-triggered eviction, policy selection, threshold behavior, repeated passes, and inactive paths.
common/metrics/metrics.go Exposes filesystem free bytes as a Prometheus gauge.
docs/configuration.md Documents the fixed filesystem reserve behavior for capped caches.

Reviews (5): Last reviewed commit: "feat: statfs-based free-space reserve as..." | Re-trigger Greptile

Comment thread storage/cleaner.go Resolved
Comment thread storage/diskspace.go Resolved
@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from 8495a83 to b3fc5fb Compare August 14, 2026 23:00
Comment thread storage/cleaner.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/cleaner.go Resolved
@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from b3fc5fb to 8af4466 Compare August 14, 2026 23:18
@ovaistariq

Copy link
Copy Markdown
Contributor Author

Both actionable findings from this round are fixed in the latest push:

@cursor (High) / @greptile-apps (P1) — reserveOutstanding used the requested deficit, not bytes actually evicted. Correct and important: if the eviction index is exhausted or a batch write fails, recording the full requested deficit as "in flight" would never decay (free stays flat) and would suppress later reserve passes — disabling the backstop exactly under ENOSPC pressure. Fixed: evictByIndex now returns the bytes it actually freed (committedBytes), and reserveOutstanding is incremented by that, not by the request. So a pass that frees nothing records nothing and the next tick retries. Added a regression test (DoesNotOverEvictWhileReclaimLags) with a sub-cache deficit that asserts the first pass evicts part of the cache and subsequent flat-free ticks evict nothing more.

@cursor (Medium) — Bavail * Bsize mis-scales free space. Right — block counts are in fragment-size units, which is Frsize on Linux (Bsize is only the preferred I/O size and can differ on some FUSE / Docker Desktop mounts) and Bsize on darwin (which has no Frsize). Fixed with per-platform statfsBlockSize (diskspace_linux.go uses Frsize with a Bsize fallback; diskspace_darwin.go uses Bsize).

The earlier P1 on commit 8495a83 ("physical deficit drives logical eviction / repeatedly evict entire cache") is the same class the in-flight accounting was added for; with the actual-bytes-evicted fix it no longer records phantom reclamation. make test-storage green; vet/fmt clean.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026

Copy link
Copy Markdown

Both fixes are implemented correctly.

P1 (actual-bytes accounting): evictByIndex now returns evictedBytes via the deferred capture of committedBytes, and enforceFilesystemReserve increments reserveOutstanding by that value rather than the requested deficit. If the index is exhausted or a batch write fails, committedBytes stays low, so reserveOutstanding records nothing and the next tick retries — exactly the right behavior under ENOSPC pressure.

Medium (block-size scaling): The per-platform split is clean. diskspace_linux.go uses Frsize with a Bsize fallback (for degenerate filesystems that report Frsize == 0); diskspace_darwin.go uses Bsize since darwin's statfs_t has no Frsize. The uint64 cast on st.Bavail in diskspace.go is defensively correct on both platforms.

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 reserveOutstanding resets to 0 when free rises above the reserve closes the loop on the decay path.

Both findings are resolved. No further concerns.

Comment thread storage/cleaner.go Resolved
@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from 8af4466 to d828105 Compare August 14, 2026 23:26
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@cursor (Medium, "Free-space decay skips after zero") — valid, fixed.

The prevFree > 0 guard conflated the unset initial value with a real statfs reading of zero free bytes, so recovering from a genuine near-ENOSPC episode (free 0 → rising, still below reserve) skipped decaying reserveOutstanding, leaving phantom credit that could suppress the backstop exactly when it's needed.

Fixed by initializing lastReserveFree to a -1 sentinel ("no sample yet") and changing the decay guard to prevFree >= 0, so a real zero is a valid decay baseline. Added TestEnforceFilesystemReserve_DecaysAfterRealZero, which seeds lastReserveFree=0 with a full-reserve outstanding, then a rise to 10 KiB free and asserts outstanding decays to 20 KiB (was stuck at 30 KiB before the fix).

make test-storage green (8 reserve tests); vet/fmt clean.

@cursor

cursor Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

The fix for the "Free-space decay skips after zero" finding is correctly implemented and verified:

Implementation Summary:

  1. Sentinel initialization (storage/cleaner.go:99):
	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{}),
	}
}
  1. Decay guard fixed (storage/cleaner.go:671-680):
	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
		}
	}
  1. Regression test (storage/filesystem_reserve_test.go:152-177):
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 -1 sentinel (uninitialized) and a genuine 0 free-space reading, ensuring the backstop continues to function during ENOSPC recovery scenarios. All changes are already committed to the branch.

Open in Web Open in Cursor 

Comment thread storage/cleaner.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@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 reserveOutstanding stays as phantom credit, deficit stays ≤ 0, and the backstop stalls below the reserve under sustained write pressure — risking the ENOSPC it exists to prevent.

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. reserveOutstanding is dropped if free hasn't risen after reserveOutstandingMaxTicks (2) reserve checks, so the backstop resumes evicting instead of stalling. This deliberately errs toward preventing ENOSPC (terminal) over avoiding over-eviction (recoverable cache warmth). Note it only fully "holds" when free is stable; if free is actually falling, deficit goes positive on its own and eviction continues regardless of the credit — so real pressure is never suppressed.

Tests: DoesNotOverEvictWhileReclaimLags now asserts the hold lasts through the age-out window; new ResumesAfterHold pins free flat past the window and asserts eviction resumes (no indefinite stall). make test-storage green; vet/fmt clean.

@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from d828105 to 560a434 Compare August 14, 2026 23:48
@cursor

cursor Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Perfect! The "Phantom outstanding blocks backstop" fix is fully implemented and verified. Here's what's in place:

Implementation Summary:

  1. Age-out constant (storage/cleaner.go:55-63):
	// 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
  1. Age tracking field (storage/cleaner.go:82):
	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
  1. Age-out logic (storage/cleaner.go:679-738) that:

    • Increments age each tick when outstanding credit exists
    • Drops the credit after reserveOutstandingMaxTicks (2) checks
    • Resets age when new eviction happens or free rises
  2. Regression tests:

    • TestEnforceFilesystemReserve_DoesNotOverEvictWhileReclaimLags verifies hold within the age-out window
    • TestEnforceFilesystemReserve_ResumesAfterHold verifies eviction resumes after the window expires

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.

Open in Web Open in Cursor 

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

Comment thread storage/cleaner.go Resolved
Comment thread storage/cleaner.go Outdated
Comment on lines +685 to +688
if c.reserveOutstandingAge > reserveOutstandingMaxTicks {
c.reserveOutstanding = 0
c.reserveOutstandingAge = 0
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 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

@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from 560a434 to 2872d4d Compare August 15, 2026 00:06
@ovaistariq

Copy link
Copy Markdown
Contributor Author

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 free < reserve, evict at most 1/4 of the cache this tick and re-measure next tick. It cannot stall (no accounting to get stuck on), and it's self-limiting because evicting segment entries drives the recompaction that frees them. It deliberately accepts bounded, recoverable over-eviction during reclamation lag rather than risk the terminal under-eviction. Kept: the per-platform Frsize/Bsize statfs fix and the small-volume reserve cap (both inherent to any design).

Comment thread storage/cleaner.go Resolved
@ovaistariq

Copy link
Copy Markdown
Contributor Author

Both latest findings target commit 560a434 — the in-flight-accounting design that the bounded-slice rework (2872d4d) removed entirely:

  • @cursor "Age-out ignores free-space rises" — reserveOutstandingAge and the decay ordering no longer exist. Stale (and, for the record, one more finding in the class the rework was done to eliminate).
  • @greptile-apps "Reclamation credit expires too early" — the 2-tick credit expiry no longer exists either. But the underlying fact is correct and worth addressing head-on: DefaultMinSegmentAgeForRecompaction = 2h, and the eligibility check (recompactor.go:384) applies it unconditionally — so evicting entries backed by young segments frees zero physical bytes for up to 2 hours.

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:

  1. No design that evicts can free young-segment space — the in-flight version also resumed after its hold (deliberately, else it stalls into ENOSPC) and drained too, just slower. The choice isn't "drain vs don't"; it's "drain simply vs drain with stateful machinery whose failure mode is a stall."
  2. Eviction is oldest-first (FIFO/LRU order), so the evicted slice is preferentially raw files and >2h segments — exactly the bytes that do free. The pathological case needs essentially the whole cache to be <2h old, i.e. small and cheap to re-warm.
  3. The slice bound keeps each tick's damage at 25% of the remaining cache.

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.

@greptile-apps

greptile-apps Bot commented Aug 15, 2026

Copy link
Copy Markdown

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.

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@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 enforceFilesystemReserve for the rationale). No code change.

@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from 2872d4d to 56e441b Compare August 15, 2026 00:13
@cursor

cursor Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Verified! The stale reserve field comments have been properly cleaned up in the latest commit:

What was fixed:

  1. Cleaner struct comments (storage/cleaner.go:68-72) - Collapsed to a single accurate description:
	// 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
  1. All in-flight tracking fields removed - No more reserveOutstanding, lastReserveFree, or reserveOutstandingAge fields

  2. Implementation comment (storage/cleaner.go:640-648) - Now accurately describes the bounded-slice design:

// 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 (min(deficit, cache/4)) and evicts, with no bookkeeping that could stall. All changes are committed at 56e441b.

Open in Web Open in Cursor 

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

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

Comment thread storage/diskspace.go Resolved
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]>
@ovaistariq

Copy link
Copy Markdown
Contributor Author

@cursor (Medium, "Zero statfs wipes cache") — valid, fixed.

Confirmed the chain: a mount reporting zero fragment/block size (or zero total blocks) yielded free=0, total=0, ok=true; the volume-cap's total > 0 guard then skipped, leaving the full 2 GiB reserve, and free=0 < reserve evicted a slice every tick for as long as the mount reported zeros.

Fix in diskUsage: a zero-capacity reading is "measurement unavailable" (ok=false → backstop inactive for the tick, logical cap still protects), not "disk full". Crucially, free=0 with a sane total remains a valid reading — a genuinely full disk must still trigger the backstop. Added TestEnforceFilesystemReserve_InactiveWhenStatfsUnavailable covering the ok=false → no-eviction contract. make test-storage green.

@ovaistariq
ovaistariq force-pushed the fix/204-statfs-reserve-backstop branch from 56e441b to ec99549 Compare August 15, 2026 00:21
@cursor

cursor Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Perfect! The "Zero statfs wipes cache" fix is fully implemented and verified:

Implementation Summary:

  1. diskUsage validation (storage/diskspace.go:27-34):
	// 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:

  • Returns ok=false when total <= 0 (zero-capacity reading)
  • Treats this as "measurement unavailable" rather than "disk full"
  • Preserves the distinction: free=0 with total>0 is still a valid reading for a genuinely full disk
  1. Regression test (storage/filesystem_reserve_test.go:145-167):
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 ok=false makes the backstop inactive for the tick, preventing the cache wipe that would occur if free=0, total=0 were treated as "disk full". All changes are committed at ec99549.

Open in Web Open in Cursor 

@ovaistariq

Copy link
Copy Markdown
Contributor Author

@greptile

@tigrisdata-argocd-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.10.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.

2 participants