Skip to content

[4.2.1-hotfix] Fix vector ownership on clone and transaction errors - #31693

Merged
XuPeng-SH merged 1 commit into
release/v4.2.1-hotfix-20261026from
codex/fix-31690-v421-vector-leaks
Oct 29, 2026
Merged

XuPeng-SH merged 1 commit into
release/v4.2.1-hotfix-20261026from
codex/fix-31690-v421-vector-leaks

Conversation

@XuPeng-SH

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 #31690

What this PR does / why we need it:

Constant-NULL cloning can discard an owned destination buffer, and transaction error paths can abandon vectors borrowed from the Small pool. Retain owned destination capacity as a zero-length slice for reuse and eventual release, while detaching borrowed data safely. Register row-ID cleanup before either caller rejects an error, preserving write-write conflict continuation. Release newly acquired append vectors on failure until ownership transfers to the node; leave borrowed vectors under their existing owner.

Regression tests cover allocator/account balance, serialization, nil-mpool and borrowed-buffer controls, pool reuse and allocation-limit eviction, both actual lookup callers including cancellation/deadline errors and write-write conflict results, and append-vector early/late errors, successful transfer, and positive-offset borrowing. The new regressions fail against the original production code.

Validation: normal and race tests for pkg/container/vector, pkg/vm/engine/tae/containers, and pkg/vm/engine/tae/txn/txnimpl; incremental gofmt, go vet, MatrixOne molint, and repository-pinned golangci-lint. Native prerequisites were rebuilt locally from this release base. Vector owning-package tests use TZ=UTC: the existing TestRowToString fails in the host's New York timezone with the same signature on the original production code. These are internal ownership fixes with no intended SQL/error/protocol changes; no SQL BVT or performance benchmark was added. CI results are pending.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner October 29, 2026 06:16
@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 →

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement labels Oct 29, 2026
@mergify

mergify Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 02c88dab2d3cd93d1218a7d51d915ce71520cd52

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Commit: 02c88dab2d3cd93d1218a7d51d915ce71520cd52

Assessment: approve

The three ownership fixes preserve borrowed storage, node ownership transfer, and existing error semantics. Complete change and discussion review found no actionable defects.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Isolation preflight and native build from matching frozen inputs passed.

  • All three affected packages passed normally and under race: 215 tests each, no skips.

  • Seven regression tests each passed 100 focused race repetitions.

  • Scoped go vet, gofmt, and git diff --check passed.

  • validation-report.json reconciles 17 checks with source fingerprints, receipts, and retained logs. Discussion assessment is complete; source remains unchanged.

Limitations:

  • Validation used Linux amd64, Go 1.26.4, and TZ=UTC.

  • SQL BVT and production RSS/performance measurements were not run; the supplied CI snapshot provided no completed relevant validation.

@LeftHandCold

Copy link
Copy Markdown
Collaborator

Detailed review: ownership fixes and production TN memory attribution

Assessment: the three Vector ownership fixes are justified and suitable for a hotfix candidate. No new blocking code defect was identified in this review. Production rollout remains gated; this is not yet proof that this PR eliminates all of the observed TN memory growth.

Frozen review range:

  • Base: f6a27941d7185e3b406f7d45326ff9c86a9d1ff7 (release/v4.2.1-hotfix-20261026).
  • Head: 02c88dab2d3cd93d1218a7d51d915ce71520cd52.
  • Investigated TN binary: d2393868a7aaa6343518d80849fe4696aa3577e9 (v4.2.1). The relevant Vector / TAE transaction source at the PR base is unchanged from that TN version.
  • This comment records source review and existing evidence. No production mutation, new fault injection, or production workload replay was performed. It is not a claim that the entire exact-head test suite was independently rerun for this comment.

1. What the PR actually fixes

Closure Original failure Ownership after the patch Assessment
Vector.CloneWindowTo, Const-NULL branch Setting an already-owned destination data buffer to nil loses the only effective native-buffer cleanup handle. Later Vector close / Go GC cannot recover that buffer. Retain owned capacity with data[:0]; detach borrowed data without freeing its owner's allocation. Correct targeted fix. Pool accounting can see the retained capacity again, and subsequent reuse / eviction / Free can release it.
GetByFilter and DedupSnapByPK getRowsByPK may return both a Vector and an error. Registering cleanup only after the error check abandons that Vector on early returns. Register rowIDs.Close() immediately after the call when non-nil. Correct cleanup order; no premature release or duplicate cleanup found.
prepareApplyANode A newly acquired RowID Vector can be abandoned on an error before transfer to node.data. The function owns cleanup when startOffset == 0; successful assignment to node.data disarms that cleanup. Positive-offset vectors remain owned by the existing node. Correct ownership split; no new double-free or premature pool return found.

Source: Const-NULL clone, GetByFilter, DedupSnapByPK, append ownership transfer.

Important semantic checks:

  • GetByFilter still continues for ErrTxnWWConflict as before. Cleanup happens at function exit, not before the continuation. The returned RowID information is copied rather than exposing storage owned by the closed Vector.
  • DedupSnapByPK retains its existing error behavior, including conflict errors.
  • The newly allocated append Vector is closed only if ownership has not transferred. The startOffset > 0 branch does not install the new cleanup on a borrowed node Vector.
  • The patch does not change disk, wire, or catalog formats, add a background worker, or introduce a new lock. This reduces the scope of compatibility risk, but is not a blanket zero-regression guarantee for shared Vector code.

These are the defects tracked in #31690. They should not be conflated with the separate publication.convertObjectToBatch or ETL schema-mismatch investigations.

2. Evidence that the Const-NULL defect is reachable through a real TN consumer

Separate diagnostic work before this review exercised a real persisted-column reader, not just a direct call to the clone helper:

valid CN-created tombstone without hidden commit TS -> reader synthesizes Const-NULL -> LoadPersistedColumnData(needCopy=true, isTombstone=true) -> pooled destination clone.

The fixture first populated a reusable destination buffer using a valid object containing the commit-TS column, then read valid objects without that column. Its allocator / ownership oracle produced:

Observation Original code Owned-buffer retention fix
Three reuse cycles Native outstanding bytes: 16 -> 32 -> 48; pool-owned bytes: 0 Native / pool-owned bytes remain 16
After pool destruction 48 bytes remain 0 bytes remain
Fresh missing-column and complete-column controls Pass Pass

The counterexample was observed on Darwin/arm64 and Linux/amd64. This proves a real TN consumer can lose native ownership on the original code, and that retaining owned capacity fixes that counterexample.

Evidence reuse boundary: that diagnostic candidate used base 47e644f2d704c02baf90461de8f164e1d39c344e and the owned-buffer retention change. It was not this complete PR head. It supports the unchanged owned-buffer mechanism and consumer reachability; it must not be presented as exact-head validation of the additional borrowed-data and transaction-error changes. The tiny fixture's byte count is also not an estimate of production leakage per operation.

3. Why the production memory incident is not fully attributed yet

An anonymized TN observation around 2026-10-29 05:24 UTC / 13:24 CST recorded:

Metric Approximate observation
Process RSS 51.53 GiB
Container usage / limit 52.19 / 58 GiB
Total mpool off-heap 20.04 GiB
tae_small, included in that total 19.57 GiB
FileService memory cache, actual use / configured capacity 1.84 / 5 GiB

These are historical samples from this investigation, not a claim about the live state at the time someone reads this comment. Sampling times are close but not atomic, and these metrics must not be indiscriminately added together as disjoint RSS components.

The acquired malloc profile covered approximately the FileService cache allocation total, not the 19.57 GiB of mpool allocations. It did not provide the native allocation stacks needed to assign that outstanding mpool balance to individual paths. The Go heap profile cannot fill that native allocation gap.

One accounting distinction is particularly important here:

  • Small.GetVector() identifies the Vector checkout pool; it does not by itself establish the allocation owner of every buffer in that Vector.
  • getRowsByPK supplies common.WorkspaceAllocator when initially filling or growing the RowID data. A fresh / grown buffer is therefore normally charged to tae_workspace.
  • Reusing sufficient existing capacity preserves that buffer's previous allocation owner, which can be tae_small or tae_workspace. Cross-pool Free uses the recorded original owner.
  • prepareApplyANode uses the Vector wrapper's allocator for its RowID extension and can retain Small-allocator memory on the original failure paths. The real persisted-reader pool also uses SmallAllocator. Their production frequency and contribution are still unquantified.

Therefore, the correct classification is:

  • Proven code defects: the three ownership failures.
  • Strong targeted fix evidence: source closure, deterministic allocator oracles, and the existing exact-head validation statement.
  • Leading hypothesis, not proven complete production root cause: these failures account for all observed tae_small growth.

Neither all 19.57 GiB nor the total RSS should be labelled as the amount this PR will necessarily eliminate.

4. Validation evidence and its limits

The existing exact-head review reports Linux/amd64, Go 1.26.4, TZ=UTC; all three affected packages passing normally and under race (215 tests in each mode, no skips); seven regressions each passing 100 focused race repetitions; matching-input native build and static checks; and a 17-check validation-report.json with receipts and retained logs.

That is meaningful revision-bound validation evidence. However, the raw report and retained logs were not available to this review for independent reconciliation. It would be useful to provide an accessible, appropriately redacted evidence artifact / location. This does not imply that those checks failed or did not run.

Two test-boundary details should remain explicit:

  1. The new append transfer case uses rows=0, and borrowed_success uses offset==rows; both avoid the non-empty append loop. Existing owning-package tests such as TestAppend exercise real non-empty transactions, so this is not evidence of a new code bug or a demand to rebuild the test framework. Verify those existing tests are present in the package receipts. A focused one-row successful transfer and a 0 < offset < rows continuation would be useful optional strengthening.
  2. Some error cases deliberately use injected dependencies. That is valid for proving the cleanup contract, but not proof of production frequency: the real PrepareAppend implementation currently has no non-nil error return, and the offline late-error test enters an internal function that the usual offline-write entry point rejects earlier. Real schema-change and allocation / I/O failures remain separate reachable triggers.

The current completed GitHub checks are MongoDB E2E and Mergify checks, not full kernel validation. Also, the main CI entrypoint's target-branch filter does not include this release/... base. Do not assume the missing main kernel CI is simply queued and will appear automatically. Exact-revision local validation can supply the relevant evidence without waiting for a workflow that was not triggered.

5. Separate retained-memory findings not fixed by this PR

These are not regressions introduced by #31693 and should not be folded into its proven production impact.

A. TNUsageMemo.AddReqTrace retention. The investigated TN heap included approximately 560 MiB attributed to this diagnostic history. At the running version it appends per storage-usage request/account, with no identified runtime count/time retention limit; the production clear call was at DB close. This is Go-heap retained growth, not the same native-buffer leak. This PR does not touch it. Separate follow-up; not filed or changed by this review.

B. Appender object-reference cleanup before registration. A source-level follow-up remains in the same append operation:

GetAppender / SetAppender acquires object Ref -> schema mismatch or RowID construction/extension fails -> return before registering the current appender in space.appends -> CloseAppends cannot release that Ref.

GetAppender and SetAppender acquire the object reference; objectAppender.Close performs its matching Unref. The early returns in prepareApplyANode precede registration; transaction / table-space cleanup only closes registered appenders and does not compensate for this current reference. The IsSameColumns deferred Unref belongs to its separately pinned node, not this object reference.

The concrete consequence is that PrepareCompact refuses to proceed while the object reference count remains positive. This behavior already exists at the PR base. It has not been independently reproduced or quantitatively connected to the observed production memory balance in this review. Separate follow-up; no new Issue created here. It does not invalidate the Vector fix, but the PR should not be described as closing every resource leak in append error handling.

6. Hotfix / rollout decision

I support progressing this as a targeted ownership-fix candidate, subject to these release and incident-verification gates:

  1. Freeze the full release delta. The PR base already contains [4.2.1-hotfix] fix(plan): skip empty predicate deduction traversals #31511 (7ce664f08a) and [4.2.1-hotfix] fix(window): reuse unbounded aggregate frames #31581 (f6a27941d7) after the previously recorded CN hotfix 47e644f2d7. Publishing the whole branch is not the same change set as taking only this PR. If a smaller cherry-pick onto another approved base is chosen, validate the resulting source / dependency closure rather than relabelling existing results as a different build's validation.
  2. Reconcile exact-candidate validation and packaging. Confirm the source-bound normal/race/native receipts, non-empty transaction controls, and final release artifact identity. An isolated startup and small read/write smoke check on the final candidate is an operational gate, not a requirement to run a new large benchmark or production fault test.
  3. Apply the fix to the component that owns the memory. The investigated growth is in TN. Upgrading only CN leaves the old TN code running. Already-orphaned native allocations are not recovered by ordinary Go GC; reclaiming the old process's memory requires an explicitly approved TN replacement/restart plan. This review performs or authorizes no such operation.
  4. Judge recovery by the post-warmup trend under comparable work, not the immediate restart drop. Track tae_small, tae_workspace, total mpool, heap/RSS, workload volume, checkpoint/logtail progress, transaction failures, and restarts. A fresh process starting with less memory is not proof that the triggering leak has stopped.

Bottom line: #31693 fixes real ownership defects and is a credible, narrowly scoped hotfix candidate. No new blocking defect was found in the changes reviewed. The remaining gates concern exact release validation and proving how much of the production incident it resolves; they do not justify claiming that all TN memory growth or all future OOM risk is already eliminated.

@XuPeng-SH
XuPeng-SH merged commit 3391c68 into release/v4.2.1-hotfix-20261026 Oct 29, 2026
4 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-31690-v421-vector-leaks branch October 29, 2026 07:22
XuPeng-SH added a commit that referenced this pull request Oct 29, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #31690

## What this PR does / why we need it:

Forward-port the remaining constant-NULL clone ownership fix from
#31693. Keep owned data capacity as a zero-length slice for reuse and
eventual release. Release a borrowed data lease through its existing
reference-counted owner, or detach a legacy alias, while preserving
independent area ownership and existing runtime metadata handling.

The transaction-vector errors from #31690 already have cleanup in this
main base, so no transaction changes are included. Tests cover retained
capacity/accounting, nil-mpool and legacy aliases, serialization and
metadata reset, data-only and shared data/area lease release, pool
reuse, and allocation-limit eviction.

Validation: focused regressions and full normal/race tests for
`pkg/container/vector` and `pkg/vm/engine/tae/containers`; incremental
gofmt, go vet, repository-pinned molint and golangci-lint. Native
prerequisites rebuilt from this base; tests use Go 1.27.1 and TZ=UTC. CI
is pending.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH added a commit that referenced this pull request Oct 29, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #31690

## What this PR does / why we need it:

Forward-port #31693 to `4.2-dev`. Preserve owned destination capacity
when cloning a constant NULL, detach borrowed data safely, release
returned row-ID vectors on both callers' error paths, and release newly
borrowed append vectors until ownership transfers to the node. Existing
write-write conflict continuation and positive-offset borrowing remain
unchanged.

Validation: focused regressions and full normal/race tests for
`pkg/container/vector`, `pkg/vm/engine/tae/containers`, and
`pkg/vm/engine/tae/txn/txnimpl`; incremental gofmt, go vet,
repository-pinned molint and golangci-lint. Native prerequisites rebuilt
from this base; tests use Go 1.26.4 and TZ=UTC. Regression coverage
includes allocator/account balance, nil-mpool/alias controls, pool
reuse/eviction, real lookup callers with cancellation/deadline and
conflict controls, and append-vector error/transfer/borrowing paths. CI
is pending.
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants