Skip to content

fileservice: reserve disk-cache quota for temp and in-progress writes #25764

Closed

Description

@LeftHandCold

Summary

DiskCache accounts a file only after the temporary file has been fully copied, synced, closed, and renamed. Concurrent and unknown-length writes can therefore consume substantially more physical disk than the configured cache capacity.

Root cause

DiskCache.writeFile creates a temp file and streams the entire reader into it (pkg/fileservice/disk_cache.go:536-587). FIFO accounting is updated only after rename (disk_cache.go:592-601).

The pre-write eviction estimate is non-zero only when the reader is an *os.File with a known size (disk_cache.go:559-568). S3 streaming readers and other unknown-length readers can write with no reservation. Multiple writers can all observe the same indexed usage because temp and in-progress bytes are absent from d.cache.Used().

ENOSPC handling is reactive: it attempts eviction after the write has already failed. It cannot keep concurrent temp files within the configured capacity or protect a shared filesystem from transient exhaustion.

Impact

  • concurrent full-object/range cache fills can exceed DiskCache capacity;
  • temp files can exhaust the CN volume and affect logs, spill, checkpoints, or other colocated services;
  • accounting and operational metrics under-report physical cache consumption;
  • unknown-length streams have no admission bound.

Proposed design

Introduce cancellable byte reservations for temp and in-progress writes:

  1. reserve known sizes before creating/writing the temp file;
  2. for unknown sizes, grow a reservation in bounded chunks and stop when the next chunk cannot be reserved;
  3. convert the reservation to resident accounting only after successful rename/index insertion;
  4. release it on every open/copy/sync/close/rename/cancel failure;
  5. track resident, reserved/in-flight, temp, and orphan bytes separately;
  6. define how reservation interacts with eviction and shared-volume headroom.

This issue intentionally does not propose a partial PR until the reservation and rollback contract is agreed.

Acceptance criteria

  • physical resident + temp + in-flight cache bytes stay within the configured bound plus explicitly documented filesystem headroom;
  • reservations are cancellable and cannot leak on any error path;
  • concurrent known- and unknown-length writer tests cannot overcommit quota;
  • ENOSPC/fault-injection tests leave no unindexed temp files.

Activity

  1. added
    kind/bug
    severity/s0
    and removed on Jul 15, 2026
  2. self-assigned this
    on Jul 15, 2026
  3. added and removed
    severity/s0
    on Jul 15, 2026
  4. LeftHandCold commented on Jul 15, 2026

    @LeftHandCold
    CollaboratorAuthor

    Why this issue does not have a small fix PR yet

    The problem is not an isolated missing Evict call. The current DiskCache accounting model only knows about resident, indexed files, while the failure mode is caused by temporary and in-progress physical bytes that exist before a file becomes resident.

    Current write/accounting sequence

    DiskCache.writeFile currently follows this sequence:

    1. create a temporary file (pkg/fileservice/disk_cache.go:536-545);
    2. open the source reader;
    3. optionally estimate the source size only when the reader is an *os.File (disk_cache.go:559-568);
    4. copy the complete source into the temp file and Sync it (disk_cache.go:570-580);
    5. obtain the actual size, close, and rename the temp file (disk_cache.go:583-594);
    6. only after rename, add/replace the file in FIFO accounting (disk_cache.go:599-601).

    Until step 6, the bytes are physically present on disk but absent from d.cache.Used(). S3 full-object streaming and other non-file readers commonly have no size estimate at step 3.

    For example, if the configured cache has 1 GiB available and four goroutines concurrently stream 1 GiB objects, all four can create and grow temp files before any of them updates FIFO usage. Physical usage can grow by roughly 4 GiB even though every writer individually observes the same 1 GiB capacity state.

    The existing ENOSPC path is reactive: it attempts eviction only after a write has already failed. That can help a later request but cannot protect the shared volume from transient exhaustion.

    Why the obvious small fixes are insufficient

    • Evict once before writing: concurrent writers still observe usage before any temp bytes are accounted, and unknown-length readers still have no reliable eviction target.
    • Limit the number of writers: a semaphore bounds item count, not bytes; one or two very large streams can still exhaust the disk.
    • Use Stat for the source size: this only works for *os.File, not the S3 streaming path that matters for full-object caching.
    • Account the temp file after copy: that is still too late because the physical overcommit has already happened.
    • Use the configured cache capacity as filesystem free space: unsafe when the volume is shared with logs, spill, checkpoints, or other services; an explicit headroom policy is required.

    These mitigations may reduce probability, but none establishes the invariant that resident + temp + in-flight cache bytes remain within a defined physical budget.

    Required correctness model

    A correct implementation needs a reservation token with an explicit lifecycle, for example:

    Reserve(ctx, estimatedBytes) -> token
    token.Grow(ctx, additionalBytes)  // unknown-length streams
    token.Commit(actualBytes)         // rename/index success: in-flight -> resident
    token.Release()                   // every failure/cancel/duplicate path
    

    The implementation must define and preserve the following invariants:

    1. reservation is atomic across all full-file and range writers sharing the DiskCache;
    2. waiting for quota is context-cancellable;
    3. unknown-length streams grow their reservation in bounded chunks before writing those chunks;
    4. successful rename/index insertion converts reserved bytes to resident accounting exactly once;
    5. open/copy/sync/close/rename/cancel failures release all reservation exactly once;
    6. duplicate/per-path write suppression cannot leak or double-commit a token;
    7. eviction and reservation waits have a fixed lock order and cannot deadlock with updatingPaths or FIFO callbacks;
    8. physical headroom and temp/orphan bytes are visible through separate metrics.

    Modification cost and risk

    This crosses several contracts rather than one function:

    • Accounting/data model: FIFO currently accounts only resident entries. DiskCache needs an in-flight byte counter or reservation manager whose state is coordinated with, but not confused with, FIFO Used.
    • All write producers: both range-cache updates and full-object SetFile/S3 streaming must use the same reservation contract.
    • Unknown-size streaming: the copy loop must reserve before each bounded growth step, handle cancellation, and stop cleanly when capacity cannot be extended.
    • Commit/rollback: every return path around reader open, io.Copy, Sync, Stat, Close, Rename, duplicate detection, and cache admission needs an audited release/commit decision.
    • Concurrency/lock ordering: reservation waits, eviction, updatingPaths, and FIFO callbacks must not form a lock cycle or starve cache writers.
    • Error semantics: writeFile currently logs and masks cache-write errors. We need to decide which quota/cancellation errors remain best-effort cache misses and which must be observable through metrics or return values.
    • Startup/recovery: temp and unindexed files found by the loader need a defined cleanup/accounting policy so restarts do not bypass the physical budget.
    • Tests: deterministic concurrent known-size and unknown-size writers, cancellation while waiting/growing, ENOSPC, short copy, sync/close/rename failures, duplicate writers, exact once-release, and restart/orphan cleanup all need coverage.

    The highest regression risks are quota-token leaks that permanently block caching, double release/commit that corrupts accounting, and lock-order mistakes that turn disk pressure into a service hang.

    Proposed implementation sequence

    1. agree on the physical budget/headroom contract and reservation API;
    2. add reservation state and observability without changing admission behavior;
    3. integrate known-size writers with complete commit/rollback tests;
    4. integrate unknown-size streaming with chunked growth and cancellation;
    5. cover loader/temp/orphan recovery and high-concurrency fault injection;
    6. enable hard enforcement only after the accounting invariants are demonstrated.

    This is implementable, but it should be a dedicated design-and-fix PR rather than a small patch that only lowers the probability of overcommit. A partial PR that claims to fix the capacity invariant without covering the lifecycle above would be more dangerous than keeping the limitation explicit and tracked here.

  5. LeftHandCold commented on Jul 31, 2026

    @LeftHandCold
    CollaboratorAuthor

    2026-08-01 current-main re-evaluation

    Rechecked against main@ecc389d4206b310784595ef4e1c131c97908ab4a. The defect is still present, and the decision remains deferred / no partial PR.

    Current code still has the same accounting gap

    DiskCache.writeFile still:

    1. creates a temporary file;
    2. opens and fully copies the reader;
    3. syncs, stats, closes, and renames the temporary file;
    4. only then inserts/replaces the resident FIFO entry.

    Before step 4, physical temporary and in-flight bytes are absent from d.cache.Used(). The pre-write estimate is still available only for an *os.File; the production S3 full-object streaming path passes a fullObjectDiskCacheReader, so it remains unknown-length and unreserved. Different paths may write concurrently.

    Live error paths close and remove their temporary file, but that does not provide admission control. After a process crash, startup keeps cache temp files younger than eight hours, and those bytes are also outside FIFO accounting.

    Q1-Q3 result

    • Q1: ordinary returned-error cleanup exists, but crash/restart orphan bytes do not enter resident accounting.
    • Q2: any future quota wait must be context-cancellable and must not inherit the updatingPaths / eviction callback wait chain.
    • Q3: configured disk-cache capacity still does not bound resident + temp + in-flight bytes.

    Why the small alternatives remain unsafe

    • pre-eviction is not an atomic reservation;
    • a writer semaphore bounds item count, not bytes;
    • Stat does not cover S3/unknown-length streams;
    • accounting after copy happens after physical overcommit;
    • treating cache capacity as shared-volume free space has no headroom contract.

    A complete fix still needs an atomic Reserve/Grow/Commit/Release lifecycle covering range/full-file producers, dynamic capacity, eviction, cancellation, duplicate paths, every write failure, and restart/orphan cleanup. The highest regression risks remain leaked quota that permanently disables caching and lock-order mistakes that turn disk pressure into a service hang.

    Therefore I am keeping this Issue deferred until that contract and its fault-injection matrix can be implemented as one dedicated change.

  6. loveRhythm1990 commented on Oct 14, 2026

    @loveRhythm1990
    Contributor

    Cross-linking a related-but-distinct issue: #30167 — observed a production ENOSPC on DiskCache writes caused by ext4 per-directory htree capacity exhaustion (unsharded cache directory), not the concurrent/unknown-length byte-accounting gap described here. Also notes isDiskFull() doesn't recognize ENOSPC, so the reactive eviction mentioned in this issue's root-cause section never actually engages for that error string.

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

Metadata

Metadata

Assignees

Labels

deferredkind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions