Skip to content

[4.1] fix(fileservice): backport memory cache allocator - #27584

Merged
XuPeng-SH merged 9 commits into
matrixorigin:4.1-devfrom
VioletQwQ-0:codex/issue-27567-4.1-memory-cache-backport
Aug 30, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:4.1-devfrom
VioletQwQ-0:codex/issue-27567-4.1-memory-cache-backport

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

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

Which issue(s) this PR fixes:

Related issues: #26992, #27567

What this PR does / why we need it:

This PR backports the memory-cache backing-capacity accounting and the dedicated jemalloc allocator to 4.1-dev.

The change is based on upstream PR #26997 (allocator replacement) and #26783 (backing-capacity accounting), adapted to the exact 4.1-dev base 0d5195e5f93292939e2c5bca66a9746993315d25. It adds:

  • allocator-backed capacity accounting before cache admission;
  • one isolated jemalloc arena per configured memory cache, with bounded pending-buffer reuse and explicit reclaim/close ownership;
  • foreign-cache-data rehoming and reservation transfer on insert/reject/evict/close;
  • service-scoped logical, physical/backing-overhead, and allocator statistics;
  • the pinned jemalloc 5.3.1 source archive and static build verification.

The backport preserves the 4.1 FileService/objectio surface and does not import unrelated main-only DISK-V2, ONNX, CopyObject, or validation-pipeline changes. No SQL syntax, wire protocol, storage format, or default public configuration is changed.

This update also closes the startup and remote-cache safety gaps identified during review:

  • remote-cache responses are accepted only for indexes sent to that target, with nil, range, duplicate, and hit-payload-size checks; malformed responses fall back to local storage;
  • compressed ObjectIO remote-cache hits carry the final CachedData representation size separately from the compressed extent size;
  • malformed remote-cache requests are rejected before indexing or reading, and partial cache data is released on read failure;
  • embedded FileService construction tracks created counters and closes all already-created services on later failure;
  • embedded operator/cluster startup transfers ownership before service start and rolls back partially-created services, including retryable cleanup for dynamically added CN services;
  • failed initial startup cleanup retains service dependencies together and is retried before a replacement cluster generation is admitted;
  • the default TMP FileService is rooted under the service data directory.

This update also repairs the exact 4.1 CI failures without changing allocator behavior:

  • MORPC server send-failure terminals snapshot oneWay before messageSent, which may drop the final reference and return a synchronous Future to the pool; deterministic tests cover both cleanSend and unwritten write-failure paths and preserve one-way cleanup;
  • the TAE test-only forced-checkpoint guard uses the current-main two-minute bound for flush plus incremental checkpoint completion;
  • the unstable-network lockservice regression remains three workers with disconnect-after-five fault injection, but is bounded to 32 iterations and 20 seconds while requiring complete progress, successful unlocks, and at least one lock success per worker.

Validation

  • GOWORK=off go list -mod=readonly for all changed Go packages: PASS.
  • GOWORK=off go build -mod=readonly and go vet -mod=readonly for all changed production packages: PASS.
  • Targeted and full-package CGo tests for the changed FileService, objectio, embed, allocator, MORPC, lockservice, cnservice, mo-service, metrics, and TAE testutil packages: PASS except Grafana dashboard creation, which requires an external local Grafana endpoint unavailable in this environment.
  • New cache/startup CR regressions: normal CGo PASS; each focused test passed -race -count=100; full owning-package race runs for pkg/common/malloc, pkg/embed, pkg/fileservice, and pkg/objectio: PASS.
  • MORPC deterministic regression: both tests FAIL on the old access order with duplicate Future release, then PASS after the fix; each new test passes -race -count=50, and the full pkg/common/morpc race run passes.
  • TestCannotHungWithUnstableNetwork: normal PASS, -race -count=10 PASS, and the full pkg/lockservice race run passes.
  • TestBackupProtectionCheckpointProtection and TestBackupProtectionCheckpointFiltering: normal PASS, each -race -count=5 PASS, and the full pkg/backup race run passes.
  • Current-head build and vet for all changed Go packages: PASS; the dashboard package compiles, while its live Grafana tests remain environment-blocked as stated above.
  • Semantic preflight for local head d506236e15f8adf341fd4091e5375b02da9707d6: PASS semantic=PASS with complete reviewed-content SHA-256 058dc6ccf37194fc89a65ffff1a0059d5b3f10a34225979f93906191c0118045.
  • Jemalloc source SHA-256: 3826bc80232f22ed5c4662f3034f799ca316e819103bdc7bb99018a421706f92; local static build: PASS.
  • BVT: N/A — physical allocator ownership, native reclaim, remote-cache validation, embedded startup rollback, and pooled-Future terminal ordering are package-internal and are not meaningfully observable through SQL/BVT. The deterministic package, CGo, and race tests above exercise the production constructors, handlers, and terminal paths.

QA required: yes. The backport changes allocator/cache ownership and embedded startup cleanup. QA should validate the target 4.1-dev deployment and the #26992 workload before merge acceptance; this PR does not claim that workload has been rerun.

Backport the backing-capacity accounting and dedicated jemalloc memory-cache allocator from upstream commits 0676200 and 31adf54.

This keeps the 4.1 service and objectio surface, adds physical/logical cache metrics, and avoids importing unrelated main-only features.
@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 →

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed XuPeng-SH's two blocking findings on exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054:

  • Added IOEntry.CachedDataSize, populated it from Extent.OriginSize() at every ObjectIO extent-read entry point, and validated remote hits against the final cached representation. Added compressed ObjectIO remote-hit coverage.
  • Kept operator service/dependency ownership together when Close fails, recorded initial-start pending cleanup, retried it before restart, and blocked Start from overwriting an incomplete generation. Added failed-close/retry coverage.

Validation: focused and full CGo package tests pass; each new regression passed -race -count=100; full race passed for pkg/common/malloc, pkg/embed, pkg/fileservice, and pkg/objectio; build/vet pass. The dashboard package compiles, but its live Grafana tests remain blocked because no local Grafana endpoint is available.

BVT remains N/A because these are package-internal allocator/cache/embed lifecycle contracts.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI triage for exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054:

  • Ubuntu/x86 UT job 98919947638 in run 33192109080 ended with GitHub's self-hosted runner communication-loss annotation. The Unit Testing step has no usable test result or job log. This is a runner/setup cluster; I am not starting another blind rerun after the same-head retry history.
  • Compose PROXY job 98922221470 executed the BVT and failed only at zz_statement_query_type/aggr_error_stmt.sql row 6. The artifact records an oracle mismatch: expected statement_not_exist/statement_not_exist_2 counts 1/1, actual counts 4/3 (the _3 row remains 1/1). The BVT case and statement-info implementation are unchanged by this PR.
  • Coverage job 98929476213 failed its prerequisite check with prerequisites_ready=false; it is a dependent cluster after the UT/Compose failures, not an independent coverage result.

The exact 4.1-dev base is 0d5195e5f93292939e2c5bca66a9746993315d25; the owning worktree and remote branch both match the exact PR head. The previous exact predecessor 9e6179be914a236e176ec11c39c6546b3612462e passed the same Compose PROXY check. A local exact-head/base BVT comparison is currently blocked before build by a Docker BuildKit host I/O error, and the default local port 6001 is occupied. Therefore the direct BVT mismatch is not classified as unrelated or as a PR regression yet.

No source change or rerun was made. The required CI state remains unresolved. Next action is an isolated exact-head/base BVT reproduction or actionable Compose failure output, plus a clean exact-head Ubuntu/x86 UT result.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Reran only the confirmed self-hosted-runner failure for exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054: run 33192109080, job 98919947638. I did not rerun the Compose oracle-mismatch or dependent Coverage failures; they remain separate unresolved clusters pending exact-head/base reproduction. No source change was made.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI update for the exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054 (run 33192109080, attempt 2):

  • Ubuntu/x86 UT job 98986884685 was retried after the previous runner failure and received the same self-hosted-runner communication-loss annotation. The retry produced no usable test result or test log; the runner/setup retry budget is exhausted.
  • Compose PROXY job 98986886810 executed the BVT and failed one assertion in zz_statement_query_type/aggr_error_stmt.sql (row 6). The expected statement_not_exist counts were 1/1/1, while the run observed 4/3/1 for statement_not_exist, statement_not_exist_2, and statement_not_exist_3. This case and the statement-info implementation are unchanged by the PR. A local exact-head/base Compose comparison is still blocked because the canonical compose configuration binds host port 6001, which is occupied by an existing SSH listener; I am not classifying this cluster as unrelated or PR-specific without that comparison.
  • Coverage job 98986887821 failed only its prerequisite check after the UT/Compose failures, so it is a dependent cluster with no independent coverage result.

No source change or further rerun was made. Required CI remains unresolved. The next safe action is a clean current-head UT result plus an exact-head/base Compose reproduction once the fixed-port environment is available; the PR also remains pending XuPeng-SH review confirmation.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI update for exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054 (run 33192109080, attempt 3):

  • Required Ubuntu/x86 UT job 99044036142 completed with failure, but reported zero steps. Its check output has no title, text, or summary, annotations are empty, and the job-log endpoint returns HTTP 404 (BlobNotFound). This is a runner/setup evidence cluster, not a test result; an exact-head source failure is not established.
  • Compose PROXY job 99044035761 and Coverage job 99046883800 passed on the same exact head.
  • The permitted runner/setup retry budget is exhausted, so no further rerun or source change is being made. Required CI remains unresolved.

Next action: obtain a clean Ubuntu/x86 UT execution on this exact head, then await XuPeng-SH's re-review.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed both blocking findings from XuPeng-SH's review on exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054.

  • Remote cache now carries IOEntry.CachedDataSize from ObjectIO OriginSize() and validates compressed remote hits against the final cache representation before admission. Focused final-representation and invalid-response tests pass.
  • Initial startup now transfers service ownership before Start, retains dependencies after a failed Close, records pending cleanup, and retries cleanup before restart. Focused partial-rollback, failed-close, and retry tests pass.

Validation on this exact head: focused pkg/fileservice and pkg/embed tests PASS; all 8 focused race stress tests pass at -count=100; full owning-package race runs PASS; changed-package build/vet and git diff --check PASS. BVT is N/A for these package-internal allocator, cache-representation, and startup-lifecycle contracts. The required Ubuntu/x86 UT check remains an unresolved attempt-3 zero-step runner/setup failure; no source failure was established.

Please re-review this exact head.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI update for exact head 519a4ceb5e32b56a028e60603150fc4aa0d2c054 (run 33192109080, attempt 4, job 99137991144):

  • Ubuntu/x86 UT reached the Unit Testing step and failed in pkg/tests/ddl/TestPitrCases with a nil-pointer panic at pkg/embed/testing.go:85.
  • This is a distinct test-execution cluster from the earlier zero-step runner/setup failure. Because this PR changes pkg/embed lifecycle code, I am not classifying it as unrelated based only on the failing package path.
  • The scoped GOWORK=off go test -run '^TestPitrCases$' -count=3 ./pkg/tests/ddl and full GOWORK=off go test ./pkg/tests/ddl -count=3 both pass on the PR head and exact 4.1-dev base. The CI failure is not reproduced locally, so no minimal source fix is established.
  • No further blind rerun or source mutation is being made. Required CI remains unresolved pending a clean exact-head Ubuntu/x86 result or a reproducible failure with actionable evidence.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI diagnosis for exact head 9b0591e440b8a4d37f1b7c4847f21aeae521e81b:

  • Run 33302721628, original Ubuntu/x86 UT job 99233721178, failed in pkg/tests/shard/TestPartitionBasedShardCanBeCreated after HAKeeper connection resets/timeouts caused a cluster-startup cascade and information_schema initialization panic.
  • The focused CGo/race command passed 3/3 on both the PR head and exact 4.1-dev base 0d5195e5f93292939e2c5bca66a9746993315d25 (20.205s and 20.319s). The failure is therefore classified as shared CI/service instability; no source fix is established.
  • I reran only the failed UT job once. The rerun is queued as job 99239868264; required CI remains unresolved pending its result.

No source or branch change was made from this cluster.

@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 incremental re-review completed at exact head 9b0591e against exact 4.1-dev base 0d5195e. I reused the prior full review for the patch-identical allocator, cache, and MORPC stack and reviewed every hunk in the two commits after my previous CHANGES_REQUESTED review, plus the affected consumers and lifecycle terminal paths.

Both previous blockers are closed. ObjectIO now carries the final cached representation size from every extent-read entry point, so compressed remote-cache hits are validated against OriginSize rather than compressed extent length, with focused FileService and ObjectIO coverage. Failed initial embedded startup now retains the service together with its stopper and FileService dependencies, records incomplete cleanup, rejects replacement startup while cleanup remains incomplete, and retries cleanup before admitting the next generation.

The latest commit also fixes the shared embedded-test cluster error contract: initialization state stores the first startup error alongside sync.Once, every test and benchmark call supplies a reporter, and subsequent callers fail with the original error rather than continuing with a nil cluster. All repository callers were updated; this is test-only and adds no production hot-path cost.

Q1: service and dependency ownership remains with one operator until successful cleanup, and cluster pending cleanup is de-duplicated and retried. Q2: no new wait edge is introduced; cleanup and restart remain serialized by the cluster/operator locks. Q3: pending cleanup is bounded by configured service count and is drained before restart; the once-cluster state is constant-size. No new correctness, compatibility, liveness, leak, OOM, logging, or material performance blocker was found.

Evidence reused on this exact head: Ubuntu/x86 UT, shared build, arm64 SCA, coverage, compose PROXY BVT, and pessimistic multi-CN BVT all completed successfully. The isolated macOS review worktree lacks its own cgo/libmo.dylib, so I did not misclassify that local prerequisite as product evidence.

@iamlinjunhong iamlinjunhong 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 the complete 4.1-dev..9b0591e diff, affected call chains, lifecycle ownership, and tests. I found two blocking P1 issues in the new startup rollback/retry path; details are inline. No P0 issue was found. Because the P1 issues remain at the current head, this review requests changes.

Comment thread pkg/embed/cluster.go Resolved
Comment thread pkg/embed/cluster.go Resolved
@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed both current-head P1 findings from iamlinjunhong in commit d506236.

  • Replaced atomic.Value first-error capture with sync.Once plus a typed error field, and added a regression for heterogeneous concurrent CN startup errors.
  • Tracked embedded QueryClient and CNHAKeeperClient instances in operator.reset. Close now releases them after their dependents, retains failed closes for retry, and Start blocks a replacement generation until cleanup completes. Added regressions for wait failure, failed-start retry, and normal Close.

Validation in the target worktree CGo environment:

  • Focused lifecycle/error regressions: -race -count=100 PASS.
  • Full ./pkg/embed race package: PASS.
  • ./pkg/embed list, build, vet, and normal test: PASS.
  • git diff --check and semantic preflight: PASS.

BVT: N/A — this is package-internal embedded lifecycle/error-path behavior with no SQL/DDL boundary; the existing PR BVT exception remains applicable.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

The exact-head UT failure on d506236e15f8adf341fd4091e5375b02da9707d6 was diagnosed as runner connectivity loss, not a test assertion failure. Run 33308383282, job 99248898410, completed setup, checkout, Go setup, and the unit-test step before the runner lost communication with GitHub.

The failed job was rerun once under the existing rerun budget after confirming the current 4.1-dev base (0d5195e5f93292939e2c5bca66a9746993315d25). The replacement UT job is pending on the same exact PR head. CI remains unresolved until that job reaches a terminal result; no source change was made for this infrastructure failure.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

CI diagnosis for exact head d506236e15f8adf341fd4091e5375b02da9707d6:\n\n- Run 33308383282, attempt 2, job 99261154961 failed in the Ubuntu/x86 Unit Testing step with these independent test clusters: pkg/tests/shard/TestPartitionBasedShardCanBeCreated, pkg/tests/ddl/TestCreateAndDropPitr, pkg/tests/features/TestTableFeatures, pkg/vm/engine/tae/db/test/Test_TmpFileService1, pkg/tests/issues/TestIssue23861FulltextSnapshotRestore, pkg/vm/engine/tae/logstore/driver/logservicedriver/TestReplay1, pkg/tests/dml/TestAffectedRows, pkg/tests/dml/TestDeleteAndSelect, and pkg/taskservice/TestRemovedCronTask.\n- I ran each exact test with go test -race -count=3 in clean worktrees at the PR head and exact 4.1-dev base 0d5195e5f93292939e2c5bca66a9746993315d25; all nine passed on both commits.\n- This is a separate cluster from the earlier runner-communication failure. No source change or additional blind rerun was made. The required UT check remains red/unresolved; this cluster is being treated as external/flaky pending a healthy CI rerun or infrastructure investigation.

@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 incremental re-review completed at exact head d506236e15f8adf341fd4091e5375b02da9707d6 against exact 4.1-dev base 0d5195e5f93292939e2c5bca66a9746993315d25.

I reused my complete review and approval at 9b0591e: the allocator, cache, remote-cache, ObjectIO, MORPC, metrics, native build, and earlier embedded rollback closures are unchanged. The only newer commit is the three-file startup/client-lifecycle fix, and I reviewed every new hunk plus all affected construction, normal Close, failed-start rollback, cleanup retry, and replacement-generation paths.

Both newer P1 findings are closed. Concurrent CN startup now captures the first heterogeneous error through sync.Once, so it cannot panic on atomic.Value concrete-type mismatch. Query clients and the temporary HAKeeper client are transferred into the operator reset owner immediately after construction, retained on failed cleanup, closed only after dependent service/FileService resources, and included in needsCleanup/restart admission. Partial construction, wait failure, normal Close, initial-start rollback, dynamic cleanup retry, repeated Close, and next-generation startup all preserve bounded ownership.

Unhappy-path audit: Q1 passes because every created client remains reachable from exactly one cleanup generation until successful idempotent Close; Q2 passes because the new synchronization is startup-only, all CN goroutines join through the existing WaitGroup, and cleanup remains serialized by the existing cluster/operator locks; Q3 passes because retained cleanup state is bounded by configured services and FileServices and is drained before restart. The delta adds no steady-state request-path work, lock, allocation, or logging, so it has no material hot-path performance or log-storm risk.

Exact-head evidence: rebuilt the pinned thirdparty and CGo artifacts on macOS/arm64; seven focused startup/cleanup regressions passed under -race -count=50; the complete pkg/embed suite passed in 113.639s. Required current-head CI is green: Ubuntu/x86 UT, arm64 SCA, shared build/coverage, PROXY compose BVT, and pessimistic multi-CN BVT. git diff --check passes and the review worktree is clean.

No blocking finding remains; approving this head. As the PR body states, rerunning the #26992 workload is still a QA/merge-acceptance gate; this code approval does not by itself claim that the production workload has been revalidated.

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants