Skip to content

fix ivf prefilter oom - #26759

Merged
mergify[bot] merged 14 commits into
matrixorigin:mainfrom
jiangxinmeng1:agent/fix-ivf-prefilter-oom
Aug 9, 2026
Merged

mergify[bot] merged 14 commits into
matrixorigin:mainfrom
jiangxinmeng1:agent/fix-ivf-prefilter-oom

Conversation

@jiangxinmeng1

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:

issue #26720

What this PR does / why we need it:

fix ivf prefilter oom

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

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

Requesting changes. The reproduced failures need to be addressed as system contracts, not as three local special cases.

  1. Representation-aware consumer memory accounting: put the estimator next to docfilter, or share docfilter's exact routing decision. It must cover the real build peak (live C structure, C serialization buffer, Go copy) and reader reconstruction/lifetime, be overflow-safe, and degrade to PASS whenever headroom cannot be proven. Add adversarial dense/sparse integer and varlen cases, plus genuinely parallel admission using the production throttler policy.

  2. Resumable LoopJoin evaluation: make the resume generation explicit and guarantee that each (probe row, build batch) condition is evaluated at most once. Cache the read-only expression result or evaluate only the remaining window; invalidate state on batch advance, Reset, Free, and error paths.

  3. Unified result-batch admission: use one can-append/admit primitive from every join type and finalize path. The invariant should be Batch.Size() <= limit unless the batch contains exactly one intrinsically oversized row. Cover conditional and unconditional INNER/LEFT/OUTER/SEMI/SINGLE/MARK/ANTI joins, unmatched rows, varlen/null values, split/resume, Reset/reuse, and injected errors.

Concrete proofs from review:

  • 100,000 sparse uint64 keys: raw vector 800,034 B, reservation 3,265,604 B, CRoaring output 2,200,009 B; the C serialization buffer plus Go copy alone are 4,400,018 B before counting the live C bitmap.
  • A 16,384-row non-equi build batch evaluates all 16,384 rows twice after splitting; a dense 10M-row batch would cause about 1,221 full evaluations.
  • With a 1,024-byte limit, SEMI JOIN over two 700-byte rows returns one 1,448-byte two-row batch.

The existing package tests, build/vet, full race runs, and 100x focused race repetitions pass, so these counterexamples should be added as explicit regression invariants.

Comment thread pkg/sql/colexec/loopjoin/join.go Resolved
Comment thread pkg/sql/colexec/loopjoin/join.go Resolved

@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-reviewed the complete diff and the latest f5a6a3c / bc38b3d fixes. The Sorted64 consumer charge and partial combinedTxnTable.BuildReaders cleanup address the two previous findings, but one P1 lifecycle blocker remains.

P1: normal merge-reader exhaustion drops child readers without closing them, permanently leaking the new admission lease.

In pkg/vm/engine/readutil/reader.go:393-395, when a child returns isEnd, mergeReader.Read removes it with r.rds = r.rds[1:] but never calls Close. After a successful full scan all children have been removed, so the later TableScan.Reset -> mergeReader.Close iterates an empty slice. Consequently reader.Close -> withFilterMixin.reset never runs for those children: their BF.Share() references are never freed, the last filter owner never invokes memoryRelease, and consumer-CN admission capacity is permanently consumed by every successful merge scan. Native cbitmap/CRoaring filters can leak their C allocations through the same path. The new mergeReader.Close only fixes early termination while children are still present; it does not close the normal EOF path.

Please close each child exactly once before dropping it (and define how a close error is returned), make the existing read-error/outer-close paths idempotent and release retained references, and add exact close/acquire/release-count regressions for:

  1. normal exhaustion of multiple children followed by outer Close;
  2. early LIMIT/cancellation;
  3. child read error;
  4. repeated Close.

Focused tests on this head pass (./pkg/common/docfilter, ./pkg/vm/engine/readutil), which also confirms the current suite does not exercise this ownership edge.

@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-reviewed the complete diff at current head 29864762654c06b3b84c0134d874ab2d80e8c715. The previous mergeReader blocker is fixed: normal EOF, read error, early Close, repeated Close, and child-close error now release each reader exactly once. The focused and package race tests pass.

One P1 memory-admission blocker remains.

P1: consumer leases can be released before the physical memory they protect is reflected in the throttler RSS baseline, and cbitmap/bloom omit the retained wire payload from the reservation.

NewWithMemoryAdmission installs the raw admission.Release callback on the reconstructed filter. When the last reader calls Free, cbitmap/CRoaring/Sorted64/bloom immediately drop that reservation without the ShouldRefreshBeforeRelease / ForceRefresh handoff already used by the producer path. The production throttler only refreshes opportunistically once per 10 seconds. Native pages may remain in RSS after free, and the serialized Go/protobuf payload remains reachable through FilterHint.MembershipFilterBytes until the reader/scope is reclaimed. A following query inside that window therefore observes freed reservation capacity plus a stale RSS sample and can reacquire the same capacity; rapid waves of large filters can still grow physical RSS past the limit.

I reproduced the missing transition on this head with a minimal admission double whose ShouldRefreshBeforeRelease returns true: NewWithMemoryAdmission followed by the last Free produced refreshes == 0 and only release, whereas the required order is refresh -> release. The diagnostic file was removed after the run.

There is a related peak-accounting gap in reconstructAllocationBytes: TagCbitmap reserves len(payload)+8, which is the reconstructed C object only, while the same len(payload) wire slice remains live; TagBloom similarly reserves one payload length while both the transported bytes and C copy coexist. TagSorted64 already explicitly charges its retained payload, so the other representation paths need an equivalent proof. The fix does not have to double-count blindly: either establish a current RSS baseline before reconstruction or reserve the unsampled retained payload plus reconstruction peak, but the invariant must hold under the 10-second stale-sample window.

Please make the consumer lease cover the complete retained-payload/reconstruction lifetime and conditionally refresh before its final release, preserving one lease per shared filter rather than per reader. Add a production-throttler regression that repeatedly acquires, reconstructs, closes the last share, and immediately reacquires for cbitmap, bloom, and Sorted64; it should prove that rapid turnover cannot over-admit even when RSS does not fall.

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

Can you write a better PR commit message, roughly explain WHY this cause an OOM?

Is it a real leak (C.malloc) or a quick storm of allocations that gc cannot catch up? Which change/file/function, is really critical to fix the real problme?

Comment thread pkg/common/bloomfilter/cbloomfilter.go Resolved
The OOM is rooted in a real native-memory lifecycle leak, not only Go GC lag. mergeReader previously discarded exhausted children without Close; reader Close is the terminal owner that releases the shared membership filter, so repeated queries could orphan C bitmap/bloom allocations outside GOMEMLIMIT. Concurrent build, serialization, transport, and reconstruction peaks amplified the RSS growth.

Complete the fix by charging consumer admission for both retained wire bytes and reconstructed native state, refreshing RSS before the last lease release, and reconstructing remote payloads once per BuildBlockReaders call with one share per reader. Previously the bytes reached a remote CN, but NewReader only consumes FilterHint.BF, so the remote filter and its ownership contract were bypassed.

Also remove the misleading bloom KeepAlive: the aliased C allocation is explicitly refcounted, not finalizer-owned, and KeepAlive cannot make a concurrent explicit Free safe. Add fail-closed remote decode, shared-lease, representation accounting, and release-order regressions.
@XuPeng-SH

Copy link
Copy Markdown
Contributor

@fengttt Answering the OOM/root-cause question directly: the primary defect is a real native-memory lifecycle leak; allocation bursts are a secondary amplifier.

Before this PR, mergeReader.Read removed an exhausted child from r.rds without calling Close. reader.Close -> withFilterMixin.reset -> BF.Free is the terminal ownership path. Skipping it left the shared-filter refcount above zero, so native cbitmap/CRoaring/bloom allocations never reached C.free; the consumer admission lease was leaked as well. With 100 concurrent clients and repeated queries, that accumulates outside Go's GOMEMLIMIT.

At the same time, producer serialization and consumer reconstruction temporarily coexist with the wire payload, so rapid build/transport/reconstruct waves increase RSS and make the leak surface sooner. This is why treating it as only "GC cannot catch up" is insufficient.

The critical fixes are:

  • pkg/vm/engine/readutil/reader.go: close every child on normal EOF, read error, early outer close, and repeated close — this fixes the actual lifecycle leak.
  • pkg/common/docfilter/memory.go: representation-aware producer/consumer admission, one lease per shared filter, complete wire/native peak accounting, and RSS refresh before final release.
  • pkg/vm/engine/disttae/engine.go: reconstruct remote payloads once on the consumer CN and share that owner across readers; previously the bytes arrived remotely but NewReader only consumed FilterHint.BF.
  • pkg/vectorindex/ivfflat/search.go: acquire producer admission at the actual filter allocation site.

Commit 1e4d0285f4 contains the detailed WHY in its message and closes the remaining consumer/remote gaps. We rebuilt libmo from this source generation and passed focused counterexample tests, package tests/build/vet, full race runs for docfilter/bloomfilter/readutil/disttae/loopjoin, plus 100x race repetitions for lease release and remote reader sharing.

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

Codex automated review

Revalidated the current head and post-3963338 changes. My prior stale-null blocker is fixed with logical-range accounting and regression coverage. Normal merge-reader cleanup, remote filter reconstruction/sharing, and release-time RSS refresh are addressed; the protocol gate is consistent with the documented deployment contract. The repeated integer-range scan is non-blocking and already reported by another reviewer, so it is not duplicated. No distinct blocking or non-blocking issue remains.

Reconstruct partition filters once, make reader construction consume and roll back its resources, and keep fulltext filters independent from PK pruning.

Scope remote filters to their index table domain and reject bloom reconstruction OOM before copying into C memory.
Comment thread pkg/vm/engine/readutil/pk_filter_mem.go Resolved

@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-reviewed the complete diff at exact head 65f822cd1866b03f3a5a6001da0cf157b48fef19.

The latest change correctly preserves the independently initialized IVF/fulltext membership filter when PK pruning fails open, and avoids publishing a partial disjunction. I revalidated the prior blockers end-to-end: representation-aware producer/consumer admission, retained-payload accounting and refresh-before-release, shared-filter ownership, partial/EOF/error/early-close reader cleanup, remote/local propagation, protocol-v11 rolling-upgrade gate, bounded resumable LoopJoin evaluation/output, and reset/error generations. No remaining correctness, performance, concurrency, compatibility, or unhappy-path blocker was found.

Fresh exact-head native rebuild, owning-package tests, selected-package build/vet, and sparse exact-filter benchmark all passed. GitHub required CI is green and all review threads are resolved.

@mergify

mergify Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-09 03:43 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-08-09 04:41 UTC · at eaa5e201d7f59063e5229cabe927859debd418a9 · squash

This pull request spent 57 minutes 34 seconds in the queue, including 57 minutes 20 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/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants