Skip to content

[Performance]: REPLACE INTO conflict detection falls back to loop join on large tables #27141

Closed

Description

@gouhongshen

Problem

REPLACE INTO ... VALUES becomes prohibitively slow when the target table has a primary key and an additional unique key.

The slowdown occurs in the first statement of the transaction, before the transaction workspace has accumulated mutations. CPU profiling and EXPLAIN VERBOSE point to the physical conflict-detection plan rather than transaction workspace growth.

Schema

All measurements use this exact table:

CREATE TABLE replace_record (
    id BIGINT PRIMARY KEY,
    external_key VARCHAR(80) NOT NULL UNIQUE,
    payload VARCHAR(120) NOT NULL,
    revision INT NOT NULL
);

The schema deliberately contains two independent uniqueness constraints:

  • clustered/base-table primary key: id
  • secondary unique key: external_key

This is required to reproduce the OR conflict predicate generated by REPLACE planning.

Data generation

Preloaded row n is deterministic:

id           = n
external_key = "key-<n>"
payload      = "initial"
revision     = 0

The preload contains a dense ID interval beginning at 1. Rows are inserted in batches; large preloads are expanded by INSERT ... SELECT doubling so setup time is not included in statement latency.

Transaction workload

One database connection and one explicit transaction are used. The transaction executes 12 statements sequentially; there is no client concurrency:

BEGIN;
REPLACE INTO replace_record (id, external_key, payload, revision)
VALUES (... 25,000 tuples ...);
-- repeated 12 times with disjoint ID ranges
COMMIT;

For statement s in [1, 12]:

first_id     = (s - 1) * 25,000 + 1
last_id      = s * 25,000
external_key = "key-<id>"
payload      = "replaced-<statement>-<id>"
revision     = 1

Therefore:

  • statements: 12
  • values per statement: 25,000
  • input rows per transaction: 300,000
  • SQL text per statement: approximately 1.2-1.5 MiB
  • input ID ranges are disjoint across statements

Original reproducer

  • preloaded rows: 20,000,000
  • all 300,000 input IDs already exist
  • all inputs conflict through both id and external_key
  • the first statement did not finish after more than 15 minutes

Reduced follow-up benchmark

To separate base-table conflict-scan cost from large-transaction workspace cost, the same workload is also run with:

  • preloaded rows: 10,000
  • statements: 12
  • values per statement: 25,000
  • input rows: 300,000
  • conflicting rows: 10,000 (IDs 1-10,000)
  • inserted rows: 290,000 (IDs 10,001-300,000)
  • expected final rows: 300,000

Only the initial base-table cardinality changes. Transaction shape, statement count and input cardinality remain unchanged.

Timing boundaries

The benchmark records these durations separately:

  • setup: schema creation and preload; excluded from transaction latency
  • per-statement latency: one synchronous tx.Exec(REPLACE...)
  • transaction execution: all 12 tx.Exec calls, excluding commit
  • commit latency: synchronous tx.Commit

It also records statement SQL size and min/median/max statement latency. Planning and execution are included in each statement latency.

Validation

After commit, the reduced benchmark executes:

SELECT
    count(*),
    sum(CASE WHEN revision = 1 THEN 1 ELSE 0 END),
    sum(CASE WHEN payload LIKE 'replaced-%' THEN 1 ELSE 0 END)
FROM replace_record;

Expected reduced-benchmark result:

count(*)                         = 300,000
sum(revision = 1)                = 300,000
sum(payload LIKE 'replaced-%')   = 300,000

This checks both conflict replacement and insertion of previously absent keys.

Reproduction command

Run against a fresh MatrixOne instance built from the target commit:

go run ./.bench/replace-into \
  -engine mo \
  -dsn 'dump:***@tcp(127.0.0.1:6002)/?interpolateParams=false&timeout=10s&readTimeout=30m&writeTimeout=30m' \
  -rows 10000 \
  -statements 12 \
  -values 25000

The runner drops and recreates only database txn_ws_replace_bench before each measurement.

Execution-plan evidence

Even a two-row REPLACE INTO is planned as a Multi Update containing a left join equivalent to:

VALUES
LEFT JOIN replace_record
  ON values.id = replace_record.id
  OR values.external_key = replace_record.external_key

On the original 20-million-row reproducer, EXPLAIN VERBOSE reports:

  • join type: LEFT
  • join condition: primary-key equality OR unique-key equality
  • right side: full scan of approximately 19,990,000 base-table rows
  • additional scans of the hidden unique-index table
  • no usable runtime filter for the OR join

Because the predicate contains OR across two unique constraints, it does not use the normal hash-join equality path and falls back to loopjoin.

CPU-profile evidence

A 30-second CPU profile captured while the first original statement was running showed:

  • hashbuild.Call/build -> loopjoin.Call -> loopjoin.container.probe: 25.86s cumulative, 58.39%
  • loopjoin.conditionMatchAt: 21.58s cumulative, 48.72%
  • boolean expression/vector evaluation: 20.85s cumulative
  • runtime.mallocgc: 13.41s cumulative, 30.28%
  • substantial GC work caused by repeated predicate evaluation and allocation

A profile from the reduced 10,000-row benchmark shows the same hot path: about 59% cumulative CPU in loopjoin, about 50% in conditionMatchAt, and about 31% in mallocgc.

Expected behavior

Conflict detection should scale with incoming rows and the relevant primary/unique-key lookup paths. It should not evaluate an OR predicate between incoming values and the complete base table.

The implementation must preserve REPLACE semantics when one incoming row conflicts with different existing rows through different unique constraints.

Scope clarification

This was found while benchmarking transaction workspace PR #27013, but the measured bottleneck is upstream of the workspace mutation path:

  • it appears in the first statement;
  • the workspace is still effectively empty;
  • the hot stack is planner-selected loopjoin, not workspace overlay/index code.

Related benchmark tracking: #26796.

Activity

  1. self-assigned this
    on Aug 14, 2026
  2. gouhongshen commented on Aug 14, 2026

    @gouhongshen
    ContributorAuthor

    Reduced 10,000-row base-table result

    Tested MatrixOne commit ae69b2b with the exact reduced protocol documented in this issue:

    • preloaded rows: 10,000
    • statements in one explicit transaction: 12
    • values per statement: 25,000
    • total input rows: 300,000
    • conflicting rows: 10,000
    • inserted rows: 290,000
    • validated final rows: 300,000

    The run completed successfully and produced the following statement latencies:

    Statement Input ID range Latency
    1 1-25,000 7.105 s
    2 25,001-50,000 17.447 s
    3 50,001-75,000 39.902 s
    4 75,001-100,000 63.385 s
    5 100,001-125,000 75.734 s
    6 125,001-150,000 93.380 s
    7 150,001-175,000 111.322 s
    8 175,001-200,000 140.797 s
    9 200,001-225,000 149.123 s
    10 225,001-250,000 166.379 s
    11 250,001-275,000 212.793 s
    12 275,001-300,000 239.294 s

    Summary:

    • transaction execution: 1,316.697 s (21m56.697s), excluding commit
    • commit: 756.609 ms
    • minimum statement: 7.105 s
    • median statement: 102.351 s
    • maximum statement: 239.294 s
    • statement 12 / statement 1 latency ratio: 33.68x
    • setup: 211.706 ms

    This confirms that the progressive slowdown is reproducible with only 10,000 preloaded base-table rows. As the same transaction accumulates disjoint 25,000-row REPLACE statements, latency increases from 7.1 seconds to 239.3 seconds even though the base table starts small.

    A CPU profile captured during this reduced run shows the same hot path already documented in the issue: approximately 59% cumulative CPU in loopjoin, approximately 50% in loopjoin.conditionMatchAt, and approximately 31% in runtime.mallocgc.

  3. added
    severity/s0
    ai-easy
    and removed on Sep 4, 2026
  4. gouhongshen commented on Sep 4, 2026

    @gouhongshen
    ContributorAuthor

    PR #28170 is trying to fix this issue.

  5. gouhongshen commented on Sep 5, 2026

    @gouhongshen
    ContributorAuthor

    PR #28170 has merged and is awaiting manual validation. The issue remains open.

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

Metadata

Metadata

Assignees

Labels

ai-easyseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions