Skip to content

refactor(fileservice): S3-FIFO memory cache that owns its references, LRU disk cache - #32275

Merged
mergify[bot] merged 18 commits into
matrixorigin:mainfrom
cpegeric:s3fifo_refactor
Nov 7, 2026
Merged

mergify[bot] merged 18 commits into
matrixorigin:mainfrom
cpegeric:s3fifo_refactor

Conversation

@cpegeric

@cpegeric cpegeric commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #32274

What this PR does / why we need it:

Design: docs/design/20261106-fileservice-cache-ownership.md v2 at 4deacbe750 (design-only commit, for design review before implementation review; v1 was 279858c).

The memory and meta caches move to a new fileservice/s3fifo package, and the data disk cache now uses a sharded lrucache. fifocache is deleted. The diff is +3288 / −3204 lines.

s3fifo (memory and meta caches)

  • The cache owns each value's reference counts. Callbacks only report insertions and removals.
  • A key becomes visible only once it is fully published. No half-inserted keys.
  • It has 256 index shards and 16 policy shards. Eviction runs on one goroutine at a time.
  • A Set leaves eviction to an evictor that is already running, unless the cache is more than 1/16 over capacity. Then it waits, so memory stays bounded.
  • Removal callbacks run outside every lock.
  • Replace larger than the capacity deletes the key.
  • Zero-size values are not remembered in the ghost queue.
  • Ghost entries are accounted the same way as in fifocache.

lrucache (data disk cache and index-file cache)

  • The data disk cache now evicts least recently used files first, as the index-file cache already did.
  • Keys are spread over 16 shards, each with its own lock. Each item carries a global stamp of its last use, and eviction takes the evictable item with the oldest stamp across the shards at the moment it removes it. An item that becomes evictable, or is added with SetOldest, while an eviction scans the shards can be passed over by that eviction.
  • The evictor picks the oldest shard from each shard's published tail stamp, without taking locks. It then locks that shard and retries if its oldest item no longer has the stamp it read.
  • Set and Replace leave eviction to an evictor that is already running. That evictor checks again when it is done, and evicts in batches of 64.
  • Eviction callbacks run outside every lock, so a callback may use the cache.

Whole-object prefetch and downloads

  • A table's narrow reads switch back to whole-object prefetch only once another whole object fits in the disk cache. Before, the quiet period always ran out after a pause or a TPC-H round, and the table downloaded whole objects again only to have them evicted unread.
  • Every read of an object being downloaded, including the read that started the download, takes the bytes already written and returns once its own bytes are written; the rest downloads in the background. A read waits for bytes not yet written if they arrive no more than disk-download-max-extra-wait (default 200 ms) later than a range read could fetch them, or if they are more than an eighth of what the download still writes before them.
  • New metrics mo_fs_disk_cache_download_read_total{type} and mo_fs_disk_cache_download_declined_bytes_total.

Tests

  • Design contracts: each contract of the design doc is checked as a black box through the public API: cache-owned references, publication, the used-byte bound under 16 parallel writers, notifications calling into the cache and ghost re-insertion (s3fifo); LRU order, held entries, oldest inserts and callbacks outside locks (lrucache); an object being downloaded fetched from storage once, and a read far behind a download reading its range (S3FS.Read). 12 tests, each ×30 under -race.
  • Downloads: reads return their bytes once written; fall back when the download fails, is cancelled or ends short; read the published file after publication; decline a download far behind; the margin reaches the disk cache. A narrow-read signal stays on without room past its longest quiet period.
  • s3fifo model: checked against a sequential model of the algorithm. Used bytes, small/main/ghost queue bytes and key membership are compared after every one of 20k random get/set/replace/delete ops.
  • lrucache model: checked against a single-list LRU model. The full recency order and used bytes are compared after every one of 10k random set/SetOldest/get/delete/replace/hold ops.
  • Concurrency: a concurrent test checks used bytes and that every eviction gets all its callbacks exactly once.
  • Concurrent Get during eviction: TestScanEvictsOldestAfterConcurrentGet touches the picked shard's oldest item while the eviction scan reads another shard, and checks that the globally oldest item is evicted.
  • Mutation checks: each regression test fails without its fix. The lrucache model test also fails if eviction picks any shard but the oldest, or if SetOldest is stamped as newest.
  • Race, s3fifo: 37 focused tests repeated under -race (count 100, 50, 30 or 2 depending on test length).
  • Race, lrucache and the disk cache: the LRU tests ×50, TestDiskCacheReindexBeforeEvictionStartKeepsFile ×50, and all TestDiskCache* and index-file-cache tests ×5, all under -race.
  • Packages: s3fifo, lrucache, fileservice and objectio each run once under -race.
  • After merging current main: everything builds, and fileservice and objectio pass.

Benchmarks

Setup: one CN, MinIO. TPC-H is SF10 (5.0 GB in MO). wiki_all 1M is 768-D vectors with an IVF-Flat index (lists=1000, probe_limit=8): 2.9 GB of table plus 2.9 GB of index. TPC-C is 10 warehouses (about 1 GB), 50 terminals.

Partly cached: 1 GB memory cache, 4 GB disk cache

Neither workload fits in the caches, so each round evicts the other's data. Each benchmark ran twice.

Final check, TPC-H → wiki → TPC-C. Against main, one run each, with tpcc restored from the same snapshot (and left 2 minutes for the restore's merges) before each run; cold start; 2 cycles of one TPC-H round, one wiki round and 5 min of TPC-C (10 warehouses, 50 terminals). Emulated S3 is a proxy in front of MinIO adding 25 ms per request and capping each response at 100 MB/s.

main, MinIO this PR, MinIO main, emulated S3 this PR, emulated S3
TPC-H, cycle 1 / 2 48.5 s / 74.9 s 32.7 s / 39.3 s 78.4 s / 100.9 s 32.5 s / 43.3 s
wiki filter, cycle 1 (p95) 15.7 s (792 ms) 16.1 s (663 ms) 45.3 s (2,135 ms) 29.7 s (1,656 ms)
wiki filter after TPC-H, cycle 2 (p95) 15.8 s (790 ms) 7.1 s (200 ms) 48.6 s (2,209 ms) 21.5 s (1,536 ms)
wiki nofilter / proj, cycle 2 1.95 s / 2.08 s 2.88 s / 2.16 s 6.46 s / 5.11 s 1.92 s / 1.91 s
TPC-C tpmC, cycle 1 / 2 15,664 / 14,743 15,516 / 14,236 15,313 / 14,149 15,689 / 13,933
S3 requests, whole run 45,777 40,432 45,338 38,345
bytes from object storage 93.7 GB 52.7 GB
  • The MinIO PR column is 279858c with disk-download-max-extra-wait = 200 ms, before the duplication bound; the emulated-S3 PR column is 4deacbe with defaults.
  • TPC-C is within ±3.5% of main in every run, the noise between runs.
  • TPC-H only, 2 cold rounds behind the emulated S3: main 135.5 s, 4,973 requests, 61.9 GB; this PR at 200 ms 49.3 s, 2,193 requests, 33.6 GB.

Swap test (measured at 76ddc0f, before the prefetch and download changes). Cold start, then 4 cycles of one TPC-H round (22 queries) followed by one wiki round (filter, nofilter and proj, 100 queries each). Results drifted by up to 50% over the evening, so each table compares only runs that alternated in one session.

main vs this PR at 76ddc0f (sharded LRU disk)

main this PR
TPC-H total, 4 rounds 237.0 s / 196.4 s 119.2 s / 141.1 s
TPC-H S3 reads per round 3.3k–4.1k 1.5k–2.0k
S3 reads, whole run 17,623 / 16,422 9,770 / 10,035
Disk hit ratio .9922 / .9926 .9955 / .9952
wiki total 64.1 s / 53.6 s 75.5 s / 64.3 s
wiki nofilter/proj, avg per query 19.1–19.9 ms 19.0–20.2 ms, with one round at 35.5 ms

Disk policy, with this PR's memory cache (S3-FIFO disk at 1107dd6, single-lock LRU disk at d62e924)

S3-FIFO disk single-lock LRU disk
TPC-H total 199.7 s / 209.8 s 145.7 s / 152.7 s
S3 reads, whole run 16,190 / 16,886 8,687 / 8,789
TPC-H S3 reads per round 3.3k–3.6k 1.5k–2.0k
wiki total 66.7 s / 55.1 s 55.9 s / 56.9 s

Sharding, single-lock (d62e924) vs 16-shard LRU (76ddc0f)

single-lock LRU sharded LRU
TPC-H total 126.0 s / 117.8 s 120.4 s / 117.8 s
S3 reads, whole run 12,910 / 8,473 9,012 / 7,882
wiki total 81.8 s / 84.3 s 81.0 s / 81.5 s
  • Every policy stays steady across workload swaps.
  • S3-FIFO on disk evicts a file unless it is read again soon after insertion. TPC-H re-reads its files one full round later, so S3-FIFO evicts them before they are reused.
  • Sharding does not change hit ratios or end-to-end time.

TPC-H, cold start, 2 rounds (earlier build, before 1107dd6, S3-FIFO in memory and on disk; total seconds for both rounds)

run main S3-FIFO
1 126.5 s 88.5 s
2 84.0 s 83.4 s

The memory hit ratio is equal or higher than main's, and S3 reads are similar or lower.

wiki_all 1M, warm (same earlier build): memory hit ratio .689 vs main's .685–.690; latency about 22.2 ms on both.

Fully cached: 14 GB memory cache, 20 GB disk cache

All the data fits on disk, so nothing is evicted. This measures the cost of a cache hit rather than the eviction policy. Runs alternated main and this PR.

Final check, TPC-H → wiki → TPC-C, fully cached. Head 4deacbe with defaults against main, one run each, same procedure as the partly cached final check.

main this PR
TPC-H, cycle 1 / 2 12.75 s / 9.29 s 12.69 s / 9.72 s
wiki filter, cycle 1 (p95) 9.57 s (456 ms) 8.96 s (369 ms)
wiki filter, cycle 2 (p95) 0.70 s (10.2 ms) 0.72 s (11.0 ms)
wiki nofilter / proj, cycle 2 0.45 s / 0.43 s 0.39 s / 0.44 s
TPC-C tpmC, cycle 1 / 2 16,223 / 15,256 15,696 / 15,700
S3 requests, whole run 40,235 39,324

Even on every measure; TPC-C differs by −3.2% and +2.9%.

TPC-H and wiki (measured at 76ddc0f, before the prefetch and download changes). Cold start, then 2 cycles of one TPC-H round and one wiki round. Cycle 1 fills the caches and cycle 2 is measured.

cycle 2 main this PR
TPC-H total 8.08 s / 8.47 s 8.19 s / 8.45 s
wiki filter 0.51 s / 0.44 s 0.45 s / 0.44 s
wiki nofilter 0.40 s / 0.38 s 0.39 s / 0.38 s
wiki proj 0.42 s / 0.42 s 0.42 s / 0.41 s
TPC-H S3 reads 0 / 237 0 / 0

Both read the same items. Even with 14 GB, TPC-H hits memory for 283k of 688k reads, and the other 405k all hit the disk cache.

TPC-C (measured at 76ddc0f). Restored from the same snapshot before each run, then cold start and 5 minutes of TPC-C.

main this PR
tpmC 15,771 / 16,145 16,375 / 16,282
tpmTOTAL 35,070 / 35,747 36,447 / 36,049

No errors in any run.

Disk-cache hit (measured at 76ddc0f; 4 KB random read from 4,096 cached 64 KB files, ns/op)

threads main this PR
1 20,127 / 19,842 20,194 / 19,990
4 7,375 / 7,341 7,287 / 7,464
12 12,431 / 12,460 12,171 / 12,153

Opening and reading the file dominates each hit. Both make 26 allocations per read.

  • Fully cached, this PR is even with main on TPC-H, wiki and TPC-C.

Micro-benchmarks

Micro, memory cache (ns/op, main → this PR at 1107dd6)

-4 -12
ParallelSet 98 → 85 90 → 72
GetOrSet 50 → 44 47 → 34
Evict 569 → 220 458 → 152
MemCacheSetParallel ~300 → ~497 ~270 → ~548
  • MemCacheSetParallel looks faster on main only because main stops evicting and stays at about 200% of capacity in this benchmark. Its Sets do no work; this PR stays within its bound.
  • Sequential Set: about 650 → 677 ns/op.
  • Allocations per Set: 3 → 2.

Micro, lrucache (parallel Get-or-Set, ns/op; single lock at d62e924, 16 shards at 44eadb1)

threads single lock 16 shards
1 133 200
4 343 106–115
12 706 143

The extra cost on one thread is small next to the file I/O behind each disk cache operation.

Limits

  • Wiki vs main at 76ddc0f: the filtered wiki phase was about 11 s slower than main over 4 cycles, from LRU on disk, not from sharding. The prefetch and download changes reversed this: in the final check the filtered phase after TPC-H takes 7.1 s against main's 15.8 s.
  • Remote object storage: measured behind an emulated S3 (25 ms, 100 MB/s), not a real deployment. disk-download-max-extra-wait trades latency for fewer requests; the metrics show how reads of downloading objects are served.
  • TPC-C: within ±3.5% of main in every run; run-to-run variance.
  • Variance: the first filtered wiki round after a TPC-H round varies by about 2× in every configuration, and TPC-H rounds by 20–40% between runs.

🤖 Generated with Claude Code

cpegeric and others added 4 commits November 5, 2026 16:15
Replace fifocache with pkg/fileservice/s3fifo for the memory cache, the
objectio meta cache and the disk cache index.

- The cache retains a value when it inserts it and releases it once the
  value has left the cache, outside its locks; notifications are optional
  and no longer carry reference counting.
- Keys are indexed in 256 shards and queued in 16 policy shards; every
  push is ordered globally and eviction takes the oldest member, so the
  shards evict as one S3-FIFO. One goroutine evicts at a time.
- A Set inserts, makes its value evictable once its insertion is
  notified, then evicts until Used is within the capacity, waiting for
  the evictor: Used no longer stays over the capacity after Sets return.
- The ghost queue counts only the entries it remembers; groups are an
  intrusive list, so DeletePaths needs no scan.
- A panic committing a reservation rolls back the charge and the cache's
  reference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Set that finds another goroutine evicting returns, unless Used is over
the ceiling, a sixteenth over the capacity, where it waits to evict too.
The goroutine evicting checks Used again each time it lets go of the
evictor, so it evicts the bytes of the Sets that left eviction to it.

A Set whose key is cached returns after one index check, a value is
published under the index shard lock only, and a Set evicts in small
batches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ghost entries keep counting their bytes until they leave the ghost
queue, as the cache it replaces did, which restores the warm hit ratio.
A read retries its frequency bump until it lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The data disk cache now evicts least recently used files, as the index-file
cache does. With TPC-H and wiki_all 1M alternating on one server, TPC-H reads
about half as many objects from S3 and runs about 27% faster; wiki_all is
unchanged. The LRU cache now runs eviction callbacks outside its lock, so a
callback may use the cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cpegeric and others added 2 commits November 5, 2026 21:36
Keys are spread over 16 shards with their own locks, and a global stamp of
each item's last use keeps eviction least recently used across the shards.
Set and Replace leave eviction to a running evictor, which evicts in batches
and checks again when it is done. Parallel Get-or-Set at 12 threads drops
from about 706 to 143 ns/op.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each contract of docs/design/20261106-fileservice-cache-ownership.md checked
through the public API: cache-owned references, publication, the used-byte
bound, notifications calling into the cache and ghost re-insertion for the
S3-FIFO caches; LRU order, held entries, oldest inserts and callbacks outside
locks for the disk caches; and an object being downloaded fetched once, with a
read far behind the download reading its range.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cpegeric and others added 3 commits November 6, 2026 18:50
…tarted it

The read that starts a whole-object download waited for either the download to
start or the fill to end. When the source failed right after the read's bytes
were written, both were ready and the select could pick the fill's error, failing
a read whose bytes were downloaded; TestS3FSReadFullObjectToDiskCacheStreamingErrorAfterCapture
failed about half the time. The read now prefers a started download, keeping the
fill's result for later.

Readers also reopened the download's file by name, which a publication or a failed
download's cleanup could remove first. A download now keeps one read handle,
closed once it is retired and the last reader is done, and the read that starts a
download holds it before any byte is fetched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gain

A read beyond the max extra wait read its range at once. When its bytes are
more than an eighth of what the download still writes before them, a range
read fetches again most of what the download is about to write, competing with
it; such a read now waits for the download instead, bounded by the predicted
time plus the margin. The new mo_fs_disk_cache_download_declined_bytes_total
metric counts the bytes range reads fetch again.

disk-download-max-extra-wait defaults to 200 ms, the budget of the previous
fixed wait for a downloading object. On TPC-H SF10, two cold rounds at 1 GB
memory and 4 GB disk, 200 ms took 47.6 s and 2,552 requests against 53.4 s and
4,428 at 50 ms on local object storage, and 49.3 s and 2,193 against 67.7 s and
3,199 behind an emulated remote store.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…loads

Design-only revision for review: a read beyond the margin waits when its bytes
are most of what the download writes before them; the margin defaults to
200 ms; measurements of the 50 ms margin and of the duplication bound alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XuPeng-SH

XuPeng-SH commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 4deacbe75086cf12d280d384bf6102bb4db4c982

Review linked issue or PR description changed before publication; a fresh contextual review is queued.

@XuPeng-SH

XuPeng-SH commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 4deacbe75086cf12d280d384bf6102bb4db4c982

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: 4deacbe75086cf12d280d384bf6102bb4db4c982

Assessment: request_changes

Cache-owned references and shared LRU reuse are justified, and the design gate is resolved. The new benchmarks do not resolve three implementation defects.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

  • P1 pkg/fileservice/s3_fs.go:1560: A read captures its bytes while all eight background-fill slots are occupied, then its context is cancelled during waitSet.
    Impact: The foreground read and storage copy ignore cancellation until the whole object finishes.
    Evidence: fillCtx strips cancellation at line 1494; waitSet receives setDone before calling cancelFill. The source-extracted probe fails while its cancellation-forwarding control passes (download-cancellation-probe.log). Forward cancellation until successful background handoff and test cancellation after capture with saturated slots.

  • P2 pkg/fileservice/s3fifo/cache.go:605: Delete or Replace removes the selected shard's head between oldest(small) and step acquiring its lock.
    Impact: Eviction can remove a newer entry ahead of an older entry in another shard, violating the global FIFO contract.
    Evidence: For insertion order A1, B2, A3, deleting A1 after selection makes step evict A3 while B2 remains. The actual-package witness fails; reselecting passes (s3fifo-oldest-probe.log). Carry and revalidate the selected head order under the policy lock, retrying when it changes.

  • P2 pkg/fileservice/disk_cache.go:234: During asynchronous startup loading, a live file is indexed/read before older ordinary cache files are enumerated.
    Impact: Old files receive fresh LRU priority and can displace the live working set, causing avoidable object-storage reads.
    Evidence: The new LRU owner is installed here, but loadCache still calls Set at line 315. indexLoadedDirs already uses SetOldest. The loader-equivalent probe evicts the hot entry; its SetOldest control retains it (lru-startup-probe.log). Use SetOldest for ordinary startup files too.

Validation:

  • Fresh race runs passed 28 S3-FIFO and 13 LRU tests without skips; isolation preflight passed.

  • Three candidate/control probes reproduced the findings; every correction control passed.

  • Static audit passed patch correspondence, whitespace, formatting of 40 Go files and seven-item discussion coverage. All six receipts, terminal exits and logs are reconciled in validation-evidence.json.

  • Frozen CI reports 13 successful, 14 skipped and two neutral checks. Updated benchmarks were assessed as author-reported evidence.

Limitations:

  • Native fileservice/objectio tests and live S3 cancellation were not rerun locally; cancellation uses source tracing and an extracted-method harness.

  • Raw author runtime/benchmark logs were unavailable; remote-store and multi-CN performance were not independently measured.

…oad files as oldest

- A read waiting for its download, with no background slot free, now cancels the
  download when its context is cancelled; cancellation stops forwarding only once
  the download is handed to a background slot.
- S3-FIFO eviction checks under the shard lock that the queue head it chose is
  unchanged, and chooses again otherwise, so a concurrent delete cannot make it
  evict a newer entry ahead of an older one in another shard.
- The disk cache's startup load indexes the files it finds as least recently used,
  as the design states, so a file read during the load is not evicted ahead of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@XuPeng-SH

XuPeng-SH commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 491cd699b7c95b0e7b88bab2c7100de788548aef

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: 491cd699b7c95b0e7b88bab2c7100de788548aef

Assessment: approve

Cache-owned references and shared LRU reuse remain justified. This head resolves the three prior cancellation, FIFO ordering and startup-recency findings.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed the six-file follow-up and affected ownership/liveness paths; verified 46 unchanged files or deletions against the frozen prior review.

  • Assessed all nine discussion items and reconciled the prior findings.

  • Reused frozen successful CI results and qualified prior race, model and benchmark reports.

  • Isolation preflight and source/provenance/format audit passed. Receipts and retained logs are reconciled in validation-ledger.json.

Limitations:

  • The fresh local race attempt executed zero tests: downloading Go 1.27.1 timed out before compilation.

  • Runtime and performance evidence is attributed to supplied reports; raw author artifacts and live remote-S3 validation were unavailable locally.

@mergify

mergify Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 906848d at 01:54 UTC

1 h 48 min in the queue, 1 h 14 min of it CI.

So far

  • ✅ Entered the queue Sat 7 Nov, 00:06 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 01:54 · 906848d · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

This branch was previously deployed

1 inactive deployment
ci — 47ad7bfa Deployed Nov 7, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement kind/refactor Code refactor size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants