Skip to content

Reduce transient catalog replay memory - #32611

Merged
mergify[bot] merged 12 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/39b02282d870642a032a8699a641533a3afd4edb93eff6ce4226a96033359f74
Nov 12, 2026
Merged

mergify[bot] merged 12 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/39b02282d870642a032a8699a641533a3afd4edb93eff6ce4226a96033359f74

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Related to #32426

What this PR does / why we need it:

Catalog replay previously merged all column batches into another full catalog-sized batch. Process complete table groups from borrowed windows, retain only one table across batch boundaries, and release input batches as they are consumed. Validate grouping keys, clean up partial allocations on errors and cancellation, and retain a usable bounded rollback context after cancellation. This reduces transient copying while preserving the tested schema and replay/reconnect behavior.

Validation

  • The independently reviewed head a410355fc8d8aadb61ed3d44bdd6cf059d3ad76f passed, on Darwin arm64 with Go 1.27.1 using the repository CGo wrapper, six focused replay tests covering grouping, parser ownership, cancellation, partial allocation failure, retry, and delta confirmation; two focused frontend view-privilege tests; and -race single-CN TestCatalogReplayReconnect and two-CN TestCatalogReplayMultiCN integration tests.
  • At the same head, four additional focused tests passed: TestPrivilegeCacheVersionRejectsUnprovenCatalog, TestPrivilegeCacheVersionPreservesSnapshotErrors, Test_doRevokePrivilege, and TestSelectLockViewAlternativesAndErrors.
  • Historical evidence at de9843525110ff67867b600f199e639b3120cc2a: normal-mode single- and multi-CN integration tests passed; race runs of TestCatalogReplayReconnect passed with counts 1 and 4, and TestCatalogReplayMultiCN with counts 1 and 2. Earlier owning-package, race, and incremental vet/lint results remain historical evidence for unchanged relevant code, not tests rerun at the current head.
  • Earlier historical evidence: two mo-tester DDL BVT comparisons passed 21/21. A same-fixture comparison observed five real replay batches and four tables crossing batch boundaries, with sampled SQL results matching. An older-release catalog upgrade was tested for a single batch. Full CI, the full isolated and DDL suites, and the new frontend privilege SQL BVT have not been run locally at the current head; CI was still in progress with skipped jobs at review time.

Performance and limits

Historical measurements at earlier revisions, not rerun on the current head: a component comparison on the production nil-seam path measured 54.1% lower allocations for the tested 128-column cross-batch case. Earlier component measurements observed a 6.8% median increase for an aligned case; subsequent investigation measured the added scan and did not eliminate that result. Alternating real-service comparisons did not show a stable overall regression in the measured stages; sorting and consumption at equivalent cleanup boundaries were not isolated. These are scoped measurements, not a general performance guarantee.

The executor still materializes all input, active engine/planner metadata is not compressed, and the largest single-table carry has no new column-count bound. Linux cgroup peak/events, production-scale concurrency, the reported 16 GiB OOM, process peak/RSS, complex-schema performance at scale, and extremely wide-table carry were not verified. The combined older-version upgrade plus multi-batch reconnect and complete older collation semantics were not tested. The first-connect failure diagnostic used substitutes and did not verify real receiver handoff or final readiness; the cancellation probe had empty TN shards, and named delta confirmation was tested independently. Remote rollback and the full SQL KILL matrix were not tested.

@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 the kind/bug Something isn't working label Nov 12, 2026
@mergify

mergify Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a410355fc8d8aadb61ed3d44bdd6cf059d3ad76f

Review completed. Read the assessment.

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

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

Commit: a410355fc8d8aadb61ed3d44bdd6cf059d3ad76f

Assessment: approve

No actionable defects found. Borrowed windows and a one-table carry remove the full-column merge while preserving parser ownership, cleanup, retry and readiness contracts. The added state is justified by the scoped memory benefit.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Reviewed all nine changed files, relevant owners and consumers, linked issue context and every discussion entry.

  • Frozen same-head CI records successful build, UT, static analysis, proxy BVT and pessimistic multi-CN BVT.

  • Reused explicitly qualified author-reported same-head focused tests and race reconnect coverage.

  • Local isolation preflight and diff check passed. Six check receipts were reconciled with source fingerprints and retained logs; source remains unchanged.

Limitations:

  • Local Go tests did not run: required Go 1.27.1 downloads timed out during setup and recovery. Author test logs were not supplied.

  • Historical performance measurements were not repeated. Input materialization, retained metadata and the largest-table carry remain; production OOM and peak-memory behavior were not verified.

@mergify mergify Bot added the queued label Nov 12, 2026
@mergify
mergify Bot merged commit a192fdd into matrixorigin:main Nov 12, 2026
@mergify

mergify Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

✅ Merged into main as a192fdd at 08:53 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Thu 12 Nov, 08:53 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 08:53 · a192fdd · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot removed the queued label Nov 12, 2026
XuPeng-SH added a commit that referenced this pull request Nov 20, 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:

Related to #32963 and #32426. Backports the replay mechanism from #32611
to `4.2-dev`.

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

When a table straddles a batch boundary, CN catalog replay on `4.2-dev`
copies the entire column result into one batch while keeping the source
batches. On a catalog with about nine million column rows, CN startup
ran out of memory after entering this merge path.

Order replay rows by numeric account, database and table identity.
Insert complete groups from borrowed batch windows, copy only a table
that straddles a boundary, and release each source batch once consumed.
Close database and table SQL results at the end of their respective
phases. Keep cleanup bounded after replay cancellation and drop delayed
logtail closures after apply or reset so they stop retaining entries and
cache generations.

The SQL executor still materializes the result and the cache still
builds the existing engine and planner definitions. The carry can grow
to the width of one table. This PR targets the extra merge and parser
working set, plus stale callback references. The production catalog and
container peak have not been replayed locally.

Validation on Linux/amd64:
- Owning packages `pkg/catalog` and `pkg/vm/engine/disttae` passed under
`-race`. Focused replay and delayed-queue tests passed on the final
revision, including split tables, early cleanup, parser ownership,
retry, cancellation and partial allocation failure.
- Existing SQL integration test `TestDropDatabaseReconnectRollback`
passed under `-race` in a real embedded cluster.
- A 280,000-row synthetic batch probe observed about 28.25 MiB of
additional logically owned on-heap batch memory with the full merge
versus 56 KiB with table carry. Both modes processed all rows and
released their inputs. These are samples at consumer boundaries with a
small vector layout and a counting callback. They measure batch
ownership rather than process RSS, SQL sort/executor cost or retained
schema.
- Incremental gofmt, go vet and repository golangci-lint passed for the
changed package closure under Go 1.26.4.
mergify Bot pushed a commit that referenced this pull request Nov 21, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #32426

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

After #32611 removed the full column-batch merge, each live catalog version still retained both the engine attribute graph and the planner definition. This change retains a canonical planner definition, the original constraint bytes and the engine fields that cannot be reconstructed from the planner. Relations borrow the published planner for reads and build private definitions for consumers that require ownership. Old readers retain their catalog version across DDL. Failed ALTER restores the previous schema and version.

**Linux memory comparison.** The base was `e765c5fd44`. The measurements below used `b3139f9e09`, whose Git tree matches the original PR commit `3a3f034bdf`. With Go 1.27.4 on linux/amd64, each binary ran in three independent cgroup v2 services with a 16 GiB limit, swap disabled, the same CPU set, GOMAXPROCS=4 and GOMEMLIMIT=12GiB. Runs were interleaved. The deterministic fixture contained 630,124 tables and 4,410,868 columns (six varchar columns plus a hidden rowid per table). The harness prebuilt sorted input batches of up to 147,029 rows and invoked the production `consumeReplayColumns` and `CatalogCache.InsertColumns` paths across batch boundaries.

| Median of three runs | Base | Candidate | Change |
| --- | ---: | ---: | ---: |
| Live Go heap above process baseline after input release and GC | 3.586 GiB | 2.793 GiB | −22.13% |
| Cgroup peak through input preparation, replay, cleanup and GC | 6.138 GiB | 5.425 GiB | −11.62% |
| Cgroup peak including the subsequent engine/planner readback of every table | 6.138 GiB | 6.297 GiB | **+2.59%** |
| Whole-process maximum RSS including readback | 6.193 GiB | 6.354 GiB | +2.61% |
| Column batch application | 5,019 ms | 4,813 ms | −4.10% |

All six runs verified every table, planner and engine column metadata, zero remaining input-pool ownership and zero cgroup OOM events. The exhaustive readback builds private projections in the candidate and reads retained definitions in the base. A separate 40,000-table aligned control measured a 22.12% reduction in retained heap. First Relation open in a fresh transaction measured 1,801 → 1,856 ns/op (+3.05% median over three processes per revision, 1,000 opens per process), with nine allocations per open on both revisions.

**SQL and ownership validation.** Both service binaries restarted successfully from byte-identical copies of one persisted snapshot. Both exposed 2,049 user tables and 14,339 columns and produced identical sampled rows, composite key, secondary index and decimal default. Both read 18,096 catalog column rows during SQL restart. Linux single-process cache tests, focused replay ownership/cancellation and ALTER rollback tests passed on the candidate. Multi-CN replay and durable restart tests passed on both revisions. The previous same-tree Darwin validation also passed cache, disttae and pb/plan normal and race tests.

**Remaining QA coverage.** The scaled input is synthetic. The current and two earlier development records contained generated fixtures and heap profiles. The original QA data, workload and reconnect topology were unavailable for offline replay. The original 16 GiB incident remains open for verification. Costs for projecting many schemas concurrently and end-to-end logtail transport at incident scale remain unmeasured.


After synchronizing with `main` at `d2e71035db`, Linux validation at `6734419e13` passed the build, the pb/plan, disttae/cache and disttae unit tests, multi-CN replay and durable restart tests, and the license-header check for all 35 changed Go files.

At `e2d594e1ab`, catalog type reconstruction explicitly checks whether the planner ID fits the engine OID and whether that OID supports a default type. The original engine type remains available for unsupported types. Existing strict callers keep their panic contract. The Linux build, types/cache/disttae unit tests, multi-CN replay and durable restart tests passed. The pinned CI tools checked the six changed packages with molint and golangci-lint (zero issues), and license-eye accepted all 37 changed Go files.

## Review follow-up

Statistics refresh and ANALYZE now read the published planner schema under an existing catalog publication guard. Collection releases the guard before object I/O. Primary-key lookup reconstructs only the selected attributes and their private expression metadata. Empty collection skips allocation of per-column statistics buffers.

The catalog replay changes from #32964 release the delayed callbacks on reset or after ordered application, simplify the cross-batch carry path, and clean up the replay test pools. The ownership design records publication, borrowing, private copies, ALTER rollback, and reconstruction costs. [Catalog schema ownership design](https://github.com/matrixorigin/matrixone/blob/bd1fbb64e30c245fc358465a3ff4f90f7ddc69cd/docs/design/20261120-catalog-schema-ownership.md)

| Allocation per component call on 256 user columns | Before | After |
| --- | ---: | ---: |
| Stats catalog lookup and schema access | 197,376 B | 352 B |
| Single primary-key projection | 63,512 B | 216 B |

The same synthetic schema served as both controls. The new paths allocated the same number of bytes on 16 and 256 user columns. These measurements cover the two component reads.

Validation on Darwin/arm64 with Go 1.27.1 covered type, planner, and cache unit packages, configured incremental lint, and focused race tests for schema ownership, stats publication, ALTER rollback, replay failures, reconnect, multi-CN replay, and durable restart. The stats regression test compares borrowed and owned definitions on a persisted object with a sparse physical column sequence number. Relation-level tests cover zero, single, and hidden composite keys along with mutation isolation. The delayed-queue test fails both release assertions with the prior implementation and passes with this change.

Incremental license-eye accepted all 40 changed Go files. Independent design and review gates completed on GPT-6.2-sol/xhigh and GPT-6.1-terra/max, respectively.

## Table-status metadata follow-up

The table-status path uses the planner definition already obtained for relation admission. It reads the opened relation's schema version and scans its columns without rebuilding private engine definitions. The allocator lookup uses the same normalized name as CREATE. A view, a physical row ID, and a hidden synthetic primary key do not supply a user allocator. A visible column may use the fake primary-key name. The two tagged diagnostic files were removed. The normal candidate and ALTER-copy tests cover their ownership assertions. [Catalog schema ownership, revision 2](https://github.com/matrixorigin/matrixone/blob/daac1a097507af4aed26644c7347eae96b1ed2b5/docs/design/20261120-catalog-schema-ownership.md)

The MySQL-protocol control checked return values through the function, SHOW TABLE STATUS, and information_schema.tables for ordinary tables, views, lowercase and mixed-case auto-increment columns, and a visible column named __mo_fake_pk_col. Both the merge base and the reviewed head returned 0 for the mixed-case columns after two inserts. The fixed revision returns 3 across all three entry points.

| User columns | SQL median on merge base | SQL median on reviewed head | SQL median after fix | Built-in allocations on reviewed head → after fix |
| ---: | ---: | ---: | ---: | ---: |
| 6 | 5.65 ms | 17.37 ms | 5.62 ms | 6,616 → 864 B/op |
| 256 | 20.45 ms | 256.22 ms | 10.30 ms | 170,344 → 864 B/op |

The SQL runs each read 8,192 rows naming one ordinary table. Medians use four warm queries per width, in separate embedded-cluster processes on the same Darwin/arm64 host. The allocation control invokes the actual built-in with a catalog-built relation and fixed relation resolution. These local measurements cover metadata reads.

Focused race tests passed for allocator column selection, relation-name ownership, candidate defaults, ALTER-copy and rollback, and index access admission. The saved BVT's statements, output column names and row values matched via MySQL protocol. The two-CN allocator lifecycle and indexed and temporary-table status tests also passed. Incremental golangci-lint, molint, and all 40 changed Go license headers passed. The independent design and code review gates completed.

[Metadata performance finding](#32948 (comment)) · [Tagged probe finding](#32948 (comment))

## Remove intermediate schema projections

Catalog DROP and the deletion phase of ALTER use the existing planner columns to form catalog keys. ALTER still materializes the private schema it needs to recreate the catalog and restore the previous version on statement rollback. A published catalog item now holds its schema directly. At that revision, owned planner copies worked from the planner definition. Engine copies merge the ordered residual fields directly into the output attributes. This removes the intermediate prototype, dense scratch arrays, and the unused projection from catalog deletion. Column-only replay uses read-only attributes for equivalence and retains the existing validation. Constraint validation still runs before publication, and consumers of engine definitions still receive private decoded constraints.

On Go 1.27.1 Darwin/arm64, three interleaved runs compared the same published catalog items against `daac1a097507`. Fixtures had 6 or 256 user columns plus the physical row ID. The complex fixture also had primary-key and index constraints, a default expression, and a stored generated expression.

| Fixture | User columns | Projection | Median ns/op before → after | B/op before → after | Allocations/op before → after |
| --- | ---: | --- | ---: | ---: | ---: |
| plain | 6 | planner | 1,101.0 → 628.4 | 6,536 → 4,360 | 18 → 12 |
| plain | 6 | engine | 943.7 → 395.1 | 4,936 → 1,768 | 24 → 11 |
| plain | 256 | planner | 26,113.0 → 15,019.0 | 196,896 → 133,600 | 20 → 14 |
| plain | 256 | engine | 25,336.0 → 12,388.0 | 162,680 → 62,376 | 524 → 261 |
| constraint and expression | 6 | planner | 2,037.0 → 1,489.0 | 7,488 → 5,312 | 30 → 24 |
| constraint and expression | 6 | engine | 1,904.0 → 1,301.0 | 6,183 → 2,964 | 47 → 33 |
| constraint and expression | 256 | planner | 26,410.0 → 16,402.0 | 197,848 → 134,552 | 32 → 26 |
| constraint and expression | 256 | engine | 26,680.0 → 13,246.0 | 163,924 → 63,572 | 547 → 283 |

Focused race tests covered column-only replay, old-reader and ALTER rollback, invalid constraint rejection, decoded-wire isolation, and planner and attribute fidelity. MySQL-protocol regression checks passed for DROP failure and rollback, ALTER, and allocator lifecycle. Two-CN catalog replay, reconnect, and durable restart also passed. Configured incremental golangci-lint, molint, and the license header check passed. These measurements cover component projections. The final revision has no new incident-scale or end-to-end cgroup peak measurement.

Race validation also passed for the full cache package, for 100 repetitions each of concurrent read-only encoding and column-only replay with readers and GC, and for multi-CN replay, reconnect, and durable restart.

[Catalog schema ownership, revision 3](https://github.com/matrixorigin/matrixone/blob/e85380a54e9efeae9a1fef87cc0c3d1cfed914e5/docs/design/20261120-catalog-schema-ownership.md)

### CI follow-up for the arena timer

The PR was rebased onto official `main` at `96bfaa437bd9d535f22b6bd981ad00e277a4a91e`. It includes the upstream arena fixture and shared mmap timer fixes for the runtime fatal shown by `TestArenaPoolCountCap`. The six PR patches are unchanged according to `git range-diff`. [Failed Ubuntu UT](https://github.com/matrixorigin/matrixone/actions/runs/44715065474/job/136216667093) · [Upstream fix and incident](#32951)

Local validation on `1214f5a125e4070bfb95beb987ffaa71c46b6260` used Go 1.27.1 on Darwin/arm64 with `mo-cgo-test -race -tags matrixone_test -short`. The objectio and malloc packages passed, along with focused planner, catalog replay, schema ownership, and ALTER rollback tests. All 41 changed Go license headers and the Loom artifact check passed. The original Linux fatal did not reproduce in the local baseline tests. The rebased Linux CI result is pending.

## Catalog metadata reads for extrema and sequences

`MO_TABLE_COL_MIN/MAX` uses the published planner column positions for canonical DistTAE relations. `NEXTVAL` validates the relation kind from the published catalog metadata. Other relations retain their existing metadata validation. The unused private planner projection and its copy helpers were removed. The previous planner projection benchmarks describe the earlier revision.

The embedded MySQL-protocol tests covered 256-column empty and persisted tables, case-insensitive extrema and a missing column, 8,192 consecutive sequence values, and rejection of a non-sequence relation. Multi-CN catalog replay, reconnect, and durable restart passed. The local Linux/amd64 Go 1.27.1 checks passed across the seven affected Go packages with `-race`, and incremental static analysis passed.

| Metadata operation | Before | After |
| --- | ---: | ---: |
| 256-column extrema lookup | 59,648 B/op, 258 allocs/op | 0 B/op, 0 allocs/op |
| Six-column sequence kind validation | 2,508 B/op, 21 allocs/op | 0 B/op, 0 allocs/op |

The benchmark measures the metadata operations. [Catalog schema ownership at this revision](https://github.com/matrixorigin/matrixone/blob/3c399308ea9520ec9aba6b34b7637e33a33b12c5/docs/design/20261120-catalog-schema-ownership.md)


Approved-by: XuPeng-SH <[email protected]>
Approved-by: gouhongshen <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — a410355f Deployed Nov 12, 2026 by mergify[bot]
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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants