Repository navigation
fix(fileservice): restore memory cache efficiency with jemalloc - #26997
mergify[bot] merged 24 commits into
Conversation
XuPeng-SH
left a comment
There was a problem hiding this comment.
Blocking finding on exact head ba9f6f4bd14862d0333d3763ba4b751ded9b32e3:
[P1] The configured FileService cache-data allocation hot path regresses by about 10.9x, and the PR's end-to-end performance regression remains unresolved.
I ran the repository's existing BenchmarkLocalFSAllocateCacheDataHighCardinality on this head and its current merge base 3af8be1e400d289fe2e538c485a9291f01f7e988, on the same host with -cpu=32 -benchtime=2s -count=5 -benchmem:
- merge base: 97.58–98.87 ns/op, 49 B/op, 1 alloc/op
- PR head: 1064–1075 ns/op, 104 B/op, 2 allocs/op
The five-run ranges do not overlap. This is not a synthetic allocator-only path: LocalFS.AllocateCacheData now routes every configured-cache allocation through MemCache.allocateCacheData (local_fs.go:245-248), which performs a je_nallocx size query, serializes reservation bookkeeping through capacityMu plus FIFO Used(), allocates a reservation object, and calls the dedicated-arena je_mallocx/je_dallocx path with MALLOCX_TCACHE_NONE (mem_cache.go:389-439, jemalloc_allocator.go:49-61). The same routing is used by S3FS.
This independently supports the PR description's strict same-source random_ranges_1000 result of -9.42% TPS / +9.42% P95. The latest head does not contain a newer A/B showing that regression disappeared; subsequent commits add more admission/accounting work to this path.
Please restore the allocation-path performance (including contention and the extra per-operation allocation), add a benchmark budget/regression for configured FileService allocation, and rerun repeated same-source system A/B on the latest head. A performance-restoration PR cannot land while both its own end-to-end workload and its existing hot-path benchmark show a material regression.
Correctness validation on this head otherwise passed: full pkg/common/malloc, pkg/fileservice/fifocache, and pkg/fileservice suites (excluding the credential-dependent MinIO test), focused reservation/metrics/reclaim tests under -race, ObjectIO cache/vector tests, jemalloc build, and git diff --check.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-review of exact head dd4a9fcdeb8b389ae9dc7d27c3db95620ba47df7. The new pending-buffer pool removes the prior extra allocation and most of the ~10.9x regression, but one correctness gap and a remaining measurable hot-path regression need changes.
- [P1] Reclaim the arena after forced FIFO eviction releases its entries.
MemCache.Evict releases/reclaims only the idle pool before calling m.cache.Evict (pkg/fileservice/mem_cache.go:829-834). The FIFO runs all postEvict callbacks—and therefore the cached values' final Release—after unlocking, immediately before signaling done (pkg/fileservice/fifocache/fifo.go:567-583). There is no reclaim after those releases. EvictMemoryCaches waits for that signal and returns (pkg/fileservice/cache.go:200-218), so callers are told forced eviction completed while the newly dirtied jemalloc arena pages have not been purged.
A deterministic exact-head test cached an arena-owned 64 KiB value, released the caller reference, wrapped the arena with the PR's reclaimTrackingAllocator, then called cache.Evict(ctx, done) and waited for done. FIFO usage was evicted, but tracking.reclaims == 0. Existing TestMemoryCacheExplicitEvictionReclaimsAllocator covers only EvictToCapacityPercent and Flush, so it misses this public forced-eviction path.
Please move/chain reclaim to after the synchronous FIFO callbacks for forced eviction (without purging on ordinary release), and add a regression using an actual FIFO-owned allocation rather than only an idle pending buffer.
- [P2] The configured allocation benchmark is still consistently slower than the exact merge base.
On the same Apple M4 host with -cpu=32 -benchtime=2s -count=5 -benchmem, BenchmarkLocalFSAllocateCacheDataHighCardinality produced:
- merge base
3af8be1e400d: 166.7–177.9 ns/op, 48–49 B/op, 1 alloc/op - current head: 187.6–196.5 ns/op, 0 B/op, 0 allocs/op
The allocation reduction is good, but the latency ranges do not overlap (roughly 11% at the means), and the PR still has no current-head system A/B replacing the previously reported -9.42% TPS result. Please account for the remaining synchronization/pool overhead and rerun the repeated same-source workload on this head.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-review completed on exact head b563b9eb3df4c98debd35c4a6d8c978739dd872f. The previous forced-eviction reclaim and allocation-path contention findings are fixed: FIFO-owned buffers are released before arena reclaim, and the per-size-class pool removes the shared release lock. On the same Apple M4 host, the existing high-cardinality allocation benchmark is now 78.86–86.92 ns/op with 0 B/op and 0 allocs/op, versus 166.3–169.0 ns/op with 49 B/op and 1 alloc/op at merge base 3af8be1e400d289fe2e538c485a9291f01f7e988.
One blocking observability gap remains:
[P2] Propagate the service metric scope through the embedded launcher — pkg/embed/config.go:342-350.
This PR adds CacheConfig.MetricScope specifically so caches from multiple CN/TN/LOG services in one process do not share one Prometheus series. The regular launcher sets it from serviceType + nodeUUID in cmd/mo-service/config.go:323-325, but the parallel embedded launcher passes each fileservice.Config to NewFileService unchanged. Its caller already supplies both identities at pkg/embed/operator.go:185-189, so the scope is available and is simply dropped.
As a result, every embedded node still creates its same-named SHARED-mem and LOCAL-mem gauges with an empty service label. Multi-node embedded/cluster deployments therefore aggregate or overwrite capacities and allocator statistics across nodes, exactly the collision the new label is intended to prevent.
I reproduced this on this exact head with the real embedded FileService factory: create a memory-cached LOCAL/SHARED service via ServiceConfig.createFileService(ctx, CN, "pr26997-node-a"), configure SHARED capacity to 1,048,576 bytes, then read GetFsCacheBytesGaugeWithScope("CN/pr26997-node-a", "SHARED", "mem"). The scoped capacity is 0 because the cache was registered under the empty scope. The temporary harness was removed.
Please apply the same scope propagation to pkg/embed—preferably through one shared helper used by both launchers so the paths cannot drift again—and add a factory-level regression with distinct node UUIDs proving that their cache series remain separate.
Validation otherwise passed: focused lifecycle tests under -race -count=20; full pkg/common/malloc, pkg/fileservice/fifocache, and pkg/fileservice under race; full non-race malloc/fileservice/fifo/objectio/metric suites; vet for all changed owning packages plus both launchers; and compile-only tests for pkg/embed and cmd/mo-service.
aptend
left a comment
There was a problem hiding this comment.
Re-review completed on exact head f048b1f09b74e7eafbbcb6301d9409a577b8bf32 with the full review/comment history. The embedded metric scope now propagates correctly and the prior reservation handoff, forced reclaim, allocator-metric, and hot-path findings remain fixed. Two unhappy-path ownership gaps still need changes.
-
[P1] Release a capacity reservation if the native allocation fails —
pkg/fileservice/mem_cache.go:425-428.reserveCacheDataincrementsreservedBytesand returns the only reservation token, butallocateCacheDatadoes not attach that token to aBytesowner until afterm.allocator.allocateCacheBytesreturns. That call deliberately panics on an allocator error (pkg/fileservice/bytes.go:182-186), and jemalloc explicitly returnsNewOOMwhenmallocxreturns nil. On that branch the token becomes unreachable: neithercommitnorreleasecan run, so the cache permanently loses the reserved capacity even if the query-level panic is recovered.I reproduced this deterministically on this exact head by replacing the cache's backing allocator with an exact-size allocator whose
Allocatereturns OOM. After recovering the expected panic from a 4 KiB allocation,cache.reservedBytesremained 4096 instead of returning to zero. Please keep a deferred failure owner for the reservation until it has successfully been attached to the returned data, and add an allocation-error regression that verifies the full capacity becomes reservable again. -
[P2] Retire or reuse dedicated arenas across in-process cache generations —
pkg/common/malloc/jemalloc_allocator.go:142-172,pkg/fileservice/mem_cache.go:869-873.Every
NewMemCachecallsarenas.create, whileMemCache.Closeonly flushes/purges and drops the Go references. There is noarena.<i>.destroypath anywhere in the repository; the allocator comment explicitly makes every arena process-lifetime. This is not bounded by the service lifecycle: the embedded operator supportsClosefollowed byStart, and eachStartconstructs a fresh FileService/cache set. Repeated in-process restarts therefore retain another set of jemalloc arena metadata each generation and eventually exhaust the finite explicit-arena namespace, at which point cache/service construction panics.Synchronous destruction at
MemCache.Closewould indeed be unsafe while callers retain cache data, but the arena still needs a terminal owner: for example, defer destruction until the closed allocator's last outstanding deallocator releases, or reuse a stable arena for the next generation. Please add a close/restart regression with all data released that proves active arena resources stay bounded.
Validation on the exact head: make thirdparties, make cgo, git diff --check, and full tests for pkg/common/malloc, pkg/fileservice/fifocache, pkg/fileservice, pkg/objectio, and pkg/embed passed. Focused reservation/FIFO/reclaim/metrics/embedded-scope tests also passed under -race -count=5. The temporary allocation-failure reproducer was removed.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Re-review completed on exact head f048b1f09b74e7eafbbcb6301d9409a577b8bf32. The latest embedded metric-scope fix is correct: the real embedded FileService factory keeps two node scopes separate, including under -race -count=20. Two blocking unhappy-path ownership gaps remain.
-
[P1] Release the cache-capacity reservation when the native allocation fails —
pkg/fileservice/mem_cache.go:425-428.reserveCacheDataincrementsreservedBytes, but the returned reservation is not attached to an owner untilm.allocator.allocateCacheBytessucceeds. That function panics when the allocator returns an error (pkg/fileservice/bytes.go:182-186), including jemalloc OOM. Therefore an allocation failure makes the reservation unreachable: neithercommitnorreleasecan run, and a recovered query-level panic permanently removes that capacity from the cache.I reproduced this deterministically on this exact head by replacing the cache backing allocator with an exact-size allocator that returns
NewOOMNoCtx. After recovering the expected panic from a 4 KiB allocation,cache.reservedByteswas still4096, not zero. Please keep a failure owner/defer until the reservation is successfully attached to the returnedBytes, and add an allocation-error regression proving the full capacity is reusable afterward. -
[P2] Give each dedicated jemalloc arena a bounded terminal owner, including partially constructed FileServices —
pkg/fileservice/s3_fs.go:158-161,292-329.initCachescreates the MemCache first; that immediately creates a dedicated arena (pkg/fileservice/mem_cache.go:272-274) and publishes the cache inallMemoryCaches(:383-389). If the later disk-cache initialization fails,initCachesand thenNewS3FSreturnnil, errwithout closing or aborting the partialS3FS. The caller receives no object it can close. Moreover, the allocator explicitly makes the arena process-lifetime (pkg/common/malloc/jemalloc_allocator.go:139-143), whileMemCache.Closeonly flushes/purges and unregisters the cache (pkg/fileservice/mem_cache.go:869-873). Failed startup retries therefore leak both the global cache registration and one native arena generation each time; successful in-process Close/Start generations also remain unbounded.I reproduced the production constructor path on this exact head with a valid disk-backed S3 object storage and a disk-cache path that is an existing regular file.
NewS3FScorrectly returnednil, err, butallMemoryCachesstill contained the newly created*MemCache. Since no data had escaped in this failure case, retaining its process-lifetime arena is unnecessary. Please make cache initialization transactional on every later failure and provide a bounded arena-generation strategy (for example, abort/destroy before publication when no data escaped, and defer terminal destruction until the last outstanding deallocator for published caches, or safely reuse arenas). Add both constructor-failure and Close/Start generation regressions.
The normal reservation/FIFO handoff, forced-eviction reclaim order, allocator metrics, and scoped launcher paths otherwise held in the audit. Validation passed for the focused lifecycle/metrics tests with adaptive repeated race runs, full race suites for pkg/fileservice, pkg/fileservice/fifocache, and pkg/common/malloc, normal owning-package suites, build/vet of all changed owning packages and both launchers, the embedded factory race run above, native jemalloc build, and git diff --check. Both temporary failure-injection tests were removed.
aptend
left a comment
There was a problem hiding this comment.
Re-review completed on exact head 84960197be1b7f7a870f13b4c41fd9fc58b49f6f with the full review and comment history.
The two outstanding unhappy-path findings are fixed. Allocation errors now return through a non-panicking helper so the pending capacity reservation is released before the error is re-raised. Dedicated jemalloc arenas now have an allocator-owner plus per-allocation reference model: Close prevents new allocations, retained data stays valid, and the arena is destroyed only after the last deallocator runs. Cache construction is transactional across the memory-to-disk boundary, so a later disk-cache initialization failure closes/unregisters the partial MemCache and retires its arena. Close is idempotent, drains FIFO/idle owners before retiring the allocator, and the prior reservation handoff, forced-reclaim ordering, metric scoping, and hot-path fixes remain intact.
Validation on this exact head: rebuilt the PR's jemalloc thirdparty artifacts; full pkg/common/malloc, pkg/fileservice/fifocache, and pkg/fileservice suites passed (excluding only the credential-dependent MinIO integration test); the new allocation-failure, constructor-rollback, Close/outstanding-allocation, and repeated arena-generation tests passed under -race -count=5; git diff --check is clean. CI native/shared builds are green; the longer UT/BVT jobs were still pending at review time.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Deep re-review completed on exact head 879dd386a3fd62316571cca4e7ad27c12ba92568; no blocking issue found.
I re-audited the native allocation lifecycle and cache accounting with the Q1/Q2/Q3 unhappy-path model. Reservation ownership closes allocation failure, duplicate/rejected admission, pending enqueue, FIFO transfer, idle reuse/drain, forced eviction, and Close with outstanding references. The allocator owner plus per-allocation refs prevents arena UAF and bounds cache generations; synchronous eviction has no new circular wait; idle storage is bounded by finite jemalloc classes, per-class limits, and the hard cache quota.
The only delta after the previously reviewed 84960197be removes racy nil writes to immutable LocalFS/S3FS cache pointers. Internal Close remains idempotent and the allocator closed state protects native lifetime. I independently exercised concurrent LocalFS Close/FlushCache under -race -count=5 with no race or panic.
Validation also passed full race suites for pkg/common/malloc, pkg/fileservice/fifocache, and pkg/fileservice (excluding only the credential-dependent MinIO test), focused ObjectIO cache/vector tests, the embedded metric-scope factory test, and git diff --check. CI is green and the head is mergeable. The temporary concurrency test was not committed.
Merge Queue Status
This pull request spent 1 hour 47 minutes 3 seconds in the queue, with no time running CI. Waiting for
All conditions
ReasonThe merge conditions cannot be satisfied due to failing checks Failing checks: HintYou may have to fix your CI before adding the pull request to the queue again. Requeued — the merge queue status continues in this comment ↓. |
Merge Queue Status
This pull request spent 1 hour 45 minutes 1 second in the queue, including 49 minutes 3 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
Fixes #26926
What this PR does / why we need it:
#26783correctly changed Memory Cache admission to account for physicalbacking capacity, but the prior page-rounded allocator made small and medium
cache entries consume substantially more than their payload. A 20 GiB cache
could therefore hold materially less useful data, causing the read-path cache
miss regression reported in #26926.
This PR keeps physical-backing accounting as the admission source of truth,
but changes the Memory Cache allocator to a dedicated jemalloc arena with
jemalloc size classes. Data arriving from vector, disk, and legacy paths is
rehomed into the receiving cache's arena at the single
DataCache.Setadmission boundary. FIFO capacity,
cache_bytes, and allocator statisticstherefore describe the same storage.
Additional changes:
non-jemalloc cache paths;
fragmentation/metadata/resident metrics, and arena count;
service UUID + FileServiceso CN, TN, Log,and multiple CNs cannot overwrite or aggregate one another;
and same-FileService multi-CN scope regression tests.
The cache quota remains a hard physical-backing limit. Caller-visible payload,
size-class rounding (
backing-overhead), and allocator-side active slack(
allocator-fragmentation) are exposed separately.Validation
make buildgo test ./pkg/common/malloc ./pkg/objectio ./pkg/util/metric/v2 -count=1go test ./pkg/fileservice -count=1view/system_view.sql(11/11) andview/view_all.sql(166/166).tables, 16 threads, 10 s warmup and 30 s validation; 1,910,369 point reads,
zero errors/reconnects, unchanged table checksums and 1,024 fixed-key
probes. Final metrics: logical 471.6 MB, inuse/allocated 482.8 MB, backing
overhead 11.25 MB.
129 isolated 20 GiB cache validation
All 129 runs use the 10 x 10M-row Sysbench data set, a 20 GiB CN cache, an
isolated network namespace, and a task-owned
mo-service. Results beloware from the PR head
1c3708fd81unless noted.oltp_point_select, 100 threads, 300 s:142,519.84 TPS, P95 1.64 ms, 0 errors/reconnects. The requested pre-PR
baseline
45a917d7measured 146,799.93 TPS and P95 1.61 ms on the samehost/configuration: -2.91% TPS and +0.03 ms P95. At the end of the run the
CN-only cache had logical 14.20 GiB, inuse/allocated 14.29 GiB, 0.66%
rounding overhead, and 0.66% jemalloc active slack.
sysbench1000w.random_ranges_1000, 1000 threads, 300 s:6,936.47 TPS, P95 502.20 ms, 0 errors/reconnects. This is the exact
select_random_ranges.luaautomation workload. It queries onlysbtest1; final CN cache hot set was logical 435.64 MiB,inuse/allocated 454.72 MiB, 4.38% rounding overhead, and 4.32% jemalloc
active slack. The 20 GiB cap and CN-only single arena were both observed.
random_ranges_1000, 1000 threads, 60 s:the control is the PR merge-main parent and differs only by this PR's
commits. Control measured 7,950.07 TPS / P95 458.96 ms; PR measured
7,201.13 TPS / P95 502.20 ms, both with zero errors/reconnects. This is
-9.42% TPS and +9.42% P95 in one paired sample, so the performance result
remains unresolved. Cache payload was effectively equal (control
437.6 MiB, PR 435.4 MiB), while backing usage fell from 712.2 MiB to
454.4 MiB and rounding overhead from 274.6 MiB to 19.1 MiB. The control
metrics are the legacy unscoped SHARED-mem series; non-CN contribution was
approximately 1.5 MiB and does not change the conclusion.
The older
45a917d7random-ranges result (31,821.75 TPS) is excluded fromallocator attribution because it predates substantial unrelated main-branch
changes. It is not a valid A/B baseline for this PR.
go test ./pkg/fileservice -count=1otherwise passes the cache coverage;its MinIO integration subtest requires a valid local
localhost:9007MinIOcredential and currently returns
Access Denied.CI follow-up
preallocfinding in the new jemalloc arena-statistics test. Commit3874bf8430preallocates the six known deallocator slots;go test ./pkg/common/malloc -count=1passes.Review follow-up (56ea343)
Setconfirms insertion; if insertion is a duplicate/rejected entry,Releasereturns it. A request that cannot reserve capacity is explicitly marked non-cacheable, allocated through the ordinary I/O allocator, and skipped byMemCache.Update; it neither exceeds the cache arena quota nor waits for cache references that the active read may need to release.DataCache.Setreport whether it inserted. This is necessary to distinguish FIFO ownership from a duplicate/failed admission and prevents an early reservation release. ObjectIO validated-vector wrappers forward the reservation contract.pkg/common/malloc: FileService now depends only onMemoryCacheAllocatorand generic resource statistics, notJemallocAllocatoror arena APIs. The backend remains jemalloc because isolated arenas, exact size classes, and allocator statistics are required cache contracts; initialization still fails explicitly rather than silently switching allocators.Setrehome boundary, competing pending reservations, duplicate insertion, and proper vector release in pressure tests. Broader capacity-guard cleanup is tracked separately in [Refactoring]: consolidate Memory Cache allocation capacity ownership #27138.Additional validation for this follow-up:
go test ./pkg/common/malloc ./pkg/fileservice/fifocache -count=1go test -race ./pkg/fileservice -run 'TestMemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationWaitsForPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease)' -count=1go test ./pkg/fileservice -count=1CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/objectio -run 'Test.*(Cache|Vector)' -count=1CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1Compose CI regression fix (6e3f1c3)
Compose BVT exposed the missing non-cacheable case:
log_inforead a buffer for which the 512 MB Memory Cache could not grant a reservation. The earlier reservation loop waited until query cancellation and surfaced an internal panic.MemCache.Updateskips data marked for that cache; ObjectIO validated-vector wrappers forward the marker. This preserves the cache-owned physical backing limit without blocking the query or admitting an unaccounted buffer.Validation for this CI fix:
go test ./pkg/fileservice -count=1go test -race ./pkg/fileservice -run 'TestMemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|OversizedDataBypassesAdmission|DuplicateSetKeepsReservationUntilDataRelease)' -count=1CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/objectio -run 'Test.*(Cache|Vector)' -count=1CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1Review follow-up (080334e)
The latest review found three independent accounting/observability gaps, all fixed in this commit:
DataCache.Setbecause every competing reservation observes queued plus pending backing bytes; draining the queue atomically transfers pending bytes into FIFO used bytes.MetricsAllocatornow adds each allocator's in-use delta to a shared absolute gauge instead of allowing the last allocator to overwrite it. This makesmo_mem_offheap_inuse_bytes{type="memory-cache"}aggregate all FileService cache arenas in a process.stats.arenas.<i>.residentdirectly. It no longer derives resident from page-state counters or includes muzzy pages.Validation:
go test ./pkg/fileservice ./pkg/fileservice/fifocache ./pkg/common/malloc -count=1go test -race ./pkg/fileservice ./pkg/fileservice/fifocache ./pkg/common/malloc -run 'Test(MemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease)|PendingEnqueueCountsTowardsUsed|MetricsAllocatorAggregatesAbsoluteInuseGauge|JemallocAllocatorReportsClassBackingAndArenaStats)' -count=1CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1git diff --checkReview follow-up (129e805)
Three actionable review findings are fixed:
MemoryCacheAllocatornow owns explicit native-page reclaim. The jemalloc implementation issuesarena.<i>.purge; MemCache invokes it only after explicit percentage eviction and Flush/Close, never on normal release. A dirty-page purge regression verifies allocator resident/dirty state after release.capacityChangedchannel and its close/reallocate handoff. It had no receiver; reservation release is now allocation-free, with atesting.AllocsPerRunregression.Validation:
go test ./pkg/common/malloc -count=1go test ./pkg/fileservice -count=1go test -race ./pkg/common/malloc -run "TestMetricsAllocator(RefreshRearmsAfterAllocateDuringPublish|RefreshRearmsAfterReleaseDuringPublish|AggregatesAbsoluteInuseGauge)$" -count=1go test -race ./pkg/fileservice -run "TestMemoryCache(ExplicitEvictionReclaimsAllocator|ReservationReleaseDoesNotAllocate|EvictToCapacityPercent)$" -count=1git diff --checkMerge and FIFO handoff follow-up (1086108)
The previous merge note was incorrect for the ordinary FIFO path: it invoked the successful
prepareSet(inserted)completion callback beforeenqueue. That released the reservation while neither FIFO used bytes nor pending bytes covered the live cache allocation.enqueuefirst. Before it returns, FIFO has either added the item to used bytes or charged it topendingBytes; only then does the successful completion callback commit the reservation.inserted=falserelease semantics. The publicDataCache.Set(... ) errorinterface remains unchanged.Validation for this follow-up:
go test ./pkg/fileservice/fifocache -count=1go test -race ./pkg/fileservice -run "TestMemCache(CommitsReservationAfterFIFOUsageIsCharged|RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease|ExplicitEvictionReclaimsAllocator|ReservationReleaseDoesNotAllocate)$" -count=1go test ./pkg/fileservice -count=1 -skip TestMinioSDKgo test ./pkg/fileservice -count=1reaches only the existing localTestMinioSDKfailure:localhost:9007returnsAccess Denied; the focused cache suite and all other fileservice tests pass.git diff --checkRebase onto main after #27170
Rebased this branch onto
mainafter #27170 merged (852c98f3a413cf61fb874e9596a9970ec4820ef6). The only overlap waspkg/fileservice/local_fs_test.go: retained #27170's LocalFS regression coverage and updated this PR's blocking cache test double for the currentDataCache.Setresult contract.Validation after rebase:
go test ./pkg/common/malloc -count=1go test ./pkg/fileservice -count=1 -skip TestMinioSDKgo test -race ./pkg/fileservice -run 'TestMemCache(CommitsReservationAfterFIFOUsageIsCharged|RefusesInsertionWhenCapacityIsReserved|DoesNotPanicWhenReservationContextIsCanceled)' -count=1git diff --check origin/main...HEADTestMinioSDKremains excluded only because its locallocalhost:9007credential is unavailable; all other fileservice tests pass. The preceding Ubuntu/x86 UT timeout was caused by the now-merged #27170 test scheduler fix, not a cache allocator failure.Performance review follow-up (68217c6)
The performance review was valid: the first jemalloc implementation crossed Cgo for
nallocx,mallocx, anddallocxon every small cache-data allocation. The localBenchmarkLocalFSAllocateCacheDataHighCardinalityregression was reproducible before this change.reservedBytescharge stay live while pooled, so the physical cache quota remains hard.NoClearwas requested, and honorsDoNotReuse. Large buffers still return directly to jemalloc.Validation:
go test ./pkg/fileservice -count=1 -skip TestMinioSDKgo test -race ./pkg/fileservice -run 'TestMemCache(ReusesSmallPendingAllocation|ReusedPendingAllocationIsCleared|CapacityPressureDrainsIdlePendingAllocation|FlushReleasesIdlePendingAllocation|ForcedEvictionReleasesIdlePendingAllocation|CommitsReservationAfterFIFOUsageIsCharged)$' -count=1BenchmarkLocalFSAllocateCacheDataHighCardinality -cpu=8 -benchtime=2s -count=5 -benchmem: 183.6-188.3 ns/op, 0 B/op, 0 allocs/op. On the same Apple M5, the pre-pool jemalloc path was 966.1-1026 ns/op, 104 B/op, 2 allocs/op; currentmainwas 213.4-217.7 ns/op, 48 B/op, 1 alloc/op.TestMinioSDK: the locallocalhost:9007MinIO endpoint returnsAccess Denied; cache coverage passes.SCA follow-up (dd4a9fc)
Arm64 SCA correctly reported an
ineffassigninMemCache.reserveCacheData: after draining an idle pool, the code refreshedused = m.cache.Used()although the subsequent eviction target depends only oncapacity,reservedBytes, andwant. Removed that dead read.Validation:
go test ./pkg/fileservice -run '^TestMemCache(ReusesSmallPendingAllocation|ReusedPendingAllocationIsCleared|CapacityPressureDrainsIdlePendingAllocation|FlushReleasesIdlePendingAllocation|ForcedEvictionReleasesIdlePendingAllocation|CommitsReservationAfterFIFOUsageIsCharged)$' -count=1\n-go test ./pkg/fileservice -count=1 -skip TestMinioSDK\n-git diff --check\nLatest review follow-up (b563b9e)
Two latest review findings are addressed:
doneonly after FIFO post-evict callbacks have released cache-owned buffers and the dedicated jemalloc arena has been reclaimed. This makes the public forced-eviction completion signal mean that native RSS reclaim has actually been requested. A regression caches an arena-owned FIFO value, lowers the global capacity target, waits for forced eviction, and proves reclaim ran after FIFO usage reached zero.Validation:
go test ./pkg/fileservice -count=1 -skip TestMinioSDKgo test -race ./pkg/fileservice -run '^TestMemCache(ForcedEvictionReclaimsFIFOAllocation|ForcedEvictionReleasesIdlePendingAllocation|ReusesSmallPendingAllocation|ReusedPendingAllocationIsCleared|CapacityPressureDrainsIdlePendingAllocation|FlushReleasesIdlePendingAllocation|CommitsReservationAfterFIFOUsageIsCharged)$' -count=1\n-git diff --check\n- RepeatedBenchmarkLocalFSAllocateCacheDataHighCardinality -cpu=32 -benchtime=2s -count=5 -benchmemon Apple M5: current98.6-106.2 ns/op,0 B/op,0 allocs/op; exact merge base3af8be1e40:173.5-208.3 ns/op,48-49 B/op,1 alloc/op.\nEmbedded metric-scope follow-up (f048b1f)
The embedded launcher was dropping
CacheConfig.MetricScope, causing same-named cache metrics from multiple embedded CN/TN/LOG services in one process to share the emptyservicelabel.fileservice.ServiceMetricScope(serviceType, nodeUUID)as the single scope contract. Both standalonecmd/mo-serviceandpkg/embednow use it.LOCAL/SHAREDMemory Cache sets with different UUIDs and capacities. It proves their scopedSHARED-memcapacity gauges remain 1 MiB and 2 MiB respectively.Validation (with the repository CGo/third-party build environment):
go test -mod=readonly -vet=off -tags matrixone_test ./pkg/embed -run '^TestFileServiceFactoryScopesMemoryCacheMetrics$' -count=1\n-go test -mod=readonly -vet=off -tags matrixone_test ./cmd/mo-service -run '^TestFileServiceFactory$' -count=1\n-git diff --check\nOwnership lifecycle follow-up (07fcc67)
The latest review identified two unhappy-path ownership gaps. Both are fixed without weakening the hard backing-capacity contract:
MemCachenow obtains cache bytes through an internal error-returning path. If native allocation fails, it explicitly releases the reservation before preserving the existing panic semantics. The successful allocation path does not usedeferor add a steady-state allocation.MemoryCacheAllocatorhas a terminalClosecontract. A dedicated jemalloc arena rejects new allocations once its cache generation closes, but remains alive until every outstanding data deallocator returns; the final release invokesarena.<id>.destroy. This prevents both use-after-free for retained data and unbounded arena generations across embedded Close/Start.Validation:
go test ./pkg/common/malloc ./pkg/fileservice/fifocache ./pkg/fileservice -count=1 -skip TestMinioSDKgo test -race ./pkg/common/malloc ./pkg/fileservice/fifocache ./pkg/fileservice -count=1 -skip TestMinioSDKgo vet ./pkg/common/malloc ./pkg/fileservicepkg/objectio,cmd/mo-service, andpkg/embed-race -count=10BenchmarkLocalFSAllocateCacheDataHighCardinality -benchtime=2s -count=5 -benchmemon Apple M5: 69.06-87.94 ns/op, 0 B/op, 0 allocs/op.git diff --checkUbuntu/x86 UT race fix (2026-08-17)
The UT failure on
84960197was a race introduced by this PR:LocalFS.CloseandS3FS.CloseclearedmemCache/diskCachewhile TAE GC could still be executingRead. Cache close is already idempotent, so the pointer mutations were unnecessary and have been removed in879dd386.Validation:
go test -race ./pkg/backup -run '^TestBackupProtectionCheckpointProtection$' -count=10go test -race ./pkg/fileservice -count=1 -skip TestMinioSDK