Skip to content

perf(disttae): eliminate per-tombstone scan allocations - #26470

Merged
mergify[bot] merged 2 commits into
matrixorigin:mainfrom
gouhongshen:codex/fix-tombstone-iterator-allocation
Jul 30, 2026
Merged

mergify[bot] merged 2 commits into
matrixorigin:mainfrom
gouhongshen:codex/fix-tombstone-iterator-allocation

Conversation

@gouhongshen

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

What this PR does / why we need it:

Root cause

applyPStateTombstoneObjects adapted objectio.ObjectIter to a callback by doing:

entry := iter.Entry()
return &entry.ObjectStats, nil

ObjectIter.Entry() returns an ObjectEntry by value. Taking the address of a field on that local copy makes the whole copied entry escape to the heap. The tombstone scan therefore allocated once for every physical tombstone object it visited.

This is especially expensive for MOI's metadata discovery workload: every 5 seconds it scans many workspaces and databases, repeatedly reaching this path. The allocation is not the only cause of the QA memory pressure reported in #26465, but it is a measured contributor.

Change

  • Create and close the p-state object iterator explicitly.
  • Add reusableObjectStatsIter, which copies only ObjectStats into one reusable slot.
  • Return a pointer to that slot. Its documented lifetime is until the next next call, which matches the existing callback consumer contract.
  • Add an allocation regression test that scans 10,000 entries and rejects allocations proportional to entry count.

No API, storage format, or query result changes are introduced.

Validation

Automated checks

  • mo-cgo-test -count=1 -timeout=10m ./pkg/vm/engine/disttae: PASS
  • mo-cgo-test -count=100 -timeout=5m -run '^TestReusableObjectStatsIterAllocations$' ./pkg/vm/engine/disttae: PASS
  • CGo-aware go vet ./pkg/vm/engine/disttae: PASS
  • git diff --check origin/main...HEAD: PASS
  • make static-check: attempted, but the local repository molint binary was built with Go 1.20.5 and panics with unsupported version: 2 while reading Go 1.26.4 export data. This is a local analyzer/toolchain compatibility failure, not a reported lint finding.

The regression test executes 10 runs of a 10,000-entry scan and permits at most 2 allocations per run, preventing restoration of per-entry allocation behavior.

Targeted allocation measurement

A temporary A/B benchmark of the old and new adapters over 10,000 entries measured:

Adapter Allocations/op Bytes/op Time/op
Old field-address adapter 10,001 1.92 MiB ~342 µs
Reusable stats adapter 1 32 B ~128 µs

The benchmark helper was diagnostic-only and is not included in this PR; the allocation invariant is retained by the committed regression test.

QA-scale local A/B

The local fixture was matched to the QA metadata and tombstone scale:

Metric Local QA
mo_database rows 93 93
mo_tables rows 685 703
mo_columns rows 684 670
MOI tenant catalog rows 329 329
Relevant physical tombstone objects 1,791 1,795

The workload used the deployed MOI metadata-discovery SQL and transaction boundaries:

  • 80 accounts/workspaces
  • 333 databases (4.1625 average, 27 maximum per workspace)
  • 8 workers
  • fixed 5-second cadence
  • 5 minutes per build
  • 60 passes, 4,800 workspace units, and 19,980 database synchronizations per build
  • zero workload failures in both runs

Both A/B servers were started with merge disabled in test-only binaries so the physical tombstone fixture remained stable. This was necessary because an earlier run was invalidated after automatic merge collapsed the tombstones between measurements. No merge-disabling instrumentation is part of this PR.

Results:

Runtime metric over 5 minutes Baseline Patched Difference
TotalAlloc delta 107,548,417,800 B 103,235,140,736 B -4,313,277,064 B (-4.01%)
Mallocs delta 1,035,987,666 1,015,212,702 -20,774,964 (-2.01%)
GC cycles 52 51 -1
HeapSys delta 1,751,482,368 B 1,675,067,392 B -76,414,976 B
Peak RSS 5,162,270,720 B 5,134,778,368 B -27,492,352 B
Peak live heap sample 3,133,560,144 B 3,358,671,056 B +225,110,912 B

Allocation profiles close the specific defect:

  • Baseline applyPStateTombstoneObjects.func1: 23,509,870 flat allocation objects and 4,304.79 MiB flat allocated space.
  • Patched build: the allocation site is absent from both flat allocation profiles.

Scope of the conclusion

This A/B proves that the patch removes the per-tombstone-object heap allocation under a workload and physical tombstone scale closely matching QA. It does not by itself prove that the complete QA CN OOM is resolved:

  • the local baseline did not OOM with a 24 GiB limit;
  • cumulative allocation fell materially, but peak RSS changed only slightly and the sampled peak live heap was noisy;
  • [BUG] MOI IDC (QA) MO OOM #26465 also contains a high-frequency, broad metadata-discovery workload that should be evaluated independently.

Therefore this PR references #26465 but does not close it.

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

Deep-reviewed current head 1098e7e. The reusable ObjectStats pointer is consumed synchronously before the next iterator call, iterator ownership and all error/return paths close correctly, and memory remains bounded to one reusable slot. No blocking issues found.

Validation: the allocation regression was enumerated and passed; measured race duration T=0.01s with B=30s, so it passed -race -count=100; the full disttae package passed normal and race tests; go build and go vet passed; CI is green.

@mergify mergify Bot added the queued label Jul 30, 2026
@mergify

mergify Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-30 20:15 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-30 20:59 UTC · at 7054ccc4faf4d0157dcfa45a57daccf1b3123924 · squash

This pull request spent 44 minutes 11 seconds in the queue, including 43 minutes 38 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

@mergify
mergify Bot merged commit 217b9e1 into matrixorigin:main Jul 30, 2026
24 of 25 checks passed
@mergify mergify Bot removed the queued label Jul 30, 2026
XuPeng-SH pushed a commit that referenced this pull request Jul 31, 2026
## What type of PR is this?

- [x] Improvement

## Which issue(s) this PR fixes:

Related to #26465

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

After #26470 removed the per-object allocation, large table scans still
test
every visible tombstone object for every data block. The QA workload in
#26465
has system tables with roughly 700 visible tombstone objects and scans
roughly
132 data blocks per statement, resulting in about 92,000 object-level
Rowid
zone-map checks per scan.

This PR builds a per-data-source interval index from each tombstone
object's
Rowid zone-map block range:

- ranges are sorted by minimum block ID and carry a cumulative maximum;
- each data block queries only intervals that can contain its block ID;
- candidate objects are restored to the original visible-object order
before
the existing tombstone reader is called, preserving read and error
order;
- objects without an initialized Rowid zone map remain unconditional
  candidates because they cannot be safely excluded;
- scans below 32 blocks keep the existing allocation-free linear
iterator to
  avoid paying the index construction cost for small reads;
- the index and candidate scratch space are released when the data
source is
  closed.

The existing object/block zone-map checks remain in place. This changes
only
candidate selection, not tombstone visibility or deletion semantics.

Validation:

- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
'^TestTombstoneObjectIndex' -count=1`
- exhaustive equivalence test over 701 objects and 1,100 block IDs
- QA-shape benchmark (700 tombstone objects, 132 data blocks, 5
iterations):
  - linear scan: about 501 us/op
  - index build: about 72 us/op, 57,344 B/op, 1 alloc/op
  - indexed block queries: about 11.8 us/op, 0 B/op
  - build plus queries is about 6x faster than the linear scan

This is intentionally separate from the cgroup pressure handling in
#26471.
It reduces the work generated by the workload but does not claim to
solve all
sources of CN memory pressure by itself.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…#26470)

### Root cause

`applyPStateTombstoneObjects` adapted `objectio.ObjectIter` to a callback by doing:

```go
entry := iter.Entry()
return &entry.ObjectStats, nil
```

`ObjectIter.Entry()` returns an `ObjectEntry` by value. Taking the address of a field on that local copy makes the whole copied entry escape to the heap. The tombstone scan therefore allocated once for every physical tombstone object it visited.

This is especially expensive for MOI's metadata discovery workload: every 5 seconds it scans many workspaces and databases, repeatedly reaching this path. The allocation is not the only cause of the QA memory pressure reported in matrixorigin#26465, but it is a measured contributor.

### Change

- Create and close the p-state object iterator explicitly.
- Add `reusableObjectStatsIter`, which copies only `ObjectStats` into one reusable slot.
- Return a pointer to that slot. Its documented lifetime is until the next `next` call, which matches the existing callback consumer contract.
- Add an allocation regression test that scans 10,000 entries and rejects allocations proportional to entry count.

No API, storage format, or query result changes are introduced.

### Validation

#### Automated checks

- `mo-cgo-test -count=1 -timeout=10m ./pkg/vm/engine/disttae`: PASS
- `mo-cgo-test -count=100 -timeout=5m -run '^TestReusableObjectStatsIterAllocations$' ./pkg/vm/engine/disttae`: PASS
- CGo-aware `go vet ./pkg/vm/engine/disttae`: PASS
- `git diff --check origin/main...HEAD`: PASS
- `make static-check`: attempted, but the local repository `molint` binary was built with Go 1.20.5 and panics with `unsupported version: 2` while reading Go 1.26.4 export data. This is a local analyzer/toolchain compatibility failure, not a reported lint finding.

The regression test executes 10 runs of a 10,000-entry scan and permits at most 2 allocations per run, preventing restoration of per-entry allocation behavior.

#### Targeted allocation measurement

A temporary A/B benchmark of the old and new adapters over 10,000 entries measured:

| Adapter | Allocations/op | Bytes/op | Time/op |
| --- | ---: | ---: | ---: |
| Old field-address adapter | 10,001 | 1.92 MiB | ~342 µs |
| Reusable stats adapter | 1 | 32 B | ~128 µs |

The benchmark helper was diagnostic-only and is not included in this PR; the allocation invariant is retained by the committed regression test.

#### QA-scale local A/B

The local fixture was matched to the QA metadata and tombstone scale:

| Metric | Local | QA |
| --- | ---: | ---: |
| `mo_database` rows | 93 | 93 |
| `mo_tables` rows | 685 | 703 |
| `mo_columns` rows | 684 | 670 |
| MOI tenant catalog rows | 329 | 329 |
| Relevant physical tombstone objects | 1,791 | 1,795 |

The workload used the deployed MOI metadata-discovery SQL and transaction boundaries:

- 80 accounts/workspaces
- 333 databases (4.1625 average, 27 maximum per workspace)
- 8 workers
- fixed 5-second cadence
- 5 minutes per build
- 60 passes, 4,800 workspace units, and 19,980 database synchronizations per build
- zero workload failures in both runs

Both A/B servers were started with merge disabled in test-only binaries so the physical tombstone fixture remained stable. This was necessary because an earlier run was invalidated after automatic merge collapsed the tombstones between measurements. No merge-disabling instrumentation is part of this PR.

Results:

| Runtime metric over 5 minutes | Baseline | Patched | Difference |
| --- | ---: | ---: | ---: |
| `TotalAlloc` delta | 107,548,417,800 B | 103,235,140,736 B | -4,313,277,064 B (-4.01%) |
| `Mallocs` delta | 1,035,987,666 | 1,015,212,702 | -20,774,964 (-2.01%) |
| GC cycles | 52 | 51 | -1 |
| `HeapSys` delta | 1,751,482,368 B | 1,675,067,392 B | -76,414,976 B |
| Peak RSS | 5,162,270,720 B | 5,134,778,368 B | -27,492,352 B |
| Peak live heap sample | 3,133,560,144 B | 3,358,671,056 B | +225,110,912 B |

Allocation profiles close the specific defect:

- Baseline `applyPStateTombstoneObjects.func1`: 23,509,870 flat allocation objects and 4,304.79 MiB flat allocated space.
- Patched build: the allocation site is absent from both flat allocation profiles.

### Scope of the conclusion

This A/B proves that the patch removes the per-tombstone-object heap allocation under a workload and physical tombstone scale closely matching QA. It does **not** by itself prove that the complete QA CN OOM is resolved:

- the local baseline did not OOM with a 24 GiB limit;
- cumulative allocation fell materially, but peak RSS changed only slightly and the sampled peak live heap was noisy;
- matrixorigin#26465 also contains a high-frequency, broad metadata-discovery workload that should be evaluated independently.

Therefore this PR references matrixorigin#26465 but does not close it.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## Which issue(s) this PR fixes:

Related to matrixorigin#26465

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

After matrixorigin#26470 removed the per-object allocation, large table scans still
test
every visible tombstone object for every data block. The QA workload in
matrixorigin#26465
has system tables with roughly 700 visible tombstone objects and scans
roughly
132 data blocks per statement, resulting in about 92,000 object-level
Rowid
zone-map checks per scan.

This PR builds a per-data-source interval index from each tombstone
object's
Rowid zone-map block range:

- ranges are sorted by minimum block ID and carry a cumulative maximum;
- each data block queries only intervals that can contain its block ID;
- candidate objects are restored to the original visible-object order
before
the existing tombstone reader is called, preserving read and error
order;
- objects without an initialized Rowid zone map remain unconditional
  candidates because they cannot be safely excluded;
- scans below 32 blocks keep the existing allocation-free linear
iterator to
  avoid paying the index construction cost for small reads;
- the index and candidate scratch space are released when the data
source is
  closed.

The existing object/block zone-map checks remain in place. This changes
only
candidate selection, not tombstone visibility or deletion semantics.

Validation:

- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
'^TestTombstoneObjectIndex' -count=1`
- exhaustive equivalence test over 701 objects and 1,100 block IDs
- QA-shape benchmark (700 tombstone objects, 132 data blocks, 5
iterations):
  - linear scan: about 501 us/op
  - index build: about 72 us/op, 57,344 B/op, 1 alloc/op
  - indexed block queries: about 11.8 us/op, 0 B/op
  - build plus queries is about 6x faster than the linear scan

This is intentionally separate from the cgroup pressure handling in
matrixorigin#26471.
It reduces the work generated by the workload but does not claim to
solve all
sources of CN memory pressure by itself.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…#26470)

### Root cause

`applyPStateTombstoneObjects` adapted `objectio.ObjectIter` to a callback by doing:

```go
entry := iter.Entry()
return &entry.ObjectStats, nil
```

`ObjectIter.Entry()` returns an `ObjectEntry` by value. Taking the address of a field on that local copy makes the whole copied entry escape to the heap. The tombstone scan therefore allocated once for every physical tombstone object it visited.

This is especially expensive for MOI's metadata discovery workload: every 5 seconds it scans many workspaces and databases, repeatedly reaching this path. The allocation is not the only cause of the QA memory pressure reported in matrixorigin#26465, but it is a measured contributor.

### Change

- Create and close the p-state object iterator explicitly.
- Add `reusableObjectStatsIter`, which copies only `ObjectStats` into one reusable slot.
- Return a pointer to that slot. Its documented lifetime is until the next `next` call, which matches the existing callback consumer contract.
- Add an allocation regression test that scans 10,000 entries and rejects allocations proportional to entry count.

No API, storage format, or query result changes are introduced.

### Validation

#### Automated checks

- `mo-cgo-test -count=1 -timeout=10m ./pkg/vm/engine/disttae`: PASS
- `mo-cgo-test -count=100 -timeout=5m -run '^TestReusableObjectStatsIterAllocations$' ./pkg/vm/engine/disttae`: PASS
- CGo-aware `go vet ./pkg/vm/engine/disttae`: PASS
- `git diff --check origin/main...HEAD`: PASS
- `make static-check`: attempted, but the local repository `molint` binary was built with Go 1.20.5 and panics with `unsupported version: 2` while reading Go 1.26.4 export data. This is a local analyzer/toolchain compatibility failure, not a reported lint finding.

The regression test executes 10 runs of a 10,000-entry scan and permits at most 2 allocations per run, preventing restoration of per-entry allocation behavior.

#### Targeted allocation measurement

A temporary A/B benchmark of the old and new adapters over 10,000 entries measured:

| Adapter | Allocations/op | Bytes/op | Time/op |
| --- | ---: | ---: | ---: |
| Old field-address adapter | 10,001 | 1.92 MiB | ~342 µs |
| Reusable stats adapter | 1 | 32 B | ~128 µs |

The benchmark helper was diagnostic-only and is not included in this PR; the allocation invariant is retained by the committed regression test.

#### QA-scale local A/B

The local fixture was matched to the QA metadata and tombstone scale:

| Metric | Local | QA |
| --- | ---: | ---: |
| `mo_database` rows | 93 | 93 |
| `mo_tables` rows | 685 | 703 |
| `mo_columns` rows | 684 | 670 |
| MOI tenant catalog rows | 329 | 329 |
| Relevant physical tombstone objects | 1,791 | 1,795 |

The workload used the deployed MOI metadata-discovery SQL and transaction boundaries:

- 80 accounts/workspaces
- 333 databases (4.1625 average, 27 maximum per workspace)
- 8 workers
- fixed 5-second cadence
- 5 minutes per build
- 60 passes, 4,800 workspace units, and 19,980 database synchronizations per build
- zero workload failures in both runs

Both A/B servers were started with merge disabled in test-only binaries so the physical tombstone fixture remained stable. This was necessary because an earlier run was invalidated after automatic merge collapsed the tombstones between measurements. No merge-disabling instrumentation is part of this PR.

Results:

| Runtime metric over 5 minutes | Baseline | Patched | Difference |
| --- | ---: | ---: | ---: |
| `TotalAlloc` delta | 107,548,417,800 B | 103,235,140,736 B | -4,313,277,064 B (-4.01%) |
| `Mallocs` delta | 1,035,987,666 | 1,015,212,702 | -20,774,964 (-2.01%) |
| GC cycles | 52 | 51 | -1 |
| `HeapSys` delta | 1,751,482,368 B | 1,675,067,392 B | -76,414,976 B |
| Peak RSS | 5,162,270,720 B | 5,134,778,368 B | -27,492,352 B |
| Peak live heap sample | 3,133,560,144 B | 3,358,671,056 B | +225,110,912 B |

Allocation profiles close the specific defect:

- Baseline `applyPStateTombstoneObjects.func1`: 23,509,870 flat allocation objects and 4,304.79 MiB flat allocated space.
- Patched build: the allocation site is absent from both flat allocation profiles.

### Scope of the conclusion

This A/B proves that the patch removes the per-tombstone-object heap allocation under a workload and physical tombstone scale closely matching QA. It does **not** by itself prove that the complete QA CN OOM is resolved:

- the local baseline did not OOM with a 24 GiB limit;
- cumulative allocation fell materially, but peak RSS changed only slightly and the sampled peak live heap was noisy;
- matrixorigin#26465 also contains a high-frequency, broad metadata-discovery workload that should be evaluated independently.

Therefore this PR references matrixorigin#26465 but does not close it.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## Which issue(s) this PR fixes:

Related to matrixorigin#26465

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

After matrixorigin#26470 removed the per-object allocation, large table scans still
test
every visible tombstone object for every data block. The QA workload in
matrixorigin#26465
has system tables with roughly 700 visible tombstone objects and scans
roughly
132 data blocks per statement, resulting in about 92,000 object-level
Rowid
zone-map checks per scan.

This PR builds a per-data-source interval index from each tombstone
object's
Rowid zone-map block range:

- ranges are sorted by minimum block ID and carry a cumulative maximum;
- each data block queries only intervals that can contain its block ID;
- candidate objects are restored to the original visible-object order
before
the existing tombstone reader is called, preserving read and error
order;
- objects without an initialized Rowid zone map remain unconditional
  candidates because they cannot be safely excluded;
- scans below 32 blocks keep the existing allocation-free linear
iterator to
  avoid paying the index construction cost for small reads;
- the index and candidate scratch space are released when the data
source is
  closed.

The existing object/block zone-map checks remain in place. This changes
only
candidate selection, not tombstone visibility or deletion semantics.

Validation:

- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
'^TestTombstoneObjectIndex' -count=1`
- exhaustive equivalence test over 701 objects and 1,100 block IDs
- QA-shape benchmark (700 tombstone objects, 132 data blocks, 5
iterations):
  - linear scan: about 501 us/op
  - index build: about 72 us/op, 57,344 B/op, 1 alloc/op
  - indexed block queries: about 11.8 us/op, 0 B/op
  - build plus queries is about 6x faster than the linear scan

This is intentionally separate from the cgroup pressure handling in
matrixorigin#26471.
It reduces the work generated by the workload but does not claim to
solve all
sources of CN memory pressure by itself.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…#26470)

### Root cause

`applyPStateTombstoneObjects` adapted `objectio.ObjectIter` to a callback by doing:

```go
entry := iter.Entry()
return &entry.ObjectStats, nil
```

`ObjectIter.Entry()` returns an `ObjectEntry` by value. Taking the address of a field on that local copy makes the whole copied entry escape to the heap. The tombstone scan therefore allocated once for every physical tombstone object it visited.

This is especially expensive for MOI's metadata discovery workload: every 5 seconds it scans many workspaces and databases, repeatedly reaching this path. The allocation is not the only cause of the QA memory pressure reported in matrixorigin#26465, but it is a measured contributor.

### Change

- Create and close the p-state object iterator explicitly.
- Add `reusableObjectStatsIter`, which copies only `ObjectStats` into one reusable slot.
- Return a pointer to that slot. Its documented lifetime is until the next `next` call, which matches the existing callback consumer contract.
- Add an allocation regression test that scans 10,000 entries and rejects allocations proportional to entry count.

No API, storage format, or query result changes are introduced.

### Validation

#### Automated checks

- `mo-cgo-test -count=1 -timeout=10m ./pkg/vm/engine/disttae`: PASS
- `mo-cgo-test -count=100 -timeout=5m -run '^TestReusableObjectStatsIterAllocations$' ./pkg/vm/engine/disttae`: PASS
- CGo-aware `go vet ./pkg/vm/engine/disttae`: PASS
- `git diff --check origin/main...HEAD`: PASS
- `make static-check`: attempted, but the local repository `molint` binary was built with Go 1.20.5 and panics with `unsupported version: 2` while reading Go 1.26.4 export data. This is a local analyzer/toolchain compatibility failure, not a reported lint finding.

The regression test executes 10 runs of a 10,000-entry scan and permits at most 2 allocations per run, preventing restoration of per-entry allocation behavior.

#### Targeted allocation measurement

A temporary A/B benchmark of the old and new adapters over 10,000 entries measured:

| Adapter | Allocations/op | Bytes/op | Time/op |
| --- | ---: | ---: | ---: |
| Old field-address adapter | 10,001 | 1.92 MiB | ~342 µs |
| Reusable stats adapter | 1 | 32 B | ~128 µs |

The benchmark helper was diagnostic-only and is not included in this PR; the allocation invariant is retained by the committed regression test.

#### QA-scale local A/B

The local fixture was matched to the QA metadata and tombstone scale:

| Metric | Local | QA |
| --- | ---: | ---: |
| `mo_database` rows | 93 | 93 |
| `mo_tables` rows | 685 | 703 |
| `mo_columns` rows | 684 | 670 |
| MOI tenant catalog rows | 329 | 329 |
| Relevant physical tombstone objects | 1,791 | 1,795 |

The workload used the deployed MOI metadata-discovery SQL and transaction boundaries:

- 80 accounts/workspaces
- 333 databases (4.1625 average, 27 maximum per workspace)
- 8 workers
- fixed 5-second cadence
- 5 minutes per build
- 60 passes, 4,800 workspace units, and 19,980 database synchronizations per build
- zero workload failures in both runs

Both A/B servers were started with merge disabled in test-only binaries so the physical tombstone fixture remained stable. This was necessary because an earlier run was invalidated after automatic merge collapsed the tombstones between measurements. No merge-disabling instrumentation is part of this PR.

Results:

| Runtime metric over 5 minutes | Baseline | Patched | Difference |
| --- | ---: | ---: | ---: |
| `TotalAlloc` delta | 107,548,417,800 B | 103,235,140,736 B | -4,313,277,064 B (-4.01%) |
| `Mallocs` delta | 1,035,987,666 | 1,015,212,702 | -20,774,964 (-2.01%) |
| GC cycles | 52 | 51 | -1 |
| `HeapSys` delta | 1,751,482,368 B | 1,675,067,392 B | -76,414,976 B |
| Peak RSS | 5,162,270,720 B | 5,134,778,368 B | -27,492,352 B |
| Peak live heap sample | 3,133,560,144 B | 3,358,671,056 B | +225,110,912 B |

Allocation profiles close the specific defect:

- Baseline `applyPStateTombstoneObjects.func1`: 23,509,870 flat allocation objects and 4,304.79 MiB flat allocated space.
- Patched build: the allocation site is absent from both flat allocation profiles.

### Scope of the conclusion

This A/B proves that the patch removes the per-tombstone-object heap allocation under a workload and physical tombstone scale closely matching QA. It does **not** by itself prove that the complete QA CN OOM is resolved:

- the local baseline did not OOM with a 24 GiB limit;
- cumulative allocation fell materially, but peak RSS changed only slightly and the sampled peak live heap was noisy;
- matrixorigin#26465 also contains a high-frequency, broad metadata-discovery workload that should be evaluated independently.

Therefore this PR references matrixorigin#26465 but does not close it.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [x] Improvement

## Which issue(s) this PR fixes:

Related to matrixorigin#26465

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

After matrixorigin#26470 removed the per-object allocation, large table scans still
test
every visible tombstone object for every data block. The QA workload in
matrixorigin#26465
has system tables with roughly 700 visible tombstone objects and scans
roughly
132 data blocks per statement, resulting in about 92,000 object-level
Rowid
zone-map checks per scan.

This PR builds a per-data-source interval index from each tombstone
object's
Rowid zone-map block range:

- ranges are sorted by minimum block ID and carry a cumulative maximum;
- each data block queries only intervals that can contain its block ID;
- candidate objects are restored to the original visible-object order
before
the existing tombstone reader is called, preserving read and error
order;
- objects without an initialized Rowid zone map remain unconditional
  candidates because they cannot be safely excluded;
- scans below 32 blocks keep the existing allocation-free linear
iterator to
  avoid paying the index construction cost for small reads;
- the index and candidate scratch space are released when the data
source is
  closed.

The existing object/block zone-map checks remain in place. This changes
only
candidate selection, not tombstone visibility or deletion semantics.

Validation:

- `go test ./pkg/vm/engine/disttae -count=1`
- `go test -race ./pkg/vm/engine/disttae -run
'^TestTombstoneObjectIndex' -count=1`
- exhaustive equivalence test over 701 objects and 1,100 block IDs
- QA-shape benchmark (700 tombstone objects, 132 data blocks, 5
iterations):
  - linear scan: about 501 us/op
  - index build: about 72 us/op, 57,344 B/op, 1 alloc/op
  - indexed block queries: about 11.8 us/op, 0 B/op
  - build plus queries is about 6x faster than the linear scan

This is intentionally separate from the cgroup pressure handling in
matrixorigin#26471.
It reduces the work generated by the workload but does not claim to
solve all
sources of CN memory pressure by itself.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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/enhancement kind/test-ci size/S Denotes a PR that changes [10,99] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants