Skip to content

[BUG] MOI IDC (QA) MO OOM #26465

Closed
Closed

Description

@gouhongshen

Information

  • Environment: QA
  • MOI namespace: moi-qa
  • MatrixOne namespace / cluster: mo-new-moi / moi-mo-2606
  • MOI release first correlated with the regression: 5.1.0-302a531e-20260729, deployed at 2026-07-30 05:39 CST
  • Relevant implementation commit included by that release: 85245b375 (fix(catalog): move external metadata discovery into core jobs (#14234))
  • MatrixOne image: v4.1.3-a185c23b3-2026-07-21
  • CN topology: 2 replicas, each limited to 36GiB; GOMEMLIMIT=35000MiB, GOGC=200, shared memory cache capacity 12GiB

Describe the bug

The Catalog metadata discovery job performs a full inventory and reconciliation of every active workspace on a fixed 5-second cadence.

The scheduler has a 1-second base tick, 8 workers and an in-flight guard. The guard prevents one pass from overlapping itself, but it does not avoid rescanning unchanged workspaces after the pass finishes. At QA scale, a full pass currently finishes in roughly 18 seconds, so all active workspaces and their databases are continuously rescanned approximately every 18 seconds.

This creates sustained SQL and memory pressure on MatrixOne. Both CNs repeatedly reach the 36GiB cgroup limit and are terminated with OOMKilled / exit code 137. The most affected CN recently survived only 16–25 minutes between OOM restarts.

This issue is scoped to the MOI metadata discovery workload and CN OOM. The independent QA Log Service problem is being investigated separately and is intentionally excluded.

Timeline and observed impact

  • 2026-07-30 05:39 CST: MOI release 302a531e deployed; it includes the new Catalog metadata discovery scheduler.
  • 05:44 CST: first CN OOM in the dense restart sequence.
  • Around 05:50 CST: aggregate SQL request rate increased to approximately 600–2000 requests/s per CN.
  • Previous comparable 12-hour period: approximately 130–165 requests/s per CN.
  • Hourly statement volume increased from approximately 0.8–1.6M/hour to 6.4–8.5M/hour.
  • The affected CN restart count increased from 16 to 25 during the day. Recent lifetimes were approximately 16 minutes and 25 minutes.
  • Immediately before the latest OOM, CN logged:
    • RSS: 34.49GiB
    • cgroup memory: 36GiB
    • memory pressure state: hard
    • workspace-accounted demand: 251.5GiB
    • cache eviction was attempted, but the process was subsequently OOM-killed.

Job behavior

Relevant implementation properties in moi-core/catalog/pkg/jobs at commit 85245b375:

  • MetadataDiscoveryJob.Interval() returns a fixed 5 * time.Second.
  • Scheduler baseTick = 1s.
  • Scheduler WorkerCount = 8.
  • Every pass lists all workspaces and enqueues every active workspace.
  • Each workspace opens a short-lived owner database connection.
  • Each workspace runs SHOW DATABASES.
  • Catalog assignments are fully listed with pagination.
  • Every discovered user database runs SyncMetadata, even when there is no known change.
  • SyncMetadata inventories all tables and reconciles Catalog metadata.

Schemas and tables involved

Catalog system database (moi_qa in QA)

Used to enumerate workspaces and resolve workspace owner/admin database credentials. Observed statements include access to:

  • workspaces
  • db_users
  • encrypted database credential / database instance records
  • moi_version and upgrade state tables from concurrent Catalog control-plane processing

Per-workspace MOI metadata database (moi)

Repeated reads and reconciliation touch:

  • catalog
  • catalog_database
  • catalog_table

MatrixOne metadata schemas in each workspace account

Repeated inventory queries touch:

  • information_schema.SCHEMATA
  • information_schema.TABLES
  • mo_catalog.mo_database

Exact deployed SQL and execution profile

The following is not reconstructed or simplified SQL. It is extracted from the exact QA-deployed MatrixFlow commit 302a531e (which contains implementation commit 85245b375). The source entry points are:

  • moi-core/catalog/pkg/jobs/metadata_discovery.go
  • moi-core/catalog/pkg/jobs/scheduler.go
  • moi-core/catalog/pkg/service/storage/system/impl.go
  • moi-core/catalog/pkg/service/storage/tenant/impl.go
  • moi-core/catalog/pkg/service/storage/tenant/system_resource_display.go
  • moi-core/catalog/pkg/service/database/metadata_executor.go
  • moi-core/catalog/pkg/service/database/service_impl.go

Catalog system-database SQL

Once per scheduler pass, Catalog enumerates every workspace:

SELECT id, name, description, owner_id, owner_revision, owner_changed_at, account_name, status, created_at, updated_at
FROM moi_qa.workspaces;

For every accepted active workspace, GetOwnerDBConnection runs these exact queries before opening the workspace owner connection:

SELECT id, name, description, owner_id, owner_revision, owner_changed_at, account_name, status, created_at, updated_at
FROM moi_qa.workspaces
WHERE id = ?;

SELECT id, user_id, workspace_id, db_username, is_admin, created_at, updated_at
FROM moi_qa.db_users
WHERE workspace_id = ?;

SELECT encrypted_db_password
FROM moi_qa.db_users
WHERE user_id = ? AND workspace_id = ?;

Per-workspace inventory SQL

A new short-lived owner *sql.DB is opened for every workspace and closed after that workspace completes. It first runs exactly:

SHOW DATABASES;

The code removes these names in memory and synchronizes every remaining database: information_schema, mysql, mo_catalog, system_metrics, system, mo_task, moi.

ListCatalogs, with page_size = 100 and offset decoded from the page token, runs in its own tenant transaction:

START TRANSACTION;

SELECT COUNT(*) FROM catalog;

SELECT catalog_id, catalog_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog
ORDER BY catalog_id ASC
LIMIT ? OFFSET ?;

COMMIT;

For each catalog returned above, ListDatabases, also with page_size = 100, runs in its own tenant transaction:

START TRANSACTION;

SELECT catalog_id, catalog_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog
WHERE catalog_id = ?;

SELECT COUNT(*)
FROM catalog_database
WHERE catalog_id = ?;

SELECT database_id, catalog_id, database_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog_database
WHERE catalog_id = ?
ORDER BY database_id ASC
LIMIT ? OFFSET ?;

COMMIT;

Both list paths also resolve display mappings. For N returned resources the source generates exactly one predicate per resource field (name and description), so N × 2 parenthesized predicates and N × 6 bound values are sent:

SELECT resource_type, resource_id, field, display_owner, display_key, default_text, created_at, updated_at
FROM system_resource_display_mapping
WHERE (resource_type = ? AND resource_id = ? AND field = ?)
   OR (resource_type = ? AND resource_id = ? AND field = ?);

The second predicate above is repeated by the source for every additional field after the first. This is a dynamically generated statement, not a fixed SQL literal; the exact statement length is therefore determined by the number of catalogs or databases returned in that page.

Per-database SyncMetadata SQL

Every non-system database from SHOW DATABASES starts a separate tenant transaction and runs the following stable-state path:

START TRANSACTION;

SELECT catalog_id, catalog_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog
WHERE catalog_id = ?;

SELECT COUNT(*)
FROM information_schema.SCHEMATA
WHERE SCHEMA_NAME = ?;

SELECT database_id, catalog_id, database_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog_database
WHERE database_name = ?;

SELECT dat_type
FROM mo_catalog.mo_database
WHERE datname = ?;

SELECT TABLE_NAME, TABLE_COMMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = ?
  AND TABLE_TYPE = 'BASE TABLE';

SELECT table_id, database_id, catalog_id, table_name, comment, extra,
       created_at, created_by, updated_at, updated_by
FROM catalog_table
WHERE database_id = ?
ORDER BY table_id ASC;

COMMIT;

For a subscription database, the information_schema.TABLES statement is replaced by the exact dynamically quoted statement:

SHOW TABLES FROM `<database_name_with_backticks_doubled>`;

When discovered metadata differs, the same transaction conditionally executes the following exact source statements:

INSERT INTO catalog_database (catalog_id, database_name, comment, created_by, updated_by)
VALUES (?, ?, ?, ?, ?);

SELECT database_id, catalog_id, database_name, comment, created_at, created_by, updated_at, updated_by
FROM catalog_database
WHERE database_id = ?;

UPDATE catalog_database
SET catalog_id = ?, database_name = ?, comment = ?, updated_by = ?, updated_at = CURRENT_TIMESTAMP
WHERE database_id = ?;

DELETE FROM catalog_table WHERE table_id = ?;
DELETE FROM catalog_table WHERE database_id = ?;
DELETE FROM catalog_database WHERE database_id = ?;

INSERT INTO catalog_table (database_id, catalog_id, table_name, comment, extra, created_by, updated_by)
VALUES (?, ?, ?, ?, ?, ?, ?);

Exact client/scheduling behavior required to reproduce the load

A plain SQL file is not an identical reproduction of this workload. The deployed code uses Go database/sql plus go-sql-driver/mysql with parameter placeholders. MatrixOne therefore observes parameterized statements as Prepare -> Execute -> Deallocate. Each list operation and each per-database SyncMetadata call has its own START TRANSACTION -> COMMIT pair.

The deployed scheduler behavior is:

  • fixed interval: 5s
  • scheduler tick: 1s
  • workers: 8
  • queue capacity: 1024
  • one complete pass enqueues every active workspace
  • overlap is prevented only while the previous pass still has queued/running units
  • if a pass takes longer than 5 seconds, the next 1-second scheduler tick after completion immediately starts another full pass
  • one short-lived owner database connection per workspace
  • one SHOW DATABASES per workspace
  • one SyncMetadata transaction per discovered non-system database

Therefore an identical replay must use the same client protocol behavior, transaction boundaries, 8-way concurrency, workspace/database cardinality and loop timing; replaying only the SQL strings with the MySQL CLI is not equivalent.

QA data scale and measured workload

A five-minute Catalog log sample showed:

Metric Value
Discovery passes enqueued 17
Workspace units enqueued 1,347
Workspace executions completed 1,212
Distinct successfully completed workspaces 73
Active workspace units per pass 79–80
Databases inventoried and synchronized 5,039
Average databases per completed workspace execution 4.16
Maximum databases in one workspace 27
Logged per-database sync failures 0

In the same five-minute window, all cloud_nonuser_sql traffic recorded by MatrixOne was:

Statement type Count
Select 87,309
Prepare 86,776
Deallocate 86,776
Start Transaction 14,373
Commit 14,370
Show Databases 1,796
Update 623
Insert 219
Show Tables 89

The Select statements read approximately 17.0M rows and scanned approximately 3.29GiB in five minutes. SHOW TABLES recorded an additional approximately 536K rows read and 105MiB scanned. These cloud_nonuser_sql totals include a small amount of other MOI control-plane traffic, but discovery is the dominant workload during the sample.

How to reproduce

  1. Deploy a MOI build containing commit 85245b375 with Catalog jobs enabled.
  2. Prepare approximately 80 active workspaces. QA currently has 79–80 eligible units per pass.
  3. Give each workspace one or more user databases; the QA average is 4.16 and maximum is 27.
  4. Start Catalog and observe catalog job units enqueued and metadata discovery workspace completed logs.
  5. Confirm that a new full pass begins shortly after the previous pass completes, because the fixed 5-second interval has already elapsed.
  6. Monitor:
    • mo_frontend_request_count
    • CN CPU and container_memory_working_set_bytes
    • kube_pod_container_status_restarts_total
    • CN MemoryThrottler-* logs
  7. Observe sustained high SQL rate, CN RSS approaching 36GiB, hard memory pressure and repeated OOMKilled restarts.

Expected behavior / acceptance criteria

  • Unchanged workspaces must not receive a complete database and table reconciliation every few seconds.
  • Discovery scheduling must scale with actual metadata changes rather than workspace_count × database_count × fixed cadence.
  • Concurrency and database work must remain bounded at QA scale.
  • The implementation must expose job duration, queue depth, workspace/database counts and failures as metrics.
  • With the current QA dataset, CN memory must stabilize below its cgroup limit and run for at least 30 minutes without OOM while normal QA traffic continues.
  • SQL request rate should return near the pre-regression baseline when there are no metadata changes.

Activity

  1. self-assigned this
    on Jul 30, 2026
  2. added
    kind/bug
    on Jul 30, 2026
  3. gouhongshen commented on Jul 31, 2026

    @gouhongshen
    ContributorAuthor

    进一步分析确认需要把问题拆成两个独立修复面:

    • MatrixOne 侧:pprof 中的主要内存放大来自 tombstone iterator 的按行堆分配。MO 侧本地优化与基准已经验证可将 10,000 个 tombstone 的 10,001 alloc / 1.92 MiB 降到 1 alloc / 32 B,耗时约从 342 μs 降到 128 μs。该优化能消除当前 profile 的主要分配放大、缓解 CN OOM;仍需合入并用 QA patched image 验证。
    • MOI 侧:负载源是 Catalog metadata discovery 的固定 5 秒全量 reconciliation。QA 每轮约 79 个 workspace、约 296 个 database;因为一轮耗时超过 5 秒,in-flight 结束后的下一次 scheduler tick 会立即再跑一轮,实际形成持续无空档扫描。即使 MO 内存热点修复,这种负载仍会持续浪费 SQL、事务、连接、CPU 和 I/O。

    MOI 跟踪 Issue 已重开:matrixorigin/matrixflow#14373。计划方向是保留 MOI DDL 的定向即时同步,将外部 DDL discovery 改为低频批量 inventory + diff、从上一轮完成后计时,并补齐外部 DROP 对账和调度指标。

    因此 #26465 继续跟踪 MO 的分配放大;matrixflow#14373 独立跟踪 MOI 的扫描算法和调度优化。

  4. added
    ai-heavy
    and removed on Jul 31, 2026
  5. gouhongshen commented on Aug 7, 2026

    @gouhongshen
    ContributorAuthor

    Additional QA finding: duplicated FK / ref-child metadata turns logically no-op ALTER ... CHANGE into a large allocation amplifier

    This is a separate amplification path observed in the same QA CN allocation profile. It is not evidence that the 5-second MOI discovery job created the corrupted schema metadata; the origin of the duplicate constraint writes has not yet been reduced to one external SQL sequence. It does show that, once this metadata is present, otherwise small external DDL can generate very large CN allocation volume.

    Observed trigger

    The following logically no-op statement was repeatedly issued against a user workspace database:

    ALTER TABLE departments
      CHANGE name name VARCHAR(100) NOT NULL COMMENT '部门名称';

    At the observation snapshot, name already had exactly that definition. Nevertheless, ALTER TABLE ... COPY is used by v4.1.3, so MatrixOne creates a replacement table, copies data, drops the old table, and renames the replacement. The replacement obtains a new physical table ID, which triggers foreign-key / ref-child metadata rewrites.

    CN logs recorded at least 30 departments -> departments_copy_* copy executions between 2026-08-07 02:29 and 03:34 UTC. Every corresponding base-table copy reported AffectedRows=0 (copy stage roughly 13ms--983ms); the related unique-index TABLE-CLONE records were also objCnt=0, blkCnt=0, rowCnt=0. This is not a large-row-data copy problem.

    Schema metadata at the observation snapshot

    The following counts were decoded from the current mo_catalog.mo_tables.constraint binary using the exact v4.1.3 engine.ConstraintDef.UnmarshalBinary wire format. They are the constraint representation consumed by the ALTER implementation, not inferred from table row data.

    table index definitions FK definitions ref-child table IDs constraint bytes
    recruitment.departments 768 0 349 133,622
    recruitment.users 732 349 480 180,356
    recruitment.candidates 3 702 0 146,242

    Important relationships:

    • All 349 current users foreign-key definitions have distinct names but point to the same current departments table ID.
    • departments carries 349 ref-child IDs. Only one (users) is current-visible in mo_catalog.mo_tables; the other 348 are historical/inactive IDs at the inspection snapshot.
    • candidates contains 702 FKs: 234 each to jobs, talent_pools, and users.

    For comparison, the intended normal shape is one FK edge users.department_id -> departments.id and one matching ref-child entry. The observed shape is hundreds of duplicated logical edges and historical child-table IDs.

    There is also a metadata discrepancy worth investigating: mo_catalog.mo_foreign_keys currently has no recruitment rows, while the active mo_tables.constraint blobs above contain these FK/ref-child definitions. The allocation conclusion below relies on the latter, because it is what the engine actually unmarshals and mutates.

    Why one no-op ALTER becomes hundreds of full constraint rewrites

    At a185c23b3:

    1. pkg/sql/plan/build_alter_table.go:buildAlterTableCopy selects AlterTable_COPY for CHANGE.
    2. pkg/sql/compile/alter.go:AlterTableCopy performs the base-table replacement.
    3. After the replacement, it iterates every ref-child ID without deduplication:
    for _, tblId := range qry.CopyTableDef.RefChildTbls {
        err = updateTableForeignKeyColId(
            c, qry.ChangeTblColIdMap, tblId,
            originRel.GetTableID(c.proc.Ctx),
            newRel.GetTableID(c.proc.Ctx),
        )
    }
    1. updateTableForeignKeyColId loads each child constraint and calls childRel.UpdateConstraint(...).
    2. UpdateConstraint does not patch the changed table ID in place. It serializes the full ConstraintDef, enters AlterTable, then rebuilds table metadata through txnDatabase.createWithID.

    The full constraint is serialized at least three times in this path:

    txnTable.UpdateConstraint        -> ConstraintDef.MarshalBinary
    txnTable.AlterTable              -> ConstraintDef.MarshalBinary
    txnDatabase.createWithID         -> ConstraintDef.MarshalBinary
    

    ConstraintDef.MarshalBinary starts with an empty bytes.Buffer and serializes every IndexDef / FK entry. bytes.growSlice, plan.Property.Marshal, and plan.IndexDef.Marshal are therefore direct allocation hot spots.

    Using the current users constraint size only as a scale reference, reserializing 180,356 bytes three times for 349 ref-child entries is already about 180MiB of raw encoded payload for one departments ALTER, before buffer growth/copies, metadata batch construction, index-table creation, and the reverse parent-table updates. The actual historical child versions may differ in size; this calculation is an order-of-magnitude illustration, not an attribution of an exact per-statement byte count.

    The reciprocal path is also multiplicative: when users is ALTERed, AlterTableCopy iterates every FK in qry.CopyTableDef.Fkeys and calls notifyParentTableFkTableIdChange, i.e. hundreds of parent UpdateConstraint operations. candidates has 702 such FKs.

    AddChildTblIdToParentTable in pkg/sql/compile/ddl.go currently appends tblId directly to oldRefChildDef.Tables without a uniqueness check. This does not prove it was the original source of all duplicates, but it means duplicated relationships are retained and can continue to amplify later ALTER COPY operations.

    Allocation evidence

    A QA CN alloc_space profile captured at 2026-08-07 10:36 CST is cumulative for that service process. It recorded 18.37TB total allocated space, with this ALTER-copy chain dominating:

    AlterTableCopy                                  16.78TB cumulative (87.09% of total)
      updateTableForeignKeyColId                    12.04TB
      notifyParentTableFkTableIdChange               3.29TB
      nested runSqlWithOptions (copy/create work)    1.43TB
    
    txnTable.UpdateConstraint                       16.41TB cumulative (85.20% of total)
    ConstraintDef.MarshalBinary                     15.99TB cumulative
    bytes.growSlice                                 11.95TB flat
    plan.Property.Marshal                            1.79TB flat
    plan.IndexDef.Marshal                            1.67TB flat
    

    The profile is process-lifetime cumulative, so it cannot attribute every byte to one departments statement. However, the live duplicated FK/ref-child graph, the exact copy-ALTER implementation, and the dominant call tree all align: the cost is driven by repeated full metadata reconstruction over an already duplicated dependency graph, not by the zero data rows in departments.

    Minimal reproducer shape / investigation direction

    The exact initial SQL sequence that produced the QA duplicate metadata is still unknown. A reduced reproducer should construct:

    1. a parent table;
    2. a child with many separately named FKs to that parent and duplicated/stale parent ref-child entries;
    3. a logically no-op COPY-path ALTER on the parent;
    4. an alloc_space profile around that ALTER.

    Expected observations are proportional UpdateConstraint calls for every stored FK/ref-child entry and dominant ConstraintDef.MarshalBinary / bytes.growSlice allocation.

    Potential fix directions to evaluate:

    • enforce uniqueness and validity of FK/ref-child edges when adding or restoring them;
    • remove historical/deleted child IDs from RefChildTbls rather than iterating them during every ALTER COPY;
    • avoid recreating a table's complete metadata/constraint blob once per FK edge when only a parent table ID changes;
    • add regression coverage for repeated CREATE/ALTER/DROP cycles involving FKs, asserting bounded FK and ref-child cardinality as well as bounded allocation.

    Relevant stored schema, with repetition made explicit

    The complete stored rel_createsql values are roughly 46 KiB (departments), 86 KiB (users), and 104 KiB (candidates) because they literally contain hundreds of repeated constraint clauses. Pasting those clauses verbatim would obscure the relationship, so the following is the relevant, normalized shape; x N means N separately named clauses in the stored DDL, not an inferred count.

    CREATE TABLE recruitment.departments (
      id                INT NOT NULL AUTO_INCREMENT,
      name              VARCHAR(100) NOT NULL COMMENT '部门名称',
      parentId          INT NULL,
      wecomDepartmentId INT NULL,
      ...,
      PRIMARY KEY (id),
      UNIQUE KEY wecomdepartmentid (wecomDepartmentId),
      UNIQUE KEY wecomdepartmentid_2 (wecomDepartmentId),
      ... -- 768 index definitions in the decoded constraint metadata
    );
    -- No FOREIGN KEY clause is stored on departments: it is the referenced parent.
    
    CREATE TABLE recruitment.users (
      id           INT NOT NULL AUTO_INCREMENT,
      departmentId INT NULL COMMENT '所属部门ID(关联 departments 表)',
      ...,
      PRIMARY KEY (id),
      KEY departmentid (departmentId),
      ... -- repeated UNIQUE KEY clauses on username and wecomUserId,
      CONSTRAINT <349 distinct UUID names>
        FOREIGN KEY (departmentId) REFERENCES departments(id)
        ON DELETE SET NULL ON UPDATE CASCADE
    );
    
    CREATE TABLE recruitment.candidates (
      id           INT NOT NULL AUTO_INCREMENT,
      jobId        INT NULL,
      talentPoolId INT NULL,
      createdBy    INT NULL,
      ...,
      CONSTRAINT <234 distinct UUID names>
        FOREIGN KEY (createdBy) REFERENCES users(id)
        ON DELETE CASCADE ON UPDATE CASCADE,
      CONSTRAINT <234 distinct UUID names>
        FOREIGN KEY (talentPoolId) REFERENCES talent_pools(id)
        ON DELETE SET NULL ON UPDATE CASCADE,
      CONSTRAINT <234 distinct UUID names>
        FOREIGN KEY (jobId) REFERENCES jobs(id)
        ON DELETE SET NULL ON UPDATE CASCADE
    );

    This was also checked directly against the user-visible stored CREATE SQL, rather than only against the binary constraint blob: departments.rel_createsql contains neither FOREIGN KEY nor REFERENCES; users.rel_createsql contains the repeated departmentId -> departments.id clauses; and candidates.rel_createsql contains the three repeated FK groups above. The RefChildTbls on departments is MatrixOne's inverse/internal parent-side record of child table IDs; it is not expected to appear as a FOREIGN KEY clause in the parent DDL.

    Observed DDL versus the still-unknown metadata origin

    The concrete external DDL observed repeatedly in QA is exactly:

    ALTER TABLE departments
      CHANGE name name VARCHAR(100) NOT NULL COMMENT '部门名称';

    It is a logical no-op, but v4.1.3 takes the COPY ALTER path. The observed departments_copy_<uuid> operations and INSERT INTO departments_copy_<uuid> ... SELECT ... FROM departments entries are MatrixOne's internal replacement/copy work resulting from that ALTER; the latter is DML, not another user-issued DDL. In the inspected interval, 30 such copy executions had zero copied base-table rows.

    We have not yet recovered the historical client/ORM DDL sequence that inserted the 349/702 separately named duplicate FK clauses and repeated unique keys. The no-op CHANGE statement is therefore established as the allocation trigger on already-expanded metadata, not claimed as the original creator of that metadata. Any root-cause fix for the initial duplication needs a reduced CREATE/ALTER/DROP reproducer or historical client SQL in addition to the engine-side safeguards discussed above.

  6. gouhongshen commented on Aug 7, 2026

    @gouhongshen
    ContributorAuthor

    Separate MemoryCache accounting / capacity-limit finding: logical bytes are not mmap backing bytes

    This is another independent memory-risk path in the same QA OOM investigation. It does not prove that MemoryCache alone caused every CN OOM, but it establishes that the configured MemoryCache capacity and its current gauges are not a hard bound on off-heap mapped memory or RSS.

    QA observation

    Before the capacity mitigation, QA CNs had a shared MemoryCache capacity of 12GiB. At a pre-OOM observation snapshot:

    memory-cache-inuse        = 10.22GiB
    SHARED-mem cache inuse    = 10.22GiB
    

    The cache capacity was later reduced to 6GiB as a risk reduction. That reduces the logical cache budget, but it does not change the accounting mismatch described below into a physical 6GiB RSS cap.

    Exact deployed accounting path (v4.1.3-a185c23b3)

    pkg/fileservice/malloc.go builds memoryCacheAllocator from malloc.GetDefault(nil) and wraps it in malloc.NewMetricsAllocator. The QA CN FileService configurations inspected here contain no malloc allocator override, so pkg/common/malloc/default.go selects the mmap allocator.

    For the guarded allocation path (used when DiskCache promotes data into MemoryCache), a requested cache buffer follows this path:

    requested N bytes
      -> cacheCapacityGuardedAllocator.EnsureNBytes(N)
      -> MetricsAllocator.Allocate(N)
      -> ClassAllocator: choose next power-of-two class C
      -> fixedSizeMmapAllocator: unix.Mmap(..., C, ...)
      -> return slice[:N] to Bytes / MemoryCache
    

    For a non-power-of-two N, C = 2^ceil(log2(N)), so N < C < 2N. For example, a 700KiB request maps a 1MiB class but exposes a slice of length 700KiB.

    However, every relevant cache accounting path charges N, not C:

    • In that guarded DiskCache-to-MemoryCache path, cacheCapacityGuardedAllocator calls EnsureNBytes(..., N) before allocation.
    • fifocache.DataCache.Set passes len(value.Bytes()) to FIFO. That value drives used, admission, eviction, the configured capacity guard, and the SHARED-mem cache inuse callback metric.
    • MetricsAllocator.Allocate adds/subtracts its input size (N) for memory-cache-inuse and OffHeapInuseGauge; it does not inspect the actual backing allocation.
    • Bytes.Size() and Bytes.Bytes() report the visible slice length. Bytes.Slice(length) can reduce that length without reallocating or shrinking the mmap backing object.

    Therefore none of these gauges exposes the class-rounded mmap capacity. For entries whose current visible length is their original request, 10.22GiB logical usage admits a live backing-allocation range of [10.22GiB, 20.44GiB), before cache metadata and transient work. Because Bytes.Slice can reduce visible length while retaining its backing allocation, the code does not provide a global bound derivable from a point-in-time logical gauge alone.

    RSS is not identical to mmap capacity: it depends on which pages have been faulted/touched, and retained/free allocator buffers have different residency behavior. Consequently, the 20.44GiB figure is a mathematical backing-capacity upper bound for the unsliced case, not a claim that QA actually had 20.44GiB of resident cache pages.

    Why this matters operationally

    The current setting means operators may read memory-cache-inuse <= 6GiB (or 12GiB) as “MemoryCache is bounded by 6GiB/12GiB.” That is false for off-heap memory. It makes RSS headroom calculations and OOM protection systematically optimistic, particularly for workloads with many requests just above a power-of-two boundary.

    This can coexist with the other allocation amplifiers in this issue: lowering the logical cache budget reduces one contributor, but it does not account for or constrain the FK/ALTER allocations, Go heap, other off-heap allocators, or temporary buffers.

    Proposed direction

    1. Preserve two explicit notions of size for cache data: logical payload length and allocator-backed capacity.
    2. Use backed capacity for MemoryCache admission, eviction, capacity gauges, memory-cache-inuse, and off-heap accounting; retain a separate logical-payload metric if it is useful.
    3. Make the allocation interface expose the actual capacity deterministically. For the current class allocator this is the selected class size; after allocation it is also observable as the returned slice capacity. Do not infer it from the visible slice length.
    4. Cover both normal and sliced entries. A regression test should show that two 700KiB values cannot be admitted under a capacity that only fits their logical sum but not their two 1MiB backing mappings, and that the reported physical metric remains correct after Bytes.Slice.
    5. Expose a metric or malloc-profile counter for mapped/current class bytes so QA can compare it directly with cgroup RSS rather than estimating it from logical cache usage.

    The current main branch contains malloc.ClassAllocationSize, but it is not used by the MemoryCache capacity/metric path above; in particular it does not change the deployed a185c23b3 behavior.

  7. changed the title [-][Bug]: 5-second metadata discovery full scan overloads QA MatrixOne and causes CN OOM[/-] [+][BUG] MOI IDC (QA) MO OOM[/+] on Aug 7, 2026
  8. gouhongshen commented on Aug 7, 2026

    @gouhongshen
    ContributorAuthor

    Implemented this in draft PR #26783.

    The cache now admits and reports inuse by actual retained backing capacity, rather than logical payload length. It also adds separate cache metrics:

    • type="logical": logical cached payload
    • type="backing-overhead": retained backing capacity minus logical payload

    For example, 6 GiB retained backing with 4 GiB payload will report 2 GiB backing overhead. This includes allocator size-class rounding and spare slice capacity, but deliberately excludes allocator free pools, page-level fragmentation, and process RSS. The FileService cache dashboard displays the three memory-cache series together.

    Validation includes focused FileService tests, race tests for set/evict/replacement accounting, allocator tests, and native-backed ObjectIO cache-data tests.

  9. gouhongshen commented on Sep 4, 2026

    @gouhongshen
    ContributorAuthor

    Automated AI triage

    This issue requires human involvement and cannot currently be completed independently by the
    automated fix loop.

    Reason

    MOI/QA owners must validate a known patched deployment under the real discovery workload and supply a reduced current MatrixOne reproduction/profile for any residual. The MOI scheduler cannot be changed by this handler.

    Evidence

    QA CN OOMKilled/137 is evidenced. The discovery scheduler belongs to MOI, and comments identify several independent allocation contributors. Current MatrixOne history already contains tombstone optimizations #26470/#26476 and backing-capacity accounting #26783; a remaining current code defect is not isolated.

    Please use this analysis to provide the missing decision, environment, evidence, or ownership
    needed before the issue is returned to the AI candidate pool.

  10. gouhongshen commented on Oct 15, 2026

    @gouhongshen
    ContributorAuthor

    Existing-fix audit

    Assessment: partially fixed

    Fixed evidence

    Verified on main 8795f36: #26470 / 217b9e1 removes per-tombstone allocations, covered by TestReusableObjectStatsIterAllocations; #26476 / 3f2b8fc indexes tombstone ranges, covered by TestTombstoneObjectIndexMatchesExhaustiveScan; #26783 / 0676200 accounts cache backing capacity, covered by TestBytesSliceKeepsBackingCapacity and TestMemCacheSeparatesPhysicalAndLogicalBytesMetrics; #26790 / 6481927 removes redundant ALTER/FK rewrites, covered by TestReconcileAlterCopyForeignKeyReferencesOncePerRelation and test/distributed/cases/foreign_key/issue_26465.sql.

    Remaining problems

    1. QA CN OOM closure: QA owners must identify a deployment containing the fixes and verify the reported workload for at least 30 minutes, supplying memory profiles and restart evidence for any residual failure.
    2. Continuous full metadata reconciliation: MatrixFlow owners must resolve or confirm resolution of matrixorigin/matrixflow#14373; its scheduler implementation is excluded from this MatrixOne handler.
    3. Historical duplicated FK/index metadata: its creation sequence remains unidentified. QA/client owners must supply historical DDL or a reduced current reproducer before attributing a separate duplication defect to MatrixOne.
  11. gouhongshen commented on Oct 15, 2026

    @gouhongshen
    ContributorAuthor

    Split follow-up for the un-fixed portion: #30293.

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

Metadata

Metadata

Assignees

Labels

ai-heavykind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions