Skip to content

[Performance]: Reduce catalog replay memory amplification from full column-batch merging and retained definitions #32426

Open

Description

@iamlinjunhong

Is there an existing issue for performance?

  • I have checked the existing issues.

Related: #23777 (tenant-aware catalog subscription), #31888 (a separate catalog-heavy DDL/OOM incident), and #32411 (ETL whole-file buffering/packet failures). This report tracks the locally reproduced catalog representation cost and replay all-batches merge amplification at the release below. It does not claim those incidents share one proven root cause.

Environment

  • Release: v4.2.8; exact tested source: 10d204b8763f19b2b37ba2147d1d4c1a7828d6d4.
  • Local reproduction: macOS / arm64, 16 GiB host RAM, Go 1.26.4. Native dependencies rebuilt from this revision.
  • Component processes: GOMAXPROCS=2, GOMEMLIMIT=1536MiB; 2.5 GiB polled RSS guard, 180-second Go test timeout. GOMEMLIMIT is a soft runtime target, not a hard RSS/cgroup bound.
  • Investigation originated from catalog-heavy heap profiles in a 16 GiB QA CN. This issue's quantitative experiment uses synthetic metadata only; no QA workload was generated.
  • Current main has not been runtime-tested for this report; no first-bad commit or release regression is asserted.

Details of Performance

A simple 40,000-table / 280,000-column catalog retains about 210 MiB of additional Go heap after input cleanup. With identical logical metadata, constructing one full column batch before conversion raises the observed heap peak from 490 MiB to 614 MiB. The fixture is reclaimable after releasing the cache root; this is not proof of a memory leak or reproduction of the production OOM.

Executed component comparison

The diagnostic calls the original CatalogCache.InsertTable, InsertColumns, Batch.Append and catalog GC. It does not copy their implementation. All tables are live, with seven varchar(64) columns each, short synthetic CREATE SQL, empty constraints/default expressions and no MVCC history.

  • Aligned control: 4,095 column rows/batch, keeping each seven-column table together; call InsertColumns per batch.
  • Merged: 4,096 rows/batch split tables; append all batches into the first, then call InsertColumns, matching the production fallback's merge mechanism.
  • Both retain original input batches through conversion, approximating deferred result cleanup. This is not an exact reproduction of the whole SQL executor/replay allocation topology.

Each row is one separate process. Units are MiB (2^20 bytes).

Tables / columns Mode Live heap increase after input cleanup + Go GC Observed total heap peak Observed RSS peak
10,000 / 70,000 aligned 52.41 143.44 182.03
10,000 / 70,000 merged 52.41 185.38 222.94
40,000 / 280,000 aligned 209.68 489.96 545.95
40,000 / 280,000 merged 209.68 613.87 667.92

The live increase subtracts the process baseline; peak columns are total process heap/RSS, not baseline-subtracted deltas. Heap maxima combine 10 ms sampling and explicit phase snapshots; RSS uses 20 ms polling. These are observations including harness overhead, not exact maxima or stable performance benchmarks.

Additional 40k results:

  • Go cumulative allocations between prepared column inputs and completed column insertion: 376.58 MiB aligned vs 863.79 MiB merged. Cumulative allocation is not simultaneously resident memory.
  • Logical ownership of input Go-heap backing increases from 124.51 MiB to 225.86 MiB after merging. After input cleanup, both mpool off-heap and on-heap ownership counters are zero. These counters overlap other memory views and must not be added to HeapAlloc/RSS.
  • Catalog GC scans 40,000 entries with TStaleItem=0; live catalog memory remains. Latest live schemas are still required, so this alone is not a GC defect.
  • Releasing the cache root and forcing Go GC returns HeapAlloc to the baseline vicinity (within 0.2 MiB). This demonstrates fixture reclaimability, not absence of other production retention paths.
  • inuse_space profiles are dominated by getTableDef and genTableDefOfColumn, matching the allocation paths seen during QA diagnosis. Profile attribution is sampled and identifies allocation origin, not an independently proven retaining root.

All four runs passed full per-table checks of planner/engine column names, types and widths; planner sequence numbers/name mapping; table/column counts; and three table lookups. Checks repeat after catalog GC. Complex schema/default/index compatibility is outside this fixture.

Executed public SQL path

A separate local all-in-one LOG/TN/CN instance at the same commit created 768 empty tables, each with a BIGINT primary key and six VARCHAR(64) fields. After graceful shutdown and restart from persisted data:

  • The application database still contains 768 tables.
  • SELECT COUNT(*) returns zero for three sampled tables: 0, 384 and 767.
  • Actual production replay logs report mo_databases [7][1], mo_tables [927][1], mo_columns [7800][1]. The final [1] is the batch count, not an extra row.
  • The post-restart profile includes replayCatalogCache -> getTableDef / genTableDefOfColumn.
  • Each catalog result had only one batch: this SQL experiment does not exercise the merge fallback. Both owned service processes exited normally; no OOM occurred.

Exact-version code evidence

Expected behavior / follow-up acceptance

  1. Reduce avoidable transient full-catalog copies during replay, while preserving complete per-table column grouping across arbitrary batch boundaries and correct input ownership on success/error/cancellation.
  2. Investigate reducing duplicated live engine/planner metadata, measuring actual retained bytes before selecting a design. Do not simply evict schemas still required by active transactions or tenants.
  3. Validate a candidate against identical logical schemas, including a table crossing multiple batches, complex defaults/constraints/indexes, MVCC/DDL and reconnect/replay behavior.
  4. Retain public SQL/restart coverage and compare memory at realistic catalog scale in an isolated Linux/cgroup environment before claiming an OOM fix.

Tenant-scoped catalog subscription is broader architectural work already tracked in #23777. This issue does not prescribe it as the only solution.

Reproduction

The exact executed component probe and supervisor are included below so reproduction does not depend on private profiles or local filesystem links. Create an isolated directory containing an exact-revision checkout named source. Save the Go file under source/pkg/vm/engine/disttae/cache/catalog_memory_probe_test.go; save the Python supervisor beside source as run_probe.py.

Build using that revision's supported native/toolchain prerequisites. The commands used on macOS were:

# From the isolated source checkout:
GOTOOLCHAIN=go1.26.4 make cgo
GOTOOLCHAIN=go1.26.4 GOMAXPROCS=2 GOMEMLIMIT=1536MiB \
  .agents/skills/mo-dev/scripts/mo-cgo-test -p=2 -c \
  -o ../catalog-probe.test ./pkg/vm/engine/disttae/cache
# From the parent directory containing source, the binary and run_probe.py:
mkdir -p tmp
python3 run_probe.py

Results are written to results/{10000,40000}-{aligned,merged}/, including phase MemStats, cleanup/oracle results, execution status and live-cache.pprof. The RSS supervisor uses macOS ps conventions; adapt platform/library setup if replaying on Linux. It polls rather than enforcing a hard OS memory cap.

Additional information / proof boundary

No product fix is included. The synthetic experiment does not reproduce approximately 430k production table objects, real schema complexity, final pre-kill memory growth, an ETL trigger, or a 16 GiB cgroup kill. Do not linearly extrapolate these local figures as measured production usage. A lower-memory aligned control is not itself an implemented optimization. This report does not establish an Astra or Matrixflow application bug.

The component code/results and small SQL replay were independently reviewed; there were no unresolved material blockers to the bounded conclusions above.

Exact diagnostic Go probe (307 lines)
package cache

// Local diagnostic only: invokes production cache APIs on synthetic metadata.
// Not a proposed product change or CI test.
import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"runtime/pprof"
	"strconv"
	"sync/atomic"
	"testing"
	"time"

	"github.com/matrixorigin/matrixone/pkg/catalog"
	"github.com/matrixorigin/matrixone/pkg/common/mpool"
	"github.com/matrixorigin/matrixone/pkg/container/batch"
	"github.com/matrixorigin/matrixone/pkg/container/types"
	"github.com/matrixorigin/matrixone/pkg/container/vector"
	"github.com/matrixorigin/matrixone/pkg/pb/timestamp"
	"github.com/matrixorigin/matrixone/pkg/vm/engine"
)

func probeMax(a *atomic.Uint64, v uint64) {
	for old := a.Load(); v > old; old = a.Load() {
		if a.CompareAndSwap(old, v) {
			return
		}
	}
}

func probeEnvInt(k string, fallback int) int {
	if v := os.Getenv(k); v != "" {
		n, e := strconv.Atoi(v)
		if e != nil {
			panic(e)
		}
		return n
	}
	return fallback
}
func probeCheck(e error) {
	if e != nil {
		panic(e)
	}
}
func probeZero(t types.Type) any {
	switch t.Oid {
	case types.T_Rowid:
		return types.Rowid{}
	case types.T_TS:
		return types.BuildTS(10, 0)
	case types.T_uint64:
		return uint64(0)
	case types.T_uint32:
		return uint32(0)
	case types.T_uint16:
		return uint16(0)
	case types.T_int32:
		return int32(0)
	case types.T_int8:
		return int8(0)
	case types.T_timestamp:
		return types.Timestamp(0)
	default:
		if t.IsVarlen() {
			return []byte{}
		}
		panic(fmt.Sprintf("unhandled type %v", t))
	}
}
func probeBatch(schema []types.Type, rows int, mp *mpool.MPool, value func(int, int) any) *batch.Batch {
	typs := append([]types.Type{types.New(types.T_Rowid, 0, 0), types.New(types.T_TS, 0, 0)}, schema...)
	b := batch.NewWithSize(len(typs))
	ok := false
	defer func() {
		if !ok {
			b.Clean(mp)
		}
	}()
	for j, typ := range typs {
		b.Vecs[j] = vector.NewVec(typ)
		for i := 0; i < rows; i++ {
			v := value(i, j-MO_OFF)
			if v == nil {
				v = probeZero(typ)
			}
			probeCheck(vector.AppendAny(b.Vecs[j], v, false, mp))
		}
	}
	b.SetRowCount(rows)
	ok = true
	return b
}
func probeTableBatch(start, n int, mp *mpool.MPool) *batch.Batch {
	return probeBatch(catalog.MoTablesTypes, n, mp, func(i, j int) any {
		id := start + i
		switch j {
		case catalog.MO_TABLES_REL_ID_IDX:
			return uint64(1000 + id)
		case catalog.MO_TABLES_REL_NAME_IDX:
			return []byte(fmt.Sprintf("table_%08d", id))
		case catalog.MO_TABLES_RELDATABASE_IDX:
			return []byte("probe_db")
		case catalog.MO_TABLES_RELDATABASE_ID_IDX:
			return uint64(100)
		case catalog.MO_TABLES_ACCOUNT_ID_IDX:
			return uint32(id/1000 + 1)
		case catalog.MO_TABLES_RELKIND_IDX:
			return []byte("r")
		case catalog.MO_TABLES_REL_CREATESQL_IDX:
			return []byte("CREATE TABLE synthetic_metadata_only (id BIGINT, value VARCHAR(64))")
		case catalog.MO_TABLES_CPKEY_IDX:
			return []byte(fmt.Sprintf("table_pk_%08d", id))
		}
		return nil
	})
}
func probeColumnBatch(start, n, cols int, mp *mpool.MPool) *batch.Batch {
	typ := types.New(types.T_varchar, 64, 0)
	encoded, e := types.Encode(&typ)
	probeCheck(e)
	return probeBatch(catalog.MoColumnsTypes, n, mp, func(i, j int) any {
		id, c := (start+i)/cols, (start+i)%cols
		switch j {
		case catalog.MO_COLUMNS_ACCOUNT_ID_IDX:
			return uint32(id/1000 + 1)
		case catalog.MO_COLUMNS_ATT_DATABASE_ID_IDX:
			return uint64(100)
		case catalog.MO_COLUMNS_ATT_DATABASE_IDX:
			return []byte("probe_db")
		case catalog.MO_COLUMNS_ATT_RELNAME_ID_IDX:
			return uint64(1000 + id)
		case catalog.MO_COLUMNS_ATT_RELNAME_IDX:
			return []byte(fmt.Sprintf("table_%08d", id))
		case catalog.MO_COLUMNS_ATTNAME_IDX:
			return []byte(fmt.Sprintf("column_%d", c))
		case catalog.MO_COLUMNS_ATTTYP_IDX:
			return encoded
		case catalog.MO_COLUMNS_ATTNUM_IDX:
			return int32(c + 1)
		case catalog.MO_COLUMNS_ATT_SEQNUM_IDX:
			return uint16(c)
		case catalog.MO_COLUMNS_ATT_CPKEY_IDX:
			return []byte(fmt.Sprintf("col_pk_%08d_%d", id, c))
		}
		return nil
	})
}
func probeVerify(t *testing.T, cc *CatalogCache, n, cols int) {
	t.Helper()
	if cc.tables.data.Len() != n || cc.tables.cpkeyIndex.Len() != n {
		t.Fatalf("table counts %d/%d want %d", cc.tables.data.Len(), cc.tables.cpkeyIndex.Len(), n)
	}
	total := 0
	cc.tables.data.Scan(func(item *TableItem) bool {
		if item.TableDef == nil || len(item.TableDef.Cols) != cols {
			t.Fatalf("wrong schema %s", item.Name)
		}

		for i, col := range item.TableDef.Cols {
			want := fmt.Sprintf("column_%d", i)
			if col.Name != want || col.Typ.Id != int32(types.T_varchar) || col.Typ.Width != 64 || col.Seqnum != uint32(i) || item.TableDef.Name2ColIndex[want] != int32(i) {
				t.Fatalf("planner column mismatch %s/%d", item.Name, i)
			}
		}
		attrCount := 0
		for _, def := range item.Defs {
			if attr, ok := def.(*engine.AttributeDef); ok {
				want := fmt.Sprintf("column_%d", attrCount)
				if attr.Attr.Name != want || attr.Attr.Type.Oid != types.T_varchar || attr.Attr.Type.Width != 64 {
					t.Fatalf("engine column mismatch %s/%d", item.Name, attrCount)
				}
				attrCount++
			}
		}
		if attrCount != cols || len(item.TableDef.Name2ColIndex) != cols {
			t.Fatalf("column representation count mismatch %s", item.Name)
		}
		total += len(item.TableDef.Cols)
		return true
	})
	if total != n*cols {
		t.Fatalf("column count %d", total)
	}
	for _, id := range []int{0, n / 2, n - 1} {
		q := &TableItem{Name: fmt.Sprintf("table_%08d", id), AccountId: uint32(id/1000 + 1), DatabaseId: 100, Ts: timestamp.Timestamp{PhysicalTime: 200}}
		if !cc.GetTable(q) || q.Id != uint64(1000+id) || len(q.TableDef.Cols) != cols {
			t.Fatalf("lookup %d failed", id)
		}
	}
}
func TestCatalogMemoryProbe(t *testing.T) {
	n, cols := probeEnvInt("PROBE_TABLES", 10000), 7
	mode := os.Getenv("PROBE_MODE")
	out := os.Getenv("PROBE_OUT")
	if n < 1 || n > 40000 || (mode != "merged" && mode != "aligned") || out == "" {
		t.Fatal("invalid diagnostic settings")
	}
	probeCheck(os.MkdirAll(out, 0700))
	mp := mpool.MustNewZero()
	cc := NewCatalog()
	cc.UpdateDuration(types.TS{}, types.MaxTs())
	var owned []*batch.Batch
	clean := func() {
		for _, b := range owned {
			b.Clean(mp)
		}
		owned = nil
	}
	defer clean()
	var peakHeap, peakMpool atomic.Uint64
	done, stopped := make(chan struct{}), make(chan struct{})
	defer func() { close(done); <-stopped }()
	go func() {
		defer close(stopped)
		ticker := time.NewTicker(10 * time.Millisecond)
		defer ticker.Stop()
		for {
			select {
			case <-done:
				return
			case <-ticker.C:
				var m runtime.MemStats
				runtime.ReadMemStats(&m)
				probeMax(&peakHeap, m.HeapAlloc)
				probeMax(&peakMpool, uint64(mp.CurrNB()))
			}
		}
	}()
	start := time.Now()
	measurements := []map[string]any{}
	mark := func(stage string, gc bool) {
		if gc {
			runtime.GC()
		}
		var m runtime.MemStats
		runtime.ReadMemStats(&m)
		measurements = append(measurements, map[string]any{"stage": stage, "heap_alloc": m.HeapAlloc, "heap_inuse": m.HeapInuse, "heap_sys": m.HeapSys, "total_alloc": m.TotalAlloc, "heap_objects": m.HeapObjects, "num_gc": m.NumGC, "mpool_bytes": mp.CurrNB(), "mpool_onheap_owned_bytes": mp.OnHeapCurrNB(), "elapsed_ms": time.Since(start).Milliseconds()})
	}
	mark("baseline", true)
	for first := 0; first < n; first += 1000 {
		b := probeTableBatch(first, min(1000, n-first), mp)
		owned = append(owned, b)
		cc.InsertTable(b)
	}
	mark("tables_inserted", true)
	chunk := 4096
	if mode == "aligned" {
		chunk = 4095
	}
	var columns []*batch.Batch
	for first := 0; first < n*cols; first += chunk {
		b := probeColumnBatch(first, min(chunk, n*cols-first), cols, mp)
		owned = append(owned, b)
		columns = append(columns, b)
	}
	mark("column_inputs_ready", true)
	if mode == "merged" {
		b := columns[0]
		for _, next := range columns[1:] {
			var e error
			b, e = b.Append(context.Background(), mp, next)
			probeCheck(e)
		}
		if b != columns[0] {
			t.Fatal("unexpected Append ownership")
		}
		mark("all_columns_merged", false)
		cc.InsertColumns(b)
	} else {
		for _, b := range columns {
			cc.InsertColumns(b)
		}
	}
	mark("columns_inserted_before_cleanup", false)
	probeVerify(t, cc, n, cols)
	clean()
	columns = nil
	if mp.CurrNB() != 0 || mp.OnHeapCurrNB() != 0 {
		t.Fatalf("input ownership not released: offheap=%d onheap=%d", mp.CurrNB(), mp.OnHeapCurrNB())
	}
	mark("inputs_released_live_cache", true)
	f, e := os.Create(filepath.Join(out, "live-cache.pprof"))
	probeCheck(e)
	e = pprof.WriteHeapProfile(f)
	closeErr := f.Close()
	probeCheck(e)
	probeCheck(closeErr)
	report := cc.GC(timestamp.Timestamp{PhysicalTime: 100})
	probeVerify(t, cc, n, cols)
	mark("after_catalog_gc", true)
	runtime.KeepAlive(cc)
	cc = nil
	mark("cache_released", true)
	for _, m := range measurements {
		probeMax(&peakHeap, m["heap_alloc"].(uint64))
	}
	result := map[string]any{"tables": n, "columns": n * cols, "mode": mode, "measurements": measurements, "peak_sampled_heap_alloc": peakHeap.Load(), "peak_sampled_mpool": peakMpool.Load(), "catalog_gc_report": report, "note": "component experiment; no SQL/reconnect/cgroup; simple synthetic definitions without index constraints, nonzero defaults or large SQL"}
	data, e := json.MarshalIndent(result, "", "  ")
	probeCheck(e)
	probeCheck(os.WriteFile(filepath.Join(out, "result.json"), data, 0600))
	t.Log(string(data))
}
Exact bounded Python supervisor
#!/usr/bin/env python3
import json, os, pathlib, signal, subprocess, sys, time
root=pathlib.Path(__file__).resolve().parent
cases=[(1000,'merged')] if '--smoke' in sys.argv else [(10000,'aligned'),(10000,'merged'),(40000,'aligned'),(40000,'merged')]
for tables, mode in cases:
    name=f'{tables}-{mode}'
    out=root/'results'/name
    out.mkdir(parents=True,exist_ok=True)
    env=os.environ.copy()
    env.update(GOMAXPROCS='2',GOMEMLIMIT='1536MiB',PROBE_TABLES=str(tables),PROBE_MODE=mode,PROBE_OUT=str(out),TMPDIR=str(root/'tmp'))
    max_rss=0; started=time.monotonic(); reason=None
    with (out/'run.log').open('w') as log:
        process=subprocess.Popen([str(root/'catalog-probe.test'),'-test.run=^TestCatalogMemoryProbe$','-test.v','-test.count=1','-test.timeout=180s'],cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT)
        try:
            while process.poll() is None:
                rss_out=subprocess.run(['ps','-o','rss=','-p',str(process.pid)],capture_output=True,text=True)
                if rss_out.stdout.strip():max_rss=max(max_rss,int(rss_out.stdout.strip())*1024)
                if max_rss>2684354560:reason='RSS guard >2.5GiB'
                if time.monotonic()-started>190:reason='supervisor timeout'
                if reason:process.terminate();break
                time.sleep(0.02)
            try:code=process.wait(timeout=5)
            except subprocess.TimeoutExpired:process.kill();code=process.wait()
        finally:
            if process.poll() is None:process.kill();process.wait()
    status=dict(tables=tables,mode=mode,exit_code=code,peak_rss_bytes=max_rss,elapsed_s=round(time.monotonic()-started,3),stop_reason=reason)
    (out/'execution.json').write_text(json.dumps(status,indent=2))
    print(json.dumps(status),flush=True)
    if code!=0 or not (out/"result.json").exists():sys.exit(1)

Activity

  1. self-assigned this
    on Nov 9, 2026
  2. iamlinjunhong commented on Nov 12, 2026

    @iamlinjunhong
    ContributorAuthor

    Additional QA evidence: Scenario CN OOM after reconnect/catalog replay

    A read-only investigation of the Shanghai IDC QA Scenario CN found the same catalog replay amplification path at the exact revision used by this issue, with profiles and container metrics immediately preceding an OOM-associated restart.

    • MO: v4.2.8-10d204b876-2026-11-06, commit 10d204b8763f19b2b37ba2147d1d4c1a7828d6d4.
    • Pod: moi-mo-2606-scenario-cn-twfbn; UID 8dc1e603-737f-4a34-b7c2-f75bb190baa8.
    • CN UUID: 33383162-3765-3234-6335-663036396539.
    • Main container memory limit: 16 GiB. Metrics below isolate the pre-restart container 0ddae9b5a7e507de92d3adcf23122984b00ccad877bc608d0a1dbb1cae5c68e8.

    November 12 timeline

    All timestamps below are UTC; add 8 hours for Beijing time.

    Time Evidence
    02:41:11.117 TN logtail send reports a TCP write timeout after 10.000293595s; message size 3746356 bytes. TN removes the failed session and releases 2994 remaining responses. This count is queue entries, not bytes or transactions.
    02:41:11.724 CN logs logtail.consumer.receive.one.logtail.failed, error rpc stream closed, then receives the reconnect signal.
    02:41:11.755 CN logs clean memory table finished. Replay subsequently reads 8,385 database rows, 630,124 table rows and 4,364,706 column rows. Counts are sums of logged batch row counts.
    02:42:02.459 FIND_TABLE merge mo_columns results: the 30 column result batches enter the merge fallback.
    02:43:45 Heap profile: 11.711 GiB, of which 10.903 GiB / 93.09% has replayCatalogCache allocation ancestry. Same-generation main-container RSS 14.711 GiB, usage 15.552 GiB, working set 15.433 GiB. These overlapping views must not be added.
    02:43:54.738549 connected to server. At this revision this log occurs after replayCatalogCache has returned successfully.
    02:44:03.653405 New process logs MO logger init; a new container generation appears.
    02:44:30 First query-grid observation of restart count 1 → 2, with latest termination reason OOMKilled. The reason metric is persistent; it is interpreted jointly with restart and container-generation changes, not counted as a new OOM at each sample.

    Pre-restart heap attribution

    Disjoint groups, calculated from self bytes classified by stack ancestry, rather than summing inclusive frames:

    Allocation path under replay GiB
    Internal SQL result-batch cloning 2.577
    Batch.Append merge 2.213
    Column parsing and table-definition construction 5.054
    Table-record parsing 0.996
    Other replay allocations 0.062
    All replay paths 10.903

    Unrounded bytes reconcile to the total; displayed rows are rounded. For this profile, the flamegraph root and self-byte sum equal the final heap-series point. Profiles identify allocation provenance, not a complete retaining-reference graph. The metrics query used a 15-second grid; underlying scrape samples can repeat. Old cgroup series remaining after restart were not added to the new container.

    This matches the exact-version replay implementation: separate deferred result cleanup, full column-batch merging, then column grouping and engine/planner definition construction. Result clones, merged batch backing, column structures and constructed definitions can coexist. Each deferred Result.Close captures its own result; this is delayed cleanup/peak amplification, not evidence that only the last result gets closed.

    November 11 corroborating event

    The same Pod logged rpc stream closed and reconnect at 02:59:06, then merge mo_columns results at 03:00:27, after reading 692,913 table rows / 4,877,721 column rows. A new process started at 03:02:23.912.

    The 03:01:45–03:02:00 heap time series rose from 10.228 to 11.112 GiB. Its aggregated flamegraph attributes 95.67% to replay. Unlike the November 12 profile, this graph's root is twice the final series value, so its aggregate bytes are not reported as instantaneous process heap.

    Conclusion and remaining boundaries

    High confidence: the amplification tracked by this issue was the principal observed memory-pressure driver preceding the Scenario OOM. This adds real QA incident evidence to the original component experiments; those experiments themselves still do not reproduce the production OOM.

    We have not established:

    • The exact allocation/kill instant: the last profile precedes new-process startup by about 18.7 seconds. Replay had already returned before the connected log, about 8.9 seconds before startup; do not conclude that the process was killed inside replay.
    • Why the initial TN write blocked: network, receiver progress/backpressure, GC, CPU scheduling and other causes remain unresolved.
    • A persistent catalog leak, a first-bad commit, or a particular MOI business SQL as the direct cause.

    No product code, deployment, data or monitoring configuration was changed.

  3. XuPeng-SH commented on Nov 12, 2026

    @XuPeng-SH
    Contributor

    QA 范围核对:#32611 已于 2026-11-12 08:53:57 UTC 合入 main,merge SHA a192fddbb312d7986f6da9b2d71fd60fb2033cb4。本次减少 replay 的全量列批次复制并提前释放已消费输入,覆盖本 issue 的瞬时 merge 放大部分;原验收第 2 项(重复的常驻 engine/planner 元数据)尚未完成,PR 也明确仍完整物化输入且不压缩活动元数据,因此此总项暂保留研发,不把局部优化当成完整转测或 OOM 修复。

    证据为 PR 作者在 head a410355fc8d8aadb61ed3d44bdd6cf059d3ad76f 报告的 Darwin/arm64 定向 replay、取消/错误清理及单/双 CN race 测试;历史 128-column 跨批次组件分配下降 54.1% 不是当前合并版本的进程峰值结论。原 QA OOM 评论针对旧版本 10d204b876,不能直接作为本次 main 修复后的反例。本轮仅远端核对,未运行本地测试。

    后续需明确常驻元数据优化的剩余开发范围,并以同逻辑 schema 核查跨批次/超宽表、复杂约束、MVCC/DDL、重连与取消所有权;Linux/cgroup 现实规模峰值及原 16 GiB OOM 场景尚未验证,不据此宣称验收通过,也不自动要求 backport。

  4. added
    ai-easy
    on Nov 12, 2026
  5. Ariznawlll commented on Nov 16, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 官方 main:7fcd9bdff8433d72983f0399fd5c10dcab91a00a;修复 PR Reduce transient catalog replay memory #32611 已 MERGED,merge commit a192fddbb312d7986f6da9b2d71fd60fb2033cb4 在该 main 的祖先链(Related to 本 issue,覆盖验收第 1 项的瞬时 merge 放大部分)。
    • 隔离部署:该 main 本地编译的 mo-service,1 LOG / 1 TN / 1 CN,SQL 端口 17101,全新数据目录;会话确认 git_version() = 7fcd9bdff8。
    • 测试日期:2026-11-16。

    已修复部分验证(验收第 1 项)

    1. 白盒:logtail_consumer.go 现调用 consumeReplayColumns 流式按表组消费并随用随释放输入批次;全量列批次 merge fallback 已移除(replay_columns.go)。
    2. 集成:301 张表(每表 7 列)写入后重启实例触发 catalog replay:旧版本必现的 merge mo_columns results fallback 日志 0 次出现,replay 后 301 张表全部可见、抽样行值完整、无 panic。
    3. 单测:pkg/vm/engine/disttae 全量单测通过(含 replay_columns_test 的分组/所有权/取消/部分分配失败/重试/delta 六类聚焦测试),聚焦 -race 通过。
    4. SQL 回归:已追加 matrixorigin/motr#350:issue_32426_catalog_many_tables(60 表目录的 mo_tables/mo_columns/information_schema 三方一致性与抽样断言,133 语句,record+diff×2+并行全绿)。

    未完成部分(保持 open 的理由)

    按本 issue 验收清单,第 2 项(重复的常驻 engine/planner 元数据,getTableDef/genTableDefOfColumn 的在位表示成本)尚无实现——#32611 明确"活动元数据未压缩"。第 3/4 项(Linux/cgroup 现实规模峰值、原 16 GiB OOM 场景)也未验证。与 2026-11-12 QA 结论一致:局部优化不作为完整转测或 OOM 修复。

    测试结论

    瞬时 merge 放大部分:测试通过;issue 整体保留待常驻元数据优化。

  6. Ariznawlll commented on Nov 16, 2026

    @Ariznawlll
    Collaborator

    转回研发继续处理。

    QA 验证结论(见上一条 comment):#32611 覆盖的瞬时 merge 放大部分已验证通过(301 表重启 replay 无 merge fallback、disttae 单测/race 全绿、SQL 回归已入 motr#350)。

    剩余待研发完成的本 issue 验收项:

    1. 第 2 项:重复的常驻 engine/planner 元数据(getTableDef/genTableDefOfColumn 双份表示,QA OOM 剖析中 5.05 GiB 的最大构成)——需先量化实际保留字节再选型设计;
    2. 第 3/4 项:Linux/cgroup 现实规模峰值对比与原 16 GiB OOM 场景复验。

    在常驻元数据优化合入前,本 issue 保持 open。

  7. Ariznawlll commented on Dec 1, 2026

    @Ariznawlll
    Collaborator

    结论

    未完成验收,保持开放。 最新 main 的常驻 schema 优化已合入,旧评论中“常驻元数据尚未实现”已不适用于本次版本。本轮补齐 Linux/cgroup 63 万表目录规模的三轮旧新对照:常驻 Go 堆中位数下降 22.31%,cgroup 峰值中位数下降 24.44%,逐表元数据断言通过。原 Scenario 16 GiB OOM 的完整运行环境仍未重现,不能把组件结果写成生产 OOM 已修复。

    关键证据

    版本和比较边界

    规模测试步骤

    1. 用真实 catalog tuple 构造 630,124 张表 / 4,410,868 列,每表 6 个 VARCHAR(64) 与隐藏 rowid。数量接近原现场,schema 为固定合成表,不冒充原 8,385 个数据库的全部业务 schema。
    2. 表记录进入真实 CatalogCache.InsertTable。列输入按 147,029 行分批,故意跨越每表 7 列边界,进入真实 consumeReplayColumns 和 InsertColumns。
    3. 回放后检查输入 on-heap/off-heap mpool 均归零;GC 后记录常驻 HeapAlloc 增量。再逐一读取全部表的 planner/engine 定义,检查列数、名字、类型 ID、engine 完整类型(含 VARCHAR 宽度)及隐藏列标志。
    4. 两版本各执行三个独立进程,记录完整进程 cgroup 峰值、failcnt、OOM 事件及退出码。基线只适配测试夹具调用签名和旧 TableDef/Defs 读取方式,没有修改产品实现。
    指标(bytes) 合并前父提交,第1/2/3轮 最新 main,第1/2/3轮
    GC 后常驻 Go 堆增量 3,728,817,800 / 3,728,817,792 / 3,728,819,048 2,897,102,392 / 2,897,103,232 / 2,897,102,944
    cgroup 全过程峰值 7,354,212,352 / 7,303,798,784 / 7,409,586,176 5,574,086,656 / 5,525,536,768 / 5,556,678,656
    failcnt / OOM kill / exit 全部 0 / 0 / 0 全部 0 / 0 / 0
    逐表元数据及输入池释放断言 全部通过 全部通过

    按三轮中位数,常驻堆下降 22.31%,cgroup 峰值下降 24.44%。cgroup 峰值不等同于 Go heap,不把这两类数值相加。

    父提交总耗时 46.237 / 44.959 / 44.559 秒;main 为 47.324 / 46.094 / 47.704 秒。本机有其他任务,且不是反序交错的专用吞吐基准,这些耗时不用于宣称吞吐提升或确定性能回退。本轮的可复核收益是相同规模/资源上限下的内存降低。

    故障、所有权和真实服务验证

    • cache 包:63 个根测试 ×3,189 次 race 执行通过,无跳过/失败。
    • replay 定向:9 个根测试 ×3,27 次 race 执行通过。覆盖取消、deadline、跨批次 carry、部分复制失败、插入失败后重试、重复列名冲突、借用 schema 的 DDL/rollback 及读者不可变性。
    • TestCatalogReplayMultiCN ×3:真实嵌入式两 CN/TN/LOG,验证不同 CN、DDL/默认值/rename/drop/recreate、租户隔离和快照/RR 边界;全部通过。
    • TestCatalogReplayReconnect ×3:真实 logtail 断连重连与 SQL 元数据/数据检查;全部通过。
    • TestDatabaseDefaultsDurableRestart ×3:停止并重新启动自有服务,确认持久化 catalog、复合 PK、二级索引、FK 拒绝路径、默认值及表达式行为;全部通过。
    • 上述嵌入式多 CN 是同一测试进程中的真实服务,不是三台物理服务器。
    • 另外在独立 mo-service 中创建 2,048 张简单表和1张复杂表。简单表共 14,336 个用户列,每表写一行;复杂表包含 DECIMAL 默认值、唯一键、二级索引和 ALTER 添加列。正常重启后,全部 2,048 行逐一核对,2,049 张表可见,复杂表 SHOW CREATE 与重启前一致,索引读回正确。这里是 2,049 表真实 SQL 重启测试,不能与上面的 630,124 表组件测试混称为 63 万表整实例重启。

    回归和证据位置

    已加入现有 MOTR main PR #404,提交 881d6ca259df051d169a1f3870803ba1b245ec10,没有向 matrixone 主库提测试 PR。

    • .github/qa/issue_32426_catalog_scale_test.go:可配置表数,真实 tuple/replay/cache 及逐表检查。
    • .github/workflows/qa-32426-30219.yml:PR/manual 精确 SHA;托管 CI 跑 40,000 表 / 280,000 列 ×3、所有权/race、双 CN、重连及持久化重启。63 万表 16 GiB 对照为本次独立大数据验收,不能用小 CI 替代。
    • 本次 CI 已成功完成,所有权/race、磁盘 EOF、4 万表、双 CN、重连及持久化重启步骤均通过。
    • 128 任务目录 /root/qa-32426-20261202 保存 scale-{1,2,3}.log、parent-scale-{1,2,3}.log、对应 cgroup 记录、cache/replay JSONL、integration/durable 日志和独立 MO 重启 JSON。

    待解决点

    原 Scenario 16 GiB 现场包含内部 SQL 结果批次、数据库目录、logtail 队列和业务负载的同时存活;本轮固定 schema 的组件输入没有覆盖这些完整叠加条件。仍需在匹配现场的完整 CN 重连/目录规模/并发负载下验收,;对应组件 CI 已通过。不能因为优化已实现或新组件峰值低于 16 GiB 就自动关闭原 OOM 问题。

    最终结论:未完成验收。 常驻元数据优化和本轮规模/错误路径/双 CN/重启检查通过;尚缺原 Scenario 16 GiB 完整场景,回归 CI 已通过,原场景未完成,保持开放。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

ai-easykind/performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions