Skip to content

fix: account memory cache by backing capacity - #26783

Merged
mergify[bot] merged 11 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26465-memory-cache-physical-accounting
Aug 9, 2026
Merged

mergify[bot] merged 11 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26465-memory-cache-physical-accounting

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 7, 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 #26465

What this PR does / why we need it:

The memory cache previously admitted entries and reported cache in-use bytes
using the logical payload length. The default class allocator rounds a request
up to a size class, so the cache could retain materially more backing memory
than its capacity and metrics indicated.

This PR makes physical backing capacity the single source of truth for
memory-cache admission, FIFO usage, and malloc in-use accounting. It adds an
explicit allocator backing-size contract and forwards it through all allocator
decorators and FileService cache-data allocators.

It also keeps logical payload accounting separate:

  • mo_fs_cache_bytes{type="inuse"}: physical cache backing capacity
  • mo_fs_cache_bytes{type="logical"}: logical cache payload
  • mo_fs_cache_bytes{type="backing-overhead"}: physical backing minus logical payload

The FileService cache dashboard now exposes all three memory-cache series.
backing-overhead covers size-class rounding and caller-provided spare slice
capacity. It intentionally does not claim to measure allocator free pools,
page-level fragmentation, or process RSS.

Logical size is captured in the FIFO value and forwarded to both post-set and
post-evict callbacks. This avoids a global MemCache accounting lock and a
duplicate per-entry map on the cache-write path. The FIFO stores physical
capacity for admission, while cache metrics remain balanced from the same
entry lifetime data.

ShardedAllocator validates all shard backing-size contracts once, then
predicts using its selected shard without per-request memoization. The contract
is restricted to built-in immutable mappings: exact capacity (C allocator) or
the shared class-allocation mapping. All decorators propagate that contract and
the random decorator rejects divergent branches. A sharded allocator without a
stable known contract fails explicitly instead of risking under-reservation.
This keeps predictions O(1) for arbitrary request sizes without request-keyed
metadata, heap churn, or cached transient errors.

The sharded contract cache is now bound to a private shard configuration rather
than the public slice representation. Callers cannot slice, reorder, replace,
or mix shards after construction, so the one-time all-shard validation remains
valid for the allocator lifetime.

ObjectIO cache-data wrappers forward the capacity contract. The FIFO stores
the logical size captured at admission time, and MemCache callback sequencing
continues to suppress stale post-set callbacks after invalidation or reinsertion.

The first CI run exposed one stale test assertion: it expected a 10-byte
logical request to reserve 10 bytes. The test now derives the expected
reservation from DefaultCacheDataAllocator().BackingSize(10), matching the
production contract. A subsequent coverage run required tests for every
allocator decorator plus all LocalFS/S3FS and guarded-allocation entry points;
those tests verify that the full physical backing is reserved before allocation.

Validation:

  • go test -race -count=20 ./pkg/common/malloc -run 'Test(BackingSize|ShardedBackingSize)'
  • go test -race -count=1 ./pkg/fileservice
  • go test -count=1 ./pkg/fileservice/fifocache
  • go test -race -count=1 ./pkg/fileservice -run 'Test(MemCacheSeparatesPhysicalAndLogicalBytesMetrics|MemCacheSkipsStalePostEvictAfterReinsert|MemCacheSerializesSameKeyCallbacks|MemCacheRetainsBeforeSetVisible)$' -v
  • go test -count=1 ./pkg/fileservice/fifocache -run '^TestDataCacheCallbacksReceiveCapturedLogicalSize$' -v
  • go test -count=1 ./pkg/fileservice -run '^$' -bench '^Benchmark(LocalFS|S3FS)AllocateCacheData(HighCardinality)?$' -benchtime=2s -benchmem
  • go test -count=1 ./pkg/fileservice -run '^$' -bench '^BenchmarkMemCacheSet(Sequential|Parallel)$' -benchtime=100ms -benchmem
  • go test -count=1 ./pkg/fileservice -coverprofile=... (full package; exercised all new LocalFS/S3FS paths)
  • go test -count=1 ./pkg/util/metric/v2 ./pkg/util/metric/v2/dashboard -run '^$'
  • Native-backed ObjectIO/object-tool compilation attempted but is blocked locally by missing usearch.h, xxhash.h, and roaring.h.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@gouhongshen
gouhongshen requested a review from XuPeng-SH August 7, 2026 17:01
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Aug 7, 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.

Deep re-review completed at head 21789ee895ce089ce761592595e64c09cae88769 against merge-base 8824b6c7f4549dfdc6fce37fec4c0002ce703b3e.

The previous two findings are substantially addressed: request-keyed memoization and miss allocations are gone, the stable mapping is explicit, and fixed/high-cardinality public-path performance is back to the base level. I am requesting changes for one remaining configuration-correctness blocker.

P1: bind the one-time validation result to the exact shard configuration

ShardedAllocator is a public slice type, but every element created by NewShardedAllocator shares one shardedBackingSizeContractState. BackingSizeContract runs state.once.Do with whichever receiver slice reaches it first (pkg/common/malloc/backing_size.go:142-150). The cached result therefore describes that receiver view, not necessarily every other view sharing the state.

This public-API counterexample bypasses the new heterogeneous-shard rejection:

  1. construct two shards where shard 0 is CAllocator (exact) and shard 1 is ClassAllocator (class);
  2. call BackingSize(shards[1:], 3) first: it validates only shard 1, returns 4, and permanently records class in the shared sync.Once state;
  3. call BackingSize(shards, 3): it reuses that completed state, skips validation of the full two-shard set, calls shard 0, and returns 3 with no error;
  4. ShardedAllocator.Allocate can select shard 1, whose allocation has capacity 4, so cache admission was prepared for 3 bytes while the selected shard retained 4.

I verified that shards[1:] compiles and executes from an external malloc_test package despite the unexported element type. The same root cause applies to append/reordered configurations that reuse a previously completed shard state. The existing inconsistent-shard test passes only because the full slice happens to be the first caller, so it does not cover the state/configuration identity invariant.

Please either make the shard configuration immutable and bind validation to the constructor's complete snapshot, or ensure every distinct derived configuration gets validation state that actually represents that configuration. Add a regression where a partial view is queried first and the later full heterogeneous configuration must still be rejected. Merely documenting call order would leave a public slice API with order-dependent correctness.

Systematic audit:

Question Result Evidence
Q1: exactly one effective owner Pass FIFO value ownership remains balanced across retain, rejected/duplicate set, purge, eviction, and close.
Q2: every wait terminates Pass The request cache and collision path are removed; sync.Once initialization is finite for the built-in contracts and no callback/wait edge was added.
Q3: every accumulation is bounded Blocker Normal full-slice use accounts retained backing capacity correctly, but a poisoned shared contract state lets a reachable shard retain more than the pre-allocation prediction, invalidating the cache's physical-capacity bound.

Performance verification on the same Linux/amd64 host (24 CPUs, identical LocalFS public path, 2s x 3):

  • fixed size: base 122.1-122.3 ns/op; head 122.3-122.4 ns/op;
  • sizes 1..1024: base 122.9-123.2 ns/op; head 122.1-123.3 ns/op;
  • both revisions: 48-49 B/op, 1 alloc/op.

Validation on the pinned head:

  • full malloc, fileservice/fifocache, fileservice, objectio, objecttool, and metric tests passed;
  • focused allocator contract and cache lifecycle tests passed under -race (allocator matrix at -count=20);
  • owning/dependent package go list, build, vet, dashboard compile, and git diff --check passed;
  • both temporary review worktrees were left clean;
  • CI for this latest head is still running at review time.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Fixed in c204c20.

I independently reproduced the counterexample from an external malloc_test package: shards[1:] is legal despite the private element type; querying it first previously poisoned the shared sync.Once, letting the original heterogeneous allocator report 3 bytes even though another shard reserves 4. External callers can also reorder existing elements, so a first-address/length snapshot is not sufficient.

The fix makes ShardedAllocator a public struct with a private shard slice and private allocator fields. The cached all-shard contract is now owned by that immutable configuration. This removes the derived-view API that made the cached result ambiguous, while preserving the normal path: one all-shard validation and O(1) backing-size prediction per request. The repository has no consumer of the old slice representation.

Verified with:

  • go test -race -count=20 ./pkg/common/malloc -run 'Test(BackingSize|ShardedBackingSize)'\n- go test -race -count=1 ./pkg/common/malloc\n- go test -race -count=1 ./pkg/fileservice ./pkg/container/types\n- LocalFS/S3FS fixed-size and high-cardinality allocation benchmarks: still 48 B/op and 1 alloc/op.

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

Reviewed current head c204c20. The previous shard-contract correctness, hot-path performance, and immutable-configuration concerns are addressed. Focused malloc, FIFO, and FileService tests pass, and the branch merges cleanly with current main. No remaining blocking findings.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

CI investigation: the red coverage checks are infrastructure failures, not test or coverage failures.

  • First attempt failed in the Guangzhou self-hosted runner while checkout fetched matrixorigin/CI through the configured proxy: TLS/prosisor fetch was reset before UT started.
  • The rerun completed all coverage UT and generated the compacted profile, then actions/upload-artifact@v7 failed at CreateArtifact with ECONNRESET, before content upload. The coverage merge failure is the expected downstream consequence of the missing artifact.

The same runner pool previously uploaded a comparable profile successfully, so this is intermittent proxy/GitHub egress instability rather than a profile-size limit or this PR. Tracked in matrixorigin/CI#417. No MatrixOne code change is being made for this CI-only failure.

@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 review completed at head 585f6fb75229b6040600f1c3ce88b75942d3ebe4 against merge-base 08770e1beeb23239c91165492f2fe85243a3c66a.

No blocking findings remain. The allocator backing-size contract, physical cache admission/accounting, logical-vs-backing metrics, FIFO ownership, eviction, stale-generation callbacks, and decorator propagation were reviewed end-to-end. Focused counterexamples, full owning-package tests, full race tests, build/vet, and LocalFS/S3FS fixed/high-cardinality benchmarks passed. Dashboard integration tests are the existing local-Grafana dependency and reproduce identically on the merge-base. Approving this head.

@mergify

mergify Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-09 06:09 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-09 07:05 UTC · at 9256a661464cb94d00e920ff2b9d6061f5d00407 · squash

This pull request spent 55 minutes 54 seconds in the queue, including 55 minutes 33 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 Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • 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

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/api-change kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] MOI IDC (QA) MO OOM

5 participants