Skip to content

fix(fileservice): restore memory cache efficiency with jemalloc - #26997

Merged
mergify[bot] merged 24 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26926-memory-cache-allocator
Aug 18, 2026
Merged

mergify[bot] merged 24 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26926-memory-cache-allocator

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 12, 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:

Fixes #26926

What this PR does / why we need it:

#26783 correctly changed Memory Cache admission to account for physical
backing 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.Set
admission boundary. FIFO capacity, cache_bytes, and allocator statistics
therefore describe the same storage.

Additional changes:

  • bundle and build jemalloc 5.3.1 with its license;
  • add exact backing-size contracts and a hybrid mmap allocator for
    non-jemalloc cache paths;
  • export logical payload, rounding overhead, jemalloc allocated/active/
    fragmentation/metadata/resident metrics, and arena count;
  • scope every cache metric by service UUID + FileService so CN, TN, Log,
    and multiple CNs cannot overwrite or aggregate one another;
  • retain ObjectIO validated-vector cache data when it is rehomed;
  • add ownership, admission, backing-size, arena-statistics, metric-refresh,
    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 build
  • go test ./pkg/common/malloc ./pkg/objectio ./pkg/util/metric/v2 -count=1
  • go test ./pkg/fileservice -count=1
  • Local isolated BVT: view/system_view.sql (11/11) and
    view/view_all.sql (166/166).
  • Local Sysbench-shaped read validation with a 2 GiB cache: 4 x 200k-row
    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 below
are from the PR head 1c3708fd81 unless noted.

  • oltp_point_select, 100 threads, 300 s:
    142,519.84 TPS, P95 1.64 ms, 0 errors/reconnects. The requested pre-PR
    baseline 45a917d7 measured 146,799.93 TPS and P95 1.61 ms on the same
    host/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.lua automation workload. It queries only
    sbtest1; 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.
  • Strict same-source A/B for 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 45a917d7 random-ranges result (31,821.75 TPS) is excluded from
allocator 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=1 otherwise passes the cache coverage;
its MinIO integration subtest requires a valid local localhost:9007 MinIO
credential and currently returns Access Denied.

CI follow-up

  • Arm64 SCA initially reported one prealloc finding in the new jemalloc arena-statistics test. Commit 3874bf8430 preallocates the six known deallocator slots; go test ./pkg/common/malloc -count=1 passes.

Review follow-up (56ea343)

  • Reserve exact physical backing capacity before every cache-owned allocation, including rehome copies. A reservation remains attached to the data until FIFO Set confirms insertion; if insertion is a duplicate/rejected entry, Release returns it. A request that cannot reserve capacity is explicitly marked non-cacheable, allocated through the ordinary I/O allocator, and skipped by MemCache.Update; it neither exceeds the cache arena quota nor waits for cache references that the active read may need to release.
  • Make DataCache.Set report 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.
  • Keep allocator-specific operations in pkg/common/malloc: FileService now depends only on MemoryCacheAllocator and generic resource statistics, not JemallocAllocator or 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.
  • Add regression coverage for the pre-Set rehome 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=1
  • go test -race ./pkg/fileservice -run 'TestMemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationWaitsForPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease)' -count=1
  • go test ./pkg/fileservice -count=1
  • CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/objectio -run 'Test.*(Cache|Vector)' -count=1
  • CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1

Compose CI regression fix (6e3f1c3)

Compose BVT exposed the missing non-cacheable case: log_info read 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.

  • A request larger than the cache, or one that cannot obtain capacity after synchronous eviction, now becomes an explicit transient read buffer. It is allocated through the ordinary I/O allocator and carries a destination-cache admission marker.
  • MemCache.Update skips 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.
  • Added oversized-entry, pending-reservation, and ObjectIO forwarding regressions.

Validation for this CI fix:

  • go test ./pkg/fileservice -count=1
  • go test -race ./pkg/fileservice -run 'TestMemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|OversizedDataBypassesAdmission|DuplicateSetKeepsReservationUntilDataRelease)' -count=1
  • CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/objectio -run 'Test.*(Cache|Vector)' -count=1
  • CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1

Review follow-up (080334e)

The latest review found three independent accounting/observability gaps, all fixed in this commit:

  • FIFO now counts asynchronous pending enqueues as physical cache usage. A reservation can be committed after DataCache.Set because every competing reservation observes queued plus pending backing bytes; draining the queue atomically transfers pending bytes into FIFO used bytes.
  • MetricsAllocator now adds each allocator's in-use delta to a shared absolute gauge instead of allowing the last allocator to overwrite it. This makes mo_mem_offheap_inuse_bytes{type="memory-cache"} aggregate all FileService cache arenas in a process.
  • jemalloc resident now reads stats.arenas.<i>.resident directly. 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=1
  • go test -race ./pkg/fileservice ./pkg/fileservice/fifocache ./pkg/common/malloc -run 'Test(MemCache(RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease)|PendingEnqueueCountsTowardsUsed|MetricsAllocatorAggregatesAbsoluteInuseGauge|JemallocAllocatorReportsClassBackingAndArenaStats)' -count=1
  • CGO_CFLAGS=... CGO_LDFLAGS=... go test ./pkg/... -run '^$' -count=1
  • git diff --check

Review follow-up (129e805)

Three actionable review findings are fixed:

  • Metrics refresh now records mutations that arrive while a snapshot is being published, then rearms after publishing. This closes the lost-wakeup window that could permanently under-report the shared off-heap in-use gauge. Deterministic allocation-during-publish and release-during-publish regressions cover both directions.
  • MemoryCacheAllocator now owns explicit native-page reclaim. The jemalloc implementation issues arena.<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.
  • Removed the dead capacityChanged channel and its close/reallocate handoff. It had no receiver; reservation release is now allocation-free, with a testing.AllocsPerRun regression.

Validation:

  • go test ./pkg/common/malloc -count=1
  • go test ./pkg/fileservice -count=1
  • go test -race ./pkg/common/malloc -run "TestMetricsAllocator(RefreshRearmsAfterAllocateDuringPublish|RefreshRearmsAfterReleaseDuringPublish|AggregatesAbsoluteInuseGauge)$" -count=1
  • go test -race ./pkg/fileservice -run "TestMemoryCache(ExplicitEvictionReclaimsAllocator|ReservationReleaseDoesNotAllocate|EvictToCapacityPercent)$" -count=1
  • git diff --check

Merge 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 before enqueue. That released the reservation while neither FIFO used bytes nor pending bytes covered the live cache allocation.

  • The ordinary path now calls enqueue first. Before it returns, FIFO has either added the item to used bytes or charged it to pendingBytes; only then does the successful completion callback commit the reservation.
  • The admission-target path already completes after its synchronous FIFO charge. Duplicate and rejected paths retain their original inserted=false release semantics. The public DataCache.Set(... ) error interface remains unchanged.
  • Added a deterministic end-to-end regression: it blocks the reservation completion at the handoff boundary, verifies FIFO usage is already charged, then proves a competing same-size request cannot enter the cache arena and allocator allocated bytes remain within cache capacity.

Validation for this follow-up:

  • go test ./pkg/fileservice/fifocache -count=1
  • go test -race ./pkg/fileservice -run "TestMemCache(CommitsReservationAfterFIFOUsageIsCharged|RehomeReservesCapacityBeforeCopy|CapacityReservationBypassesPendingAllocation|DuplicateSetKeepsReservationUntilDataRelease|ExplicitEvictionReclaimsAllocator|ReservationReleaseDoesNotAllocate)$" -count=1
  • go test ./pkg/fileservice -count=1 -skip TestMinioSDK
  • Full go test ./pkg/fileservice -count=1 reaches only the existing local TestMinioSDK failure: localhost:9007 returns Access Denied; the focused cache suite and all other fileservice tests pass.
  • git diff --check

Rebase onto main after #27170

Rebased this branch onto main after #27170 merged (852c98f3a413cf61fb874e9596a9970ec4820ef6). The only overlap was pkg/fileservice/local_fs_test.go: retained #27170's LocalFS regression coverage and updated this PR's blocking cache test double for the current DataCache.Set result contract.

Validation after rebase:

  • go test ./pkg/common/malloc -count=1
  • go test ./pkg/fileservice -count=1 -skip TestMinioSDK
  • go test -race ./pkg/fileservice -run 'TestMemCache(CommitsReservationAfterFIFOUsageIsCharged|RefusesInsertionWhenCapacityIsReserved|DoesNotPanicWhenReservationContextIsCanceled)' -count=1
  • git diff --check origin/main...HEAD

TestMinioSDK remains excluded only because its local localhost:9007 credential 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, and dallocx on every small cache-data allocation. The local BenchmarkLocalFSAllocateCacheDataHighCardinality regression was reproducible before this change.

  • Add a bounded, per-MemCache idle pool keyed by the exact jemalloc backing size class, limited to buffers at most 64 KiB. Only a buffer whose reservation is still pending (never retained by FIFO) can enter the pool. Its native allocation and its reservedBytes charge stay live while pooled, so the physical cache quota remains hard.
  • Reuse resets the live reference, applies normal zeroing unless NoClear was requested, and honors DoNotReuse. Large buffers still return directly to jemalloc.
  • On cache allocation pressure, release idle buffers before evicting FIFO entries. Flush, percentage pressure eviction, and forced global eviction also drain the pool and purge the dedicated arena. Thus the hot path avoids Cgo without hiding bytes from capacity accounting or preventing explicit RSS reclaim.
  • Add regressions for identity reuse and zero steady-state Go allocations, clearing, capacity-pressure drain, Flush, and forced eviction.

Validation:

  • go test ./pkg/fileservice -count=1 -skip TestMinioSDK
  • go test -race ./pkg/fileservice -run 'TestMemCache(ReusesSmallPendingAllocation|ReusedPendingAllocationIsCleared|CapacityPressureDrainsIdlePendingAllocation|FlushReleasesIdlePendingAllocation|ForcedEvictionReleasesIdlePendingAllocation|CommitsReservationAfterFIFOUsageIsCharged)$' -count=1
  • BenchmarkLocalFSAllocateCacheDataHighCardinality -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; current main was 213.4-217.7 ns/op, 48 B/op, 1 alloc/op.
  • The unskipped local full package run reaches only TestMinioSDK: the local localhost:9007 MinIO endpoint returns Access Denied; cache coverage passes.

SCA follow-up (dd4a9fc)

Arm64 SCA correctly reported an ineffassign in MemCache.reserveCacheData: after draining an idle pool, the code refreshed used = m.cache.Used() although the subsequent eviction target depends only on capacity, reservedBytes, and want. 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\n

Latest review follow-up (b563b9e)

Two latest review findings are addressed:

  • Forced eviction now forwards done only 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.
  • The initial idle-buffer pool used one global mutex, serializing releases for every jemalloc size class. The pool now has one lifecycle mutex per exact backing-size class. Explicit drains lock each affected class, preserving close/reclaim safety while independent small-buffer releases no longer contend globally.

Validation:

  • go test ./pkg/fileservice -count=1 -skip TestMinioSDK
  • go test -race ./pkg/fileservice -run '^TestMemCache(ForcedEvictionReclaimsFIFOAllocation|ForcedEvictionReleasesIdlePendingAllocation|ReusesSmallPendingAllocation|ReusedPendingAllocationIsCleared|CapacityPressureDrainsIdlePendingAllocation|FlushReleasesIdlePendingAllocation|CommitsReservationAfterFIFOUsageIsCharged)$' -count=1\n- git diff --check\n- Repeated BenchmarkLocalFSAllocateCacheDataHighCardinality -cpu=32 -benchtime=2s -count=5 -benchmem on Apple M5: current 98.6-106.2 ns/op, 0 B/op, 0 allocs/op; exact merge base 3af8be1e40: 173.5-208.3 ns/op, 48-49 B/op, 1 alloc/op.\n

Embedded 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 empty service label.

  • Add fileservice.ServiceMetricScope(serviceType, nodeUUID) as the single scope contract. Both standalone cmd/mo-service and pkg/embed now use it.
  • Apply that scope to every embedded FileService cache configuration before construction, covering memory and disk cache metrics.
  • Add a factory-level embedded regression that creates two real CN LOCAL/SHARED Memory Cache sets with different UUIDs and capacities. It proves their scoped SHARED-mem capacity 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\n

Ownership lifecycle follow-up (07fcc67)

The latest review identified two unhappy-path ownership gaps. Both are fixed without weakening the hard backing-capacity contract:

  • MemCache now 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 use defer or add a steady-state allocation.
  • MemoryCacheAllocator has a terminal Close contract. A dedicated jemalloc arena rejects new allocations once its cache generation closes, but remains alive until every outstanding data deallocator returns; the final release invokes arena.<id>.destroy. This prevents both use-after-free for retained data and unbounded arena generations across embedded Close/Start.
  • LocalFS and S3FS now share one transactional cache-construction helper. If disk-cache setup fails after Memory Cache creation, it closes the partially constructed memory cache and removes its global registration. The injected QueryClient remains caller-owned and is not closed by this rollback.

Validation:

  • go test ./pkg/common/malloc ./pkg/fileservice/fifocache ./pkg/fileservice -count=1 -skip TestMinioSDK
  • go test -race ./pkg/common/malloc ./pkg/fileservice/fifocache ./pkg/fileservice -count=1 -skip TestMinioSDK
  • go vet ./pkg/common/malloc ./pkg/fileservice
  • repository CGo environment: compile-only checks for pkg/objectio, cmd/mo-service, and pkg/embed
  • focused OOM reservation, S3 partial-construction, and arena close/restart tests under -race -count=10
  • BenchmarkLocalFSAllocateCacheDataHighCardinality -benchtime=2s -count=5 -benchmem on Apple M5: 69.06-87.94 ns/op, 0 B/op, 0 allocs/op.
  • git diff --check

Ubuntu/x86 UT race fix (2026-08-17)

The UT failure on 84960197 was a race introduced by this PR: LocalFS.Close and S3FS.Close cleared memCache/diskCache while TAE GC could still be executing Read. Cache close is already idempotent, so the pointer mutations were unnecessary and have been removed in 879dd386.

Validation:

  • go test -race ./pkg/backup -run '^TestBackupProtectionCheckpointProtection$' -count=10
  • go test -race ./pkg/fileservice -count=1 -skip TestMinioSDK

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement labels Aug 12, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Aug 12, 2026

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

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.

@CLAassistant

CLAassistant commented Aug 15, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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

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.

  1. [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.

  1. [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 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.

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 aptend 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.

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.

  1. [P1] Release a capacity reservation if the native allocation fails — pkg/fileservice/mem_cache.go:425-428.

    reserveCacheData increments reservedBytes and returns the only reservation token, but allocateCacheData does not attach that token to a Bytes owner until after m.allocator.allocateCacheBytes returns. That call deliberately panics on an allocator error (pkg/fileservice/bytes.go:182-186), and jemalloc explicitly returns NewOOM when mallocx returns nil. On that branch the token becomes unreachable: neither commit nor release can 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 Allocate returns OOM. After recovering the expected panic from a 4 KiB allocation, cache.reservedBytes remained 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.

  2. [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 NewMemCache calls arenas.create, while MemCache.Close only flushes/purges and drops the Go references. There is no arena.<i>.destroy path anywhere in the repository; the allocator comment explicitly makes every arena process-lifetime. This is not bounded by the service lifecycle: the embedded operator supports Close followed by Start, and each Start constructs 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.Close would 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 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.

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.

  1. [P1] Release the cache-capacity reservation when the native allocation fails — pkg/fileservice/mem_cache.go:425-428.

    reserveCacheData increments reservedBytes, but the returned reservation is not attached to an owner until m.allocator.allocateCacheBytes succeeds. 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: neither commit nor release can 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.reservedBytes was still 4096, not zero. Please keep a failure owner/defer until the reservation is successfully attached to the returned Bytes, and add an allocation-error regression proving the full capacity is reusable afterward.

  2. [P2] Give each dedicated jemalloc arena a bounded terminal owner, including partially constructed FileServices — pkg/fileservice/s3_fs.go:158-161,292-329.

    initCaches creates the MemCache first; that immediately creates a dedicated arena (pkg/fileservice/mem_cache.go:272-274) and publishes the cache in allMemoryCaches (:383-389). If the later disk-cache initialization fails, initCaches and then NewS3FS return nil, err without closing or aborting the partial S3FS. 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), while MemCache.Close only 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. NewS3FS correctly returned nil, err, but allMemoryCaches still 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 aptend 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.

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 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.

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.

@mergify

mergify Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-17 11:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-08-17 13:46 UTC · at 2b333b8c56bce5e02c2b2389afc533ad4780215c

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

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86

Reason

The merge conditions cannot be satisfied due to failing checks

Failing checks:

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, 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.

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

@mergify

mergify Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-18 01:06 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-18 02:51 UTC · at 420d13de7b0604b3cfb55122ec224508baeb2493 · squash

This pull request spent 1 hour 45 minutes 1 second in the queue, including 49 minutes 3 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

This branch was previously deployed

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

Labels

kind/bug Something isn't working kind/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: sysbench point_select TPS 暴跌 80%,二分定位到 commit 0676200da4 (account memory cache by backing capacity)

6 participants