Skip to content

[Bug]: HashBuild can bypass spill and trigger system OOM during large hash table growth #25782

Description

@aptend

Description

A long-running INSERT ... SELECT with several grouped subqueries and LEFT JOINs caused the CN process to be killed by the node OOM killer. The failing query's pipeline mpool retained 23.78 GB; immediately before the kill, hash-table-like allocations increased it by another 7.52 GB in about 1 ms. HashBuild did not enter spill mode.

This is not only a sizing/tuning problem. The current spill decision excludes broadcast hash builds, and eligible shuffle hash builds check retained input-batch memory before BuildHashmap, with no admission check during hash table growth.

Incident context

All times below are UTC on 2026-07-15.

Field Value
Environment cn-dev, Kubernetes namespace freetier-01
Pod freetier-01-s16c64g-854877c9c-cn-bnxq8
Pod UID 0338817b-437f-4681-b339-6dff5aed6c64
Node cn-hangzhou.10.3.93.228
Image matrixone:v4.1.0-c58a0e62c-2026-07-11
MO commit c58a0e62c
Session/pipeline 019f6571-fccd-7735-ac92-4f15a51967de
Statement 019f6571-fd12-7263-ac05-61e875ec0c01
Transaction 4f352d3cf2ca125118c1424e75ff854a
Transaction created 11:03:17.010486
Statement build completed 11:03:21.854903 (Exec.Build took 4.844 s)
Process killed 11:32:19
Replacement process started 11:32:22

The statement shape was:

INSERT INTO <target>.voucher_line_details__stg
SELECT ...
FROM ...
LEFT JOIN (... GROUP BY ...) ...
LEFT JOIN (... GROUP BY ...) ...
...
GROUP BY ...;

The account name, user name, client address, and business columns are omitted from this public issue. The IDs above are sufficient to locate the complete statement and trace in the dev observability data.

Failure evidence

The current pod status preserves the previous container termination:

lastState.terminated.reason     = OOMKilled
lastState.terminated.exitCode   = 137
lastState.terminated.finishedAt = 2026-07-15T11:32:19Z
state.running.startedAt         = 2026-07-15T11:32:22Z
restartCount                    = 2

The Kubernetes event reported a node-level OOM and selected mo-service as the victim:

SystemOOM encountered, victim process: mo-service

This was not a normal query error or a Go runtime OOM: the process stopped without a statement completion/error log and the container was restarted after exit 137.

Memory state at the scene

Historical Prometheus data for the old container, queried for 11:20:00-11:33:00:

Signal Observation
Node MemTotal 61.54 GiB
Node MemAvailable 2.63 GiB at 11:20; recovered to 45.19 GiB after restart
Container resource limit metric 85 GiB from 11:20:10 through the OOM
Container RSS 42.87 GiB at 11:20; last/max sample 44.17 GiB at 11:30:45
Container working set last/max sample 44.43 GiB at 11:30:45
Container usage max sample 44.74 GiB at 11:29:00

The configured container limit exceeded the node's physical memory, so it could not protect the node. The current pod spec later shows 21 GiB; that is post-incident state and must not be used as the limit at the time of failure.

At 11:30:40.066771, the failing pipeline reported:

MPool pipeline-019f6571-fccd-7735-ac92-4f15a51967de new high watermark
allocations     : 163571
frees           : 131264
alloc bytes     : 24656403965
free bytes      : 8394263181
current bytes   : 16262140784
high water mark : 16262140784

By 11:30:40.067843, about 1.07 ms later:

allocations     : 163599
frees           : 131264
alloc bytes     : 32172596733
free bytes      : 8394263181
current bytes   : 23778333552
high water mark : 23778333552

Delta:

allocations:  +28
frees:          0
bytes:        +7,516,192,768
average:       268,435,456 bytes/allocation (exactly 256 MiB)

The global mpool moved in lockstep from 17,323,812,368 to 24,840,005,136 bytes. This strongly correlates the final memory step with one pipeline rather than gradual accumulation across unrelated sessions. The repeated 256 MiB allocation size is consistent with hash table block growth; this attribution is an inference from allocation shape plus the execution/code path, not a symbolized allocation stack.

Earlier pipeline high-watermarks show sustained growth before the final step:

11:03:25   1.07 GB
11:03:31   5.42 GB
11:06:09   7.66 GB
11:12:03  10.86 GB
11:18:35  15.17 GB
11:30:40  16.26 GB -> 23.78 GB in ~1 ms
11:32:19  process killed

The transaction leak detector began reporting this transaction at 11:18:46 and continued until the process died. Those messages establish that the same transaction remained active; they do not by themselves prove a transaction leak.

Spill evidence

A Loki search on the affected pod for entering spill mode over 10:50:00-11:35:00 returned no matching line for this execution. HashBuild emits that exact log when shouldSpillBatches() succeeds, so the observed execution did not enter that spill path.

Relevant code paths at c58a0e62c

Broadcast hash builds cannot spill

pkg/sql/colexec/hashbuild/spill.go#L273-L285:

func (hashBuild *HashBuild) shouldSpillBatches() bool {
    if !hashBuild.CanSpill || !hashBuild.IsShuffle || !hashBuild.NeedHashMap {
        return false
    }
    // ...
}

constructBroadcastHashBuild sets both IsShuffle = false and CanSpill = true. The IsShuffle condition therefore makes spilling unreachable for a broadcast hash join even when runtime cardinality is much larger than planned.

Spill is checked before hash map construction

pkg/sql/colexec/hashbuild/build.go#L181-L216 copies each input batch and checks spill based on retained batch memory. If that check never fires, BuildHashmap runs afterward.

There is no spill/budget decision while the hash map is being built. Int64HashMap.ResizeOnDemand and StringHashMap.ResizeOnDemand return allocation errors, but do not receive a query/hash-build budget or a way to return NeedSpill before committing the next large growth step.

Existing limits do not provide a reliable fallback

  • join_spill_mem = 0 selects an automatic threshold; it does not disable spill, but the threshold cannot help on the excluded/runtime-growth paths above.
  • The session mpool uses GuestMmuLimitation, whose default is 1 TiB.
  • The global mpool limit also defaults to 1 TiB when [limit].memory is not configured.
  • ProcessLimitationSize is assigned to the process but is not enforced on this allocation path.
  • In this incident, the Kubernetes resource-limit metric (85 GiB) was itself larger than node physical memory (61.54 GiB).

Expected behavior

A hash build must not cause node-level OOM because planner estimates were low or hash table overhead grew after the batch-memory spill check.

Before the next hash table growth exceeds the query/hash-build budget, execution should spill, repartition, fall back from broadcast to a partitioned strategy, or return a controlled query error.

Proposed direction

  1. Introduce an enforceable per-query/hash-build memory budget.
  2. Estimate projected hash table memory before BuildHashmap and enter spill mode when it exceeds the budget.
  3. Add admission control to hash table ResizeOnDemand before allocating additional blocks.
  4. Return a typed NeedSpill result when growth cannot be admitted, allowing HashBuild to partition and retry.
  5. Support runtime fallback for broadcast hash joins, or reject broadcast plans whose build side cannot be bounded safely.
  6. Derive automatic budgets from min(cgroup limit, node allocatable memory) with reserve for Go heap, cache, other operators, and other containers.
  7. Independently prevent workload/container limits from exceeding usable node memory.

Acceptance criteria

  • A high-cardinality build side with underestimated statistics does not cause process/node OOM.
  • Broadcast hash build either spills/falls back or terminates the query with a controlled error.
  • Shuffle hash build can spill based on projected hash table size, not only retained input batch size.
  • Hash table expansion cannot exceed its query budget by more than one bounded allocation block.
  • Tests cover both broadcast and shuffle joins with a deliberately small memory budget.
  • Metrics/logs identify the join operator, query/statement ID, threshold, projected hash size, spill reason, and spilled bytes.

Activity

  1. added
    kind/bug
    on Jul 16, 2026
  2. self-assigned this
    on Jul 16, 2026
  3. aptend commented on Jul 16, 2026

    @aptend
    ContributorAuthor

    Follow-up: optimizer plan-selection findings

    I inspected the current Broadcast/Shuffle selection logic and the controlled reproduction artifacts. There are two important conclusions and one evidence boundary.

    1. The 132,096-row harness does not prove that the original incident should have selected Shuffle

    The harness intentionally patches planner statistics while keeping the physical data and SQL unchanged:

    • physical data: 132,096 rows on each side;
    • Broadcast phase estimate: build = 1,024, probe = 40,000,000;
    • Shuffle positive-control estimate: build = 6,000,000, probe = 40,000,000.

    Therefore, the harness proves that the same HashBuild execution can bypass spill in Broadcast mode while the Shuffle path spills successfully. It does not establish that 132,096 physical rows alone should cross the optimizer's Broadcast-to-Shuffle boundary.

    The original incident's actual build rows, estimated build rows, NDV, row width, and PHYPLAN were not preserved in the public evidence. The 23.78 GB pipeline mpool value is memory, not row cardinality.

    2. The original incident still strongly indicates that at least one Broadcast build was unsuitable

    The production statement contained several LEFT JOIN (... GROUP BY ...) subqueries. During execution, the pipeline reached about 16.26 GB and then allocated another 7.52 GB as 28 exact 256 MiB blocks in roughly 1 ms, reaching 23.78 GB. This allocation shape is strongly correlated with hash-table block growth, although it is not a symbolized allocation stack.

    A build side that produces a multi-GB hash table is no longer an appropriate per-CN Broadcast small side. At least that join should have used a partitioned/shuffle strategy, or execution should have fallen back/spilled/failed under a controlled budget.

    This does not mean every join in the statement should be shuffled. Small dimension joins may still be valid Broadcast joins.

    3. A GROUP BY child can currently hard-disable Shuffle on its parent join

    The current optimizer contains this gate in determineShuffleForJoin:

    // for now, if join children is merge group or filter, do not allow shuffle
    if dontShuffle(builder.qry.Nodes[node.Children[0]], builder) ||
       dontShuffle(builder.qry.Nodes[node.Children[1]], builder) {
        return
    }

    dontShuffle returns true when the child is a non-shuffle AGG, or a FILTER over a non-shuffle AGG:

    • pkg/sql/plan/shuffle.go:521-523
    • pkg/sql/plan/shuffle.go:629-639

    This matches the incident statement shape. A plausible plan-selection chain is:

    1. a grouped subquery is not selected for shuffle, possibly due to cardinality/NDV/type thresholds;
    2. the parent LEFT JOIN sees a non-shuffle AGG child;
    3. the parent join is then prevented from selecting Shuffle regardless of its eventual runtime build size;
    4. it executes as Broadcast;
    5. Broadcast HashBuild cannot enter the existing spill path and has no hash-growth admission control.

    This is currently a hypothesis consistent with the SQL shape and optimizer code, not a confirmed attribution to a specific incident plan node, because the original PHYPLAN and per-node estimates/runtime cardinalities are unavailable.

    Proposed follow-up investigation

    • Recover or reproduce the complete statement shape with representative table statistics.
    • Capture EXPLAIN PHYPLAN with estimated rows, NDV, row width, and selected build side for every grouped subquery and LEFT JOIN.
    • Identify whether the decisive cause is:
      • underestimated build cardinality/row width;
      • GROUP BY failing its own shuffle thresholds;
      • the dontShuffle(non-shuffle AGG) parent-join gate;
      • or a combination.
    • Evaluate allowing a partitioned parent join above a memory/network-cost threshold even when its AGG child is not already shuffled.
    • Add optimizer boundary tests for ordinary joins and GROUP BY subquery -> LEFT JOIN plans.

    The execution-layer memory budget/admission fix remains necessary independently: stale or inaccurate statistics and unsupported plan shapes must never be able to turn an optimizer mistake into a process/node OOM.

  4. added
    severity/s0
    ai-medium
    and removed on Jul 17, 2026
  5. 18 remaining items

  6. added 15 commits that reference this issue on Sep 17, 2026
    19e8def
    6631001
    f1c0179
    7d00102
    cf612fc
    4e0db08
    bd87354
    269fed1
    efb6c2b
    e4cfc9e
    a9afc26
    9d65fe1
    d8fdd53
    3bbb1b1
    1d37d62
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

ai-mediumkind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions