Skip to content

fix(fileservice): shard disk cache directories and classify ENOSPC correctly - #30173

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/diskcache-shard-enospc
Oct 15, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/diskcache-shard-enospc

Conversation

@loveRhythm1990

@loveRhythm1990 loveRhythm1990 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Fixes #30167

What this PR does / why we need it:

DiskCache could drive a single directory past an OS-level
per-directory capacity limit while reporting plenty of free cache byte
budget, and the existing self-healing eviction never engaged for that
failure because it only recognized EDQUOT, not ENOSPC.

  • Root cause (confirmed in production): DiskCache stored every cached
    object for a given path prefix flat in one directory with no sharding
    (pathForFile/pathForIOEntry). On an ext4 filesystem without the
    large_dir feature, a single directory's htree index has a hard ceiling
    on entry count, independent of total filesystem free space or inodes. A
    high-churn cache (e.g. query_result) can drive that ceiling before the
    filesystem's actual byte or inode budget is exhausted. The node's kernel
    log showed ext4_dx_add_entry: ... index full, reach max htree level :2
    / Large directory feature is not enabled at the exact timestamps of the
    application's write disk cache error ... no space left on device
    warnings, while df and mo_fs_cache_bytes{type="inuse"} both showed
    large amounts of headroom.
  • Fix 1 — shard cache directories. Cache files are now spread across
    4096 sub-directories keyed by a stable FNV-1a hash of the object path, so
    no single directory can approach the per-directory entry ceiling
    regardless of cache byte capacity or filesystem feature flags. The hash
    and shard count must not change without handling the previous layout;
    decodeFilePath recognizes both the sharded and the previous flat
    layout, so files written by an older version keep counting toward cache
    capacity after an upgrade and are evicted normally by the existing FIFO
    policy — they are intentionally not migrated (keeps the change minimal
    and avoids a migration path that would itself need lifecycle coverage).
    Delete also invalidates a leftover legacy-layout file for the same path,
    so it cannot later be resurrected by the disk-cache restore path
    (-fs-fix-missing / MO_FS_FIX_MISSING).
  • Fix 2 — classify ENOSPC vs EDQUOT. isDiskFull() only matched the
    string "disk quota exceeded" (EDQUOT semantics), so it never matched
    "no space left on device" (ENOSPC) — the actual error from os.Rename
    in this scenario — and the self-healing ForceEvict path in writeFile
    was never triggered. It is replaced by classifyDiskFull(), which
    distinguishes:
    • EDQUOT — freeing cache files always relieves it, evict as before.
    • ENOSPC — only relieves it when the filesystem itself (checked via
      statfs) is actually short on blocks or inodes. A directory-structure
      limit is not fixed by evicting cache files, and evicting on every
      failed write in that case would just thrash a cache that has plenty of
      byte budget left.
      Concurrent disk-full failures are also coalesced to at most one eviction
      in flight, instead of each failure independently cutting another 10% of
      capacity.

Test plan

  • New tests in pkg/fileservice/disk_cache_shard_test.go:
    • shard hash is pinned to fixed expected values (a changed hash would
      strand every existing cache file after an upgrade)
    • 100k synthetic objects spread roughly evenly across all 4096 shards
    • decodeFilePath accepts both the sharded and the legacy flat layout
    • a cache seeded with legacy-layout files on disk: they are indexed,
      never served (cache miss), and are evicted/deleted first when new
      writes need the space
    • delete removes a leftover legacy-layout file, and the disk-cache
      restore path no longer resurrects an explicitly deleted object from
      one
    • classifyDiskFull distinguishes ENOSPC/EDQUOT via errors.Is and
      via flattened error strings
    • ENOSPC with free blocks/inodes does not evict; ENOSPC with the
      filesystem genuinely exhausted (bytes, inodes, or unknown statfs)
      does evict; EDQUOT always evicts; a source-read error is not treated as
      disk-full
    • 32 concurrent ENOSPC failures against a cache whose simulated
      statfs reports exhausted until the cache frees space result in
      exactly one eviction's worth of bytes freed, not up to 32
  • Fixed 5 existing tests in disk_cache_lifecycle_test.go that wrote
    directly to the pre-sharding on-disk path and needed the shard directory
    created first; no behavioral change to what they verify.
  • GOWORK=off go build/vet ./pkg/fileservice/... clean.
  • pkg/fileservice/... full suite, plain and -race: only
    pre-existing failure is TestLocalWriterCloseCleanup/etl/sync_dir,
    reproduced identically on a clean, unmodified checkout of this branch's
    base commit, unrelated to this change (not touched by this diff).
  • Mutation check: reverted the statfs/single-flight guards to a
    naive "evict on any ENOSPC" implementation and confirmed the new tests
    fail (over-eviction with free space; double eviction under concurrency),
    then restored the real implementation. Repeated the same check for the
    legacy-layout delete fix.

🤖 Generated with Claude Code

…rrectly

DiskCache stored every cached object under one flat directory per cache
instance. On ext4 without the large_dir feature, a single directory's
htree index has a hard entry-count ceiling independent of total free
space or inodes; once a high-churn cache (e.g. query_result) hit it,
every further write into that directory failed with ENOSPC, confirmed
in production via the kernel's "index full, reach max htree level"
warning while the filesystem still had hundreds of GB free.

Cache files are now spread across 4096 sub-directories by a stable
FNV-1a hash of the object path, so no single directory can approach
that ceiling regardless of cache capacity or filesystem feature flags.
decodeFilePath still recognizes the previous flat layout so files
written by older versions keep counting toward cache capacity and are
evicted normally; they are not migrated.

isDiskFull() only matched "disk quota exceeded" (EDQUOT), so it never
recognized "no space left on device" (ENOSPC) and the existing
force-evict self-healing path never ran for this failure. It is
replaced by classifyDiskFull(), which distinguishes EDQUOT (freeing
cache files always helps) from ENOSPC (it only helps when the
filesystem itself, checked via statfs, is actually short on blocks or
inodes; a directory-structure limit is not fixed by eviction and
evicting anyway would just thrash the cache on every failed write).
Concurrent disk-full failures now trigger at most one eviction instead
of compounding independent 10%-of-capacity cuts.

Fixes matrixorigin#30167

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Oct 14, 2026
@CLAassistant

CLAassistant commented Oct 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

loveRhythm1990 and others added 2 commits October 14, 2026 17:48
Two issues from code review on the sharding/ENOSPC fix:

- pathForFile/pathForIOEntry hashed the raw object path to pick a
  shard, but the filename component they build is run through
  filepath.Join, which silently cleans "." segments. "foo/./bar" and
  "foo/bar" therefore collided on the same filename but landed in
  different shards. A delete or overwrite issued through one spelling
  left the other's entry reachable and stale (reproduced via S3FS:
  delete, write new, read still returned the old content). Clean the
  path with path.Clean before both the shard and the filename are
  derived from it, so aliased spellings always resolve to the same
  disk path.

- filesystemExhausted divided totalInodes by 100 to get a 1% free
  threshold. On a filesystem with fewer than 100 inodes total, that
  division truncates to zero, so freeInodes < 0 could never be true
  and zero free inodes was never recognized as exhaustion. Compare by
  cross-multiplication (freeInodes*100 < totalInodes) instead, which
  is exact at any inode count.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@loveRhythm1990

Copy link
Copy Markdown
Contributor Author

Fixed two issues from review:

  1. Path aliasing across shards (disk_cache.go): pathForFile/pathForIOEntry hashed the raw object path to pick a shard, but filepath.Join silently cleans . segments in the filename component it builds. So foo/./bar and foo/bar collided on the same filename but landed in different shards — a delete or overwrite through one spelling left the other's entry reachable and stale. Reproduced via S3FS (delete, write new, read still returned old) and fixed by cleaning the path with path.Clean before deriving both the shard and the filename from it.
  2. Inode-exhaustion check truncates to zero below 100 inodes (filesystemExhausted): totalInodes/100 truncates to zero when total is under 100, so freeInodes < 0 could never be true and zero free inodes was never recognized as exhaustion. Fixed by cross-multiplying (freeInodes*100 < totalInodes) instead of dividing.

Both are covered by new regression tests (TestDiskCachePathsNormalizeDotSegments, TestDiskCacheAliasDelete, TestDiskCacheS3AliasDelete, TestDiskCacheSmallInodeFilesystemTriggersEviction), verified to fail against the pre-fix code and pass after. Full pkg/fileservice suite + -race rerun clean (only the pre-existing, unrelated TestLocalWriterCloseCleanup/etl/sync_dir macOS failure remains, reproduced identically on an unmodified base commit).

🤖 Generated with Claude Code

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 017622bc10dce094d7e283d10be4cb055fdca11d

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: 017622bc10dce094d7e283d10be4cb055fdca11d

Assessment: approve

Reviewed the complete seven-file delta and affected callers. Stable sharding, capacity-accounted legacy aging, and centralized disk-full eviction fit the existing ownership model without migration machinery. The previous alias, inode-threshold, and legacy-delete concerns are resolved; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Current-head fileservice race suite passed: 924 test/subtest passes, 10 skips. Receipt: checks/1792011593894661470-5.json.

  • Legacy deletion/restore regressions passed. Eight diagnostic sync/async write cases passed normally and under race, verifying physical eviction, structural-ENOSPC retention, source-error propagation, and temporary-file cleanup.

  • Reconciled retained command/source/exit receipts and log hashes, including 100 race repetitions each for concurrent eviction and directory lifecycle. Verified 192 native inputs and 46 artifact hashes before reuse.

  • Comparable retained benchmarks: 64-entry reads increased from 2.606 to 2.680 ms and 1105 to 1301 allocations; 4 KiB write/read increased from 198 to 216 µs and 48 to 55 allocations. Successful writes incur no new statfs call.

  • Evidence, design analysis, and receipt/log mappings are retained in /home/xupeng/.local/state/mo-bot/jobs/2a0aad1a6f8b73838d5f188b/attempt-1/validation-audit.json. Final audit receipt 1792011722798846069-4.json passed; source remains unchanged.

Limitations:

  • Real ext4 directory exhaustion and physical quota exhaustion were not reproduced; distribution tests and injected filesystem errors exercised the affected production paths.

  • Local execution covered Linux/amd64. External-service and resource-heavy cases skipped; disk-backed S3 deletion/restore regressions executed.

  • Benchmark samples are short component measurements, not SQL throughput estimates. Standalone issue #30167 text was absent; its stated contract was reviewed through the frozen PR description and discussion.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

queue

⚠️ Invalid commit message

Details

section not found

@loveRhythm1990

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-15 01:47 UTC · Rule: main · triggered by @loveRhythm1990 with the @mergifyio queue command
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-15 01:50 UTC · at 6d2da5490026fd428d7c02fbb794fe5e2598ddec

This pull request spent 3 minutes 31 seconds in the queue, with no time running CI.

Reason

Pull request #30173 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@mergify mergify Bot added kind/bug Something isn't working queued labels Oct 15, 2026

This branch was previously deployed

1 inactive deployment
ci — 6d2da549 Deployed Oct 15, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: DiskCache can exhaust a single ext4 directory's htree capacity (ENOSPC) while isDiskFull() ignores ENOSPC

4 participants