Skip to content

[Bugfix][Store] Reserve bucket metadata size and remove orphaned files on write failure - #5815

Open
zhewenl wants to merge 1 commit into
kvcache-ai:mainfrom
zhewenl:zhewen/upstream-bucket-meta-reserve
Open

zhewenl wants to merge 1 commit into
kvcache-ai:mainfrom
zhewenl:zhewen/upstream-bucket-meta-reserve

Conversation

@zhewenl

@zhewenl zhewenl commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR fixes two gaps in how BucketStorageBackend::BatchOffload accounts for and cleans up a bucket's files.

1. Admission does not reserve the .meta file. BatchOffload admits a bucket with PrepareEviction(file_bytes + bucket->meta_size, ...). meta_size is only set by StoreBucketMetadata, which runs after the data write, so at admission it is still 0:

  • PrepareEviction checks the incoming bucket against max_total_size, max_physical_bytes and the free-space floor (required_size + 256 MiB) as if the bucket had no metadata.
  • The commit then adds the metadata to total_size (committed_data_size starts at bucket->meta_size), and the .meta file takes real disk blocks.

So after each admission, total_size and the bytes on disk can exceed the caps by that bucket's .meta size: with the default bucket_keys_limit of 500 and keys of ~100 bytes, about 50 KiB. On main the offload runs on the store's single heartbeat thread, one bucket at a time, so the overshoot is at most one .meta per disk at a time; it does not accumulate, because the next admission sees the committed size. It grows with the number of buckets in flight if parallel bucket writes (#5339) land. max_physical_bytes is meant to be a hard cap that keeps the store within its disk quota (cgroup / emptyDir), so it should hold exactly.

2. A failed packed io_uring write leaves its data file behind. WriteBucket relies on the file object to unlink itself when a write fails: PosixFile does this when the write fails with FILE_WRITE_FAIL (delete_on_write_fail_). The packed direct write path with io_uring (use_uring + MOONCAKE_OFFLOAD_BUCKET_DIRECT_WRITE=packed) goes through UringFile::write_aligned, which returns the ring's error without recording it (make_error is not called), so the file is not unlinked. The size-mismatch and staging-buffer allocation failures on that branch also return without removing the file. BatchOffload's failure branch then only releases the reservation, and never calls CleanupOrphanedBucket. Nothing indexes the partial file, so eviction never reclaims it, and it counts against max_physical_bytes until the next start, when Init removes it as an orphan. A review probe reproduced this on main: with use_uring=true, packed, RLIMIT_FSIZE = 128 KiB and a ~512 KiB bucket, the write fails with EFBIG and <id>.bucket (131072 bytes) stays in the directory. The buffered path with the same limit leaves nothing (posix_file.cpp: Deleted corrupted file).

Fix.

  • Encode the bucket metadata once, right after BuildBucket and before admission. Set meta_size from the encoded length so that PrepareEviction reserves the real size, and pass the same bytes through WriteBucket to StoreBucketMetadata, so the reserved size and the written size always match. meta_size is not serialized (YLT_REFL(BucketMetadata, data_size, keys, metadatas)), so setting it does not change the encoding. StoreBucketMetadata no longer needs the bucket, so it takes only the id, the disk and the encoded bytes.
  • When WriteBucket fails, BatchOffload calls CleanupOrphanedBucket(bucket_id, disk_index) before releasing the reservation, so the space stays reserved until the files are gone. This is safe on every failure path: the bucket id is unique to this call, and the bucket was never committed to buckets_ or object_bucket_map_, so no reader, eviction or pending registration ([Bugfix][Store] Protect pending bucket registrations during concurrent offload #5337's offload_notification_pending_ is only set on committed buckets) can refer to it. On the paths that already unlinked their files (buffered writes, datasync and .meta failures), CleanupOrphanedBucket finds nothing and ignores ENOENT. The commit-time failures after the write already clean up (CleanupOrphanedBucket for an all-duplicate bucket, RollbackCommittedBucket when the completion handler fails).

Related open PRs.

Suggested Merge Priority

  • P0 — Urgent: Critical security vulnerability, data loss/corruption, or widespread production outage requiring immediate action
  • P1 — High: Significant correctness or stability issue in existing functionality, or a regression blocking users without a practical workaround
  • P2 — Normal: Routine bug fix, validated performance/compatibility improvement, or new feature for a confirmed use case
  • P3 — Low: Experimental feature, optional enhancement, refactoring, or cleanup with no urgent user impact

Module

  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake Store (mooncake-store)
  • Mooncake Conductor (mooncake-conductor)
  • Reshard (mooncake-reshard)
  • Mooncake EP (mooncake-ep)
  • Mooncake PG (mooncake-pg)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • Common (mooncake-common)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Breaking change
  • Documentation update
  • Performance improvement
  • Other

How Has This Been Tested?

New tests:

  • StorageBackendTest.BucketAdmissionReservesMetadataSize offloads one 64-key bucket (long keys, one-byte values, so the .meta is a large part of it). A first offload into an empty backend with room to spare gives the footprint: the committed total_size, which equals the sizes of the .bucket and .meta files. Then, each in a fresh backend:
    • max_total_size = footprint - 1: must be rejected, with no files and nothing committed.
    • max_total_size = footprint: must be admitted, with total_size == footprint. This shows the reservation is exactly the metadata size, not more.
    • max_physical_bytes = footprint - 1: must be rejected.
  • StorageBackendTest.UringPackedBucketWriteFailureRemovesPartialFile (built with USE_URING; skipped if io_uring cannot be initialized or the packed path does not work on the test filesystem): the review probe as a regression test. A packed io_uring write of a 512 KiB bucket cut short by RLIMIT_FSIZE = 128 KiB must fail, leave no file and no committed size, and the same batch must go through once the limit is lifted (the reservation was released).
  • StorageBackendTest.BucketWriteFailureRemovesPartialFiles: the same on the buffered path, with the data file and then the .meta file cut short. main already passes it; it checks that the new cleanup is harmless where the file was already removed.

Test commands:

cmake -S . -B build -G Ninja -DUSE_CUDA=OFF -DWITH_STORE=ON -DBUILD_UNIT_TESTS=ON \
  -DUSE_ETCD=OFF -DSTORE_USE_ETCD=OFF -DWITH_STORE_RUST=OFF -DWITH_P2P_STORE=OFF
ninja -C build
cd build/mooncake-store/tests
./storage_backend_test --gtest_filter='*BucketAdmissionReservesMetadataSize*:*BucketWriteFailureRemovesPartialFiles*:*UringPackedBucketWriteFailureRemovesPartialFile*'
./storage_backend_test --gtest_filter='-*OffsetAllocatorReadPath*'
./file_storage_test
./bucket_direct_write_test
cd ../.. && ctest --test-dir build/mooncake-store

Before (this branch with the meta_size assignment moved back after the write, as on main, and the new CleanupOrphanedBucket call removed): both "short" cases are admitted and overshoot the cap, and the failed packed write leaves its file.

storage_backend_test.cpp:6619: Failure
Value of: outcome.admitted
  Actual: true
Expected: false
the bucket's metadata does not fit under the cap
Google Test trace:
storage_backend_test.cpp:6611: quota_short
storage_backend_test.cpp:6622: Failure
  outcome.total_size
    Which is: 14827          <- cap was 14826
...
storage_backend_test.cpp:6611: physical_short
[  FAILED  ] StorageBackendTest.BucketAdmissionReservesMetadataSize
[       OK ] StorageBackendTest.BucketWriteFailureRemovesPartialFiles
E... storage_backend.cpp:3202] write_aligned failed for: 7354684950535, error: INTERNAL_ERROR, errno=27 (File too large)
E... storage_backend.cpp:1764] Failed to write bucket with id: 7354684950535
storage_backend_test.cpp:6743: Failure
  CountDataFiles(config.storage_filepath)
    Which is: 1
a failed io_uring bucket write left a partial file behind
[  FAILED  ] StorageBackendTest.UringPackedBucketWriteFailureRemovesPartialFile

After:

[       OK ] StorageBackendTest.BucketAdmissionReservesMetadataSize
[       OK ] StorageBackendTest.BucketWriteFailureRemovesPartialFiles
E... storage_backend.cpp:3200] write_aligned failed for: 7354689756270, error: INTERNAL_ERROR, errno=27 (File too large)
E... storage_backend.cpp:1763] Failed to write bucket with id: 7354689756270
I... storage_backend.cpp:3296] Cleaned up orphaned bucket data file: .../target/7354689756270.bucket
[       OK ] StorageBackendTest.UringPackedBucketWriteFailureRemovesPartialFile

Test results:

  • Unit tests pass
  • Integration tests pass (if applicable)
  • Manual testing done (describe below)

Results on this branch (aarch64, Linux 6.17 with 64 KiB pages, USE_CUDA=OFF, io_uring available):

  • storage_backend_test --gtest_filter='-*OffsetAllocatorReadPath*': 144/144 passed, including the three new tests (the uring one ran, not skipped).

  • file_storage_test (67 passed, 1 skipped: UringStagingBufferUnpinnedOnDestruction, environment), bucket_direct_write_test (60/60), local_ssd_test, file_storage_config_test: passed.

  • ctest --test-dir build/mooncake-store --parallel 8: 235/237 passed. The two failures fail identically on unmodified main on this host and are environmental:

    • storage_backend_test aborts in OffsetAllocatorReadPath_*: the test's guard page uses a 4 KiB mprotect on a 64 KiB-page kernel, so it throws bad_alloc.
    • transfer_task_test fails in BatchGetOffloadObjectCopiesPinnedHostToGpu: there is no pinned host buffer in a CPU-only build.
  • Revert check: as shown under "Before", BucketAdmissionReservesMetadataSize and UringPackedBucketWriteFailureRemovesPartialFile fail without the fix; BucketWriteFailureRemovesPartialFiles passes either way.

Checklist

  • Every commit I contribute includes my Signed-off-by trailer certifying the DCO
  • I have performed a self-review of my own code
  • I have formatted my code using ./scripts/code_format.sh
  • I have run pre-commit on the files changed in this PR and all hooks pass
  • I have updated the documentation (if applicable)
  • I have added tests to prove my changes are effective
  • For changes >500 LOC: I have filed an RFC issue

AI Assistance Disclosure

  • No AI tools were used
  • AI tools were used (specify below)

Claude Code (Claude Opus 5.5) ported the reservation fix from our fork to main, turned an io_uring write-failure probe into a regression test and added the cleanup, confirmed that the new tests fail before the fix, and ran the test suites.

🤖 Generated with Claude Code

…s on write failure

Two gaps in BatchOffload's handling of a bucket's on-disk footprint.

Admission reserved nothing for the .meta file. BatchOffload admits a
bucket with PrepareEviction(file_bytes + bucket->meta_size), but
meta_size was only set by StoreBucketMetadata after the write, so it was
0 at admission. PrepareEviction checked max_total_size,
max_physical_bytes and the free space floor as if the bucket had no
metadata, while the commit then added the metadata to total_size: an
admitted bucket could overshoot both caps by the size of its .meta (tens
of KiB for a full bucket of 500 keys). BatchOffload now encodes the
metadata once, before admission, sets meta_size from it so that
PrepareEviction reserves the real size, and passes those same bytes to
StoreBucketMetadata, which no longer needs the bucket.

A failed write could leave the bucket's data file behind. WriteBucket
relies on the file to unlink itself when a write fails, which PosixFile
does for FILE_WRITE_FAIL. The packed direct write path with io_uring
does not: UringFile::write_aligned returns the ring's error without
recording it, and that branch's size-mismatch and staging-buffer
allocation failures return without touching the file either. Nothing
indexes the partial file, so eviction never reclaims it, and it counts
against max_physical_bytes until the next start removes it as an orphan.
BatchOffload now calls CleanupOrphanedBucket for the bucket id when the
write fails, before it releases the reservation. The id is not shared
and the bucket was never committed, so this cannot touch another bucket
or a pending registration, and a file the failed write already removed
is skipped.

Tests:
- StorageBackendTest.BucketAdmissionReservesMetadataSize: the footprint
  is taken from a first offload with room to spare; a quota of
  footprint - 1 or a physical cap of footprint - 1 rejects the bucket, a
  quota of exactly footprint admits it.
- StorageBackendTest.UringPackedBucketWriteFailureRemovesPartialFile
  (USE_URING; skipped without io_uring): a packed direct write cut short
  by RLIMIT_FSIZE leaves no file and no reservation behind.
- StorageBackendTest.BucketWriteFailureRemovesPartialFiles: the same on
  the buffered path, with the data file and then the .meta file cut
  short. That path already cleaned up; the test keeps the extra cleanup
  harmless there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Zhewen Li <zhewenli@inferact.ai>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T04:06:40.015689Z 910d8e1 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added run-ci Store size/M 100-1000 changed lines (additions + deletions) labels Nov 25, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci size/M 100-1000 changed lines (additions + deletions) Store

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant