Skip to content

fix: bound HashBuild memory and spill under query budgets - #25837

Merged
XuPeng-SH merged 52 commits into
matrixorigin:mainfrom
aptend:repro/25782-main-harness
Jul 25, 2026
Merged

XuPeng-SH merged 52 commits into
matrixorigin:mainfrom
aptend:repro/25782-main-harness

Conversation

@aptend

@aptend aptend commented Jul 17, 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:

Fixes #25782

What this PR does / why we need it:

HashBuild could grow past spill and process-memory safeguards, allowing large joins to exhaust a CN and trigger a system OOM. This PR makes memory admission finite and hierarchical, and gives shuffle joins a bounded spill/re-spill path when hard admission rejects growth.

The commits are separated so the correctness, performance, diagnostics, and validation infrastructure can be reviewed independently. Together they:

  • make hashmap resize transactional so a rejected allocation leaves the old table usable;
  • account retained batches, hashmap growth peaks, expressions, spill scratch/readers, disk bytes, and file descriptors;
  • propagate process spill limits to remote pipelines;
  • deliver one terminal build error to all broadcast consumers instead of exposing a partial build;
  • avoid double-charging an already-accounted retained batch when emergency spill scratch grows;
  • preserve expression join keys in shuffle spill/re-spill by admitting the full evaluator-tree peak before Eval, returning a bounded budget error before allocation when that peak cannot be admitted;
  • bound group spill-reload preallocation by proven cardinality and the active spill-memory limit;
  • compact and reuse spilled aggregate state and remove avoidable decimal aggregation/hash-probe work;
  • emit sparse spill/budget diagnostics to statement profiles and durable logs;
  • add native DUMP TABLE / LOAD TABLE fixture support and reusable image-build caches for repeatable TPCH-scale validation;
  • cover budget compatibility, ownership transfer, overflow, provider failure, spill-record merge, and cleanup/error paths.

LOAD TABLE trust and integrity boundary

DUMP TABLE / LOAD TABLE is an administrator-level fixture transport, not an untrusted file-ingestion API. The manifest and the configured ObjectCopier are trusted inputs. The streaming fallback computes and verifies SHA-256, while a provider-native server-side copy deliberately verifies object existence and size without reading the copied object back through CN to recompute its hash or physical metadata.

This is an intentional performance contract: re-reading and hashing every copied object would turn a metadata/server-side-copy operation back into a full 100 GB / 1 TB data scan, consume CN bandwidth and CPU, and erase the measured fixture-load benefit (about 9 seconds for 100 GB and 44 seconds for 1 TB). Same-size corruption introduced by a trusted storage provider is therefore outside this SQL command contract and belongs to the provider checksum/integrity layer.

Validation

After rebasing onto current main:

  • go build and go vet pass for process, group, hashbuild, hashjoin, and spillutil;
  • full tests pass for the same packages;
  • focused -race -count=3 tests pass for retained emergency scratch growth, bounded group reload preallocation, and expression-key spill admission;
  • a real shuffle HashBuild test verifies an expression join key spills successfully, while a low-budget test verifies rejection happens before evaluator allocation;
  • the latest coverage-only commit passes go test ./pkg/vm/process ./pkg/sql/colexec/spillutil ./pkg/sql/colexec/hashbuild;
  • the earlier two-CN hard-budget reproduction returned exactly 132096, with spill on both CNs and no OOM, OOM kill, or swap;
  • TPCH fixture load was measured at about 9 seconds for 100 GB and 44 seconds for 1 TB.

Performance run: https://github.com/matrixorigin/mo-auto-test/actions/runs/30081071473

  • TPCH 100 GB: four measured turns average 87.592 s, versus 98.679 s on the latest main daily run (11.2% faster). All queries succeeded and no spill occurred.
  • TPCH 1 TB: two measured turns completed in 969.523 s and 973.105 s, averaging 971.314 s, versus 1113.188 s on the latest main daily run (12.7% faster). The two turns differ by only 0.37%.
  • Both measured 1 TB turns exercised the real spill path, spilling 60.14 GB and 77.57 GB respectively in Q9 and Q18. All queries succeeded without OOM or spill-budget errors, so the improvement is not obtained by avoiding spill.
  • The latest main run also spilled in Q18 through the existing group-aggregation spill path, but it did not enter HashBuild spill for Q9. With this PR, Q9 reached the 40 GiB query-wide HashBuild budget and spilled 10.96 GB and 28.39 GB in the two measured turns. Q9 still completed in 92.33 s and 92.78 s, effectively flat against the main average of 92.39 s, demonstrating added OOM protection without a material Q9 regression.

@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Jul 17, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Jul 17, 2026
@aptend
aptend force-pushed the repro/25782-main-harness branch from 4780080 to 174b8cc Compare July 17, 2026 08:04
@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 →

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

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

发现至少 1 个明确的 correctness blocker,另外还有 1 个完整性风险:

  1. LOAD TABLE 现在会直接把 manifest 里的 ObjectStats 当成权威元数据写进 catalog,而不再回读目标对象做物理元数据校验。handleLoadTable 在 pkg/frontend/table_dump.go:1199-1253 这里只检查了 len(item.Stats)、GetAppendable() 和 ObjectName(),随后 submitTableDumpObjects 在 table_dump.go:990-1045 里直接把这些 stats 展开并提交给 relation。相比 main 分支原先会通过 loadPhysicalTableDumpStats/validatePhysicalTableDumpObjects 重新读取 extent/blocks/rows/size/sort-key zone map 并覆盖 manifest stats,这里少了最后一道 fail-closed 校验。结果是:只要 manifest 里的对象名对得上,一个 stale/forged manifest 就能把错误的 extent、block count、row count、origin size、sort-key zone map 写进 catalog;后续 block location 展开和 zone-map pruning 都会基于这些错误 stats 工作,直接变成错误结果风险,而不仅仅是装载失败。

  2. provider-side CopyObject 路径现在也把 manifest 的 SHA-256 检查降成了 size-only。copyTableDumpFile 在 pkg/frontend/table_dump.go:348-382 对 providerCopied 返回空 hash,installTableDumpObject 在 table_dump.go:921-929 里对 providerCopied 只看 size 相等就放行;verifyTableDumpObject 对空 hash 也是 size-only(table_dump.go:886-896)。现有测试甚至显式锁定了这个行为:pkg/frontend/table_dump_test.go:838-843 允许 same-size 的 "corrupt object byte" 成功安装,pkg/frontend/table_dump_test.go:964-972 也断言 provider-copy 返回空 hash 并只做 size 校验。

如果你坚持当前 PR 描述里的“trusted manifest / trusted provider”边界,第 2 点可以算风险接受;但第 1 点我认为仍然是 blocker,因为它把未经物理校验的 stats 直接写成了后续读路径的权威 catalog 元数据。

@aptend

aptend commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

关于 physical ObjectStats 校验,我不同意把它作为当前 PR 的 correctness blocker,也不会把逐 object 物理 metadata 回读重新放回默认 LOAD TABLE 路径。这里不是遗漏校验,而是已经通过性能实验确定的设计边界。

DUMP TABLE / LOAD TABLE 的定位是管理员级 fixture/restore 通道,不是接受任意 manifest 的文件导入接口。实际闭环是:

  1. DUMP TABLE 从 catalog 生成 manifest stats,同时复制对应的 immutable object;
  2. 所有 object 完成后才写 ready marker;
  3. LOAD TABLE 要求 relation topology/schema hash、object name、non-appendable 标志、fixture path、size、对象数和 block 数边界全部匹配;
  4. provider-side CopyObject 复制 manifest 指向的同名 immutable object,随后确认目标对象存在且 size 一致;
  5. manifest 和配置的 provider 都是该管理员操作的 trusted input。

在这个契约下,manifest stats 就是备份元数据的权威来源。stale/forged manifest 与 trusted provider 产生 same-size corruption 属于同一个被明确排除的威胁模型。若认为 manifest 可被不可信方修改,那么仅恢复 extent/blocks/rows/zone-map 回读也不是完整的安全方案:对象 payload 仍可能发生同尺寸篡改,应该另行设计 authenticated manifest 和 provider checksum,而不是只在 catalog stats 这一侧增加昂贵的部分防御。

这里也需要区分两类成本:SHA-256 回读会扫描完整 100 GB / 1 TB;物理 stats 校验虽只读取 header/meta range,但仍会为每个 object 增加远端 GET、metadata 解析和 CN 路径,成本按 object 数增长,直接破坏 server-side copy 后的快速 catalog install。我们之前正是因为实际大规模验证显示这些逐对象防御让 LOAD 接近重新导入的慢路径,才删除它们。

当前真实结果是:

这些数据验证的是我们真正支持的闭环:由 DUMP TABLE 生成、存放在受信 stage、通过受信 provider 复制并由 LOAD TABLE 安装。它并不声称支持人工构造或不可信 manifest。

因此本 PR 保持当前 fast trusted-restore 路径,不恢复默认 physical metadata reread。若产品后续需要接收不可信备份,可以单独设计显式 strict validation/authenticated manifest 模式,并单独承担和验收其性能成本。

@aptend

aptend commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

补充精确的逐提交 A/B 数据。刚才重新核对了当时三个 TKE job 的原始日志;使用的是同一个 COS fixture tpch100g/v1 和同一条 TPCH benchmark load 路径:

MatrixOne commit 校验路径 TPCH 100G fixture load
38873779232a provider copy 后 SHA-256 回读 + physical metadata 校验 511s
51b71138bfa5 去掉 provider SHA-256 回读,保留 physical metadata 校验 453s
27a74f04f50d 同时去掉默认 physical metadata 回读,采用 trusted manifest stats 11s

对应原始 run/job:

三个日志分别明确打印:

  • Loaded tpch100g fixture ... in 511s
  • Loaded tpch100g fixture ... in 453s
  • Loaded tpch100g fixture ... in 11s

两个 MatrixOne 变更也是连续且隔离的:51b71138 只移除 provider-copy 后的重新哈希;27a74f04 再移除逐 object physical stats 回读。auto-test 在第一和后两次之间只有删除未使用 standalone native-fixture jobs 的变化,benchmark/load 脚本没有变化。

因此这不是笼统的性能担忧:

  • 仅去掉 SHA 回读:511s → 453s,减少 58s;
  • 再去掉 physical metadata 回读:453s → 11s,减少 442s,load 快约 41.2 倍;
  • 两类重复校验全部去掉:511s → 11s,减少 500s,快约 46.5 倍。

同一 final run 的 1T fixture load 为 49s;另一次独立 load 记录为约 44s。所以恢复默认 physical metadata 校验会直接否定该功能的规模化价值。

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

Request changes.

I withdraw my previous physical ObjectStats blocker after re-checking the enforced tenant-admin boundary, DUMP publication order, and the supplied A/B data. Same-size corruption is outside the explicitly trusted fixture/provider contract and is not a blocker for this PR.

There is, however, a blocking ownership gap in the new HashBuild budget implementation: SpillEngine can destroy retained build batches without releasing the reservations that own those bytes.

  1. In RebuildHashmap with NeedBatches=false, builder.Batches.Clean releases the physical mpool allocations, but GetJoinMap immediately transfers builder.batchReservations into the JoinMap. Semi/anti/mark-style joins therefore carry phantom batch charges throughout probing. A focused 8,192-row int32 reproduction left generation.Used unchanged at 1,769,472 bytes before and after the physical clean.

  2. reSpillBucket detaches builder.Batches.Buf and cleans each batch, but the corresponding reservations remain charged until reSpillBucket returns and the caller later frees the builder. This is specifically the recovery path entered after an admission rejection; retaining already-freed batch charges while reserving expression/scatter/read scratch can turn a recoverable spill into another false admission failure.

Please fix this at the ownership boundary: provide a HashmapBuilder API that drains physical batches and their reservations together (respecting CopyIntoBatches coalescing, so releasing all ingress tokens after the last physical batch is fine), and use it in both paths instead of manipulating Batches directly. Add budgeted tests proving that NeedBatches=false drops the batch charge before probe admission and that re-spill drops drained-batch charges before subsequent scratch/read admission.

The current Ubuntu UT failure is TestDelete3 in untouched TAE code; it does not appear related to this diff, but the check is still red.

e.buckets = e.buckets[1:]
if bucket.ProbeFd != nil {
e.probeReader.ResetForFd(bucket.ProbeFd)
if err := e.probeReader.EnsureBuffer(e.cfg.Budget); err != nil {

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.

This probe-buffer admission still sees stale build-batch reservations when NeedBatches=false: the physical batches were cleaned just above, but GetJoinMap transferred their tokens. A focused 8,192-row int32 reproduction left generation.Used() unchanged at 1,769,472 bytes across that clean. Please release batch ownership before this admission through a HashmapBuilder lifecycle API.

if b != nil {
buildRows += int64(b.RowCount())
}
if err := evalAndScatter(b, buildWriters, nil, e.keyExecs); err != nil {

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.

The re-spill loop cleans these detached physical batches, but their reservations remain in the builder until the caller frees it after reSpillBucket returns. Since this is the admission-recovery path, those phantom charges can reject the expression/scatter/read scratch needed to progress. Please drain Batches and reservation ownership together rather than detaching Batches.Buf directly.

@aptend

aptend commented Jul 25, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the HashBuild budget ownership blocker in 7088293ab.

The fix introduces one ownership boundary, HashmapBuilder.DrainCopiedBatches:

  • a successful visit destroys each physical build batch and releases all coalesced ingress reservations after the final physical batch;
  • a failed visit retains the current/remaining physical batches and all conservative reservations for the existing builder cleanup path;
  • the implementation is a single linear pass, avoiding repeated slice shifts/recalculation on large re-spills.

Both affected SpillEngine paths now use this boundary:

  1. RebuildHashmap with NeedBatches=false drains batch memory and batch reservations before GetJoinMap, so the JoinMap no longer inherits phantom batch charges during probe;
  2. reSpillBucket drains each accumulated batch after successful scatter and releases the coalesced reservations before subsequent pending/read admission.

Added budgeted regressions covering:

  • coalesced ingress reservation release after the last physical batch;
  • partial visitor failure retaining cleanup ownership;
  • NeedBatches=false carrying less live budget than NeedBatches=true while entering probe;
  • direct re-spill returning without a stale builder batch charge, followed by successful full-cap admission.

Fresh local validation:

  • focused regressions, -count=10: pass;
  • focused -race: pass;
  • full hashbuild and spillutil package tests: pass;
  • package build and vet: pass.

The unrelated TestDelete3 failure is being handled by the existing separate PR, as noted.

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

我重新做了一轮 deep review,并且把作者在评论里对 trusted-manifest / trusted-provider 边界的说明也纳入考虑了。当前结论是:在这个明确声明的管理员级 fixture/restore 契约下,LOAD TABLE 不回读物理 metadata、provider-side copy 只做 size 校验,是有意识的性能/信任边界选择,不再构成我这边的 correctness blocker。

除此之外,我又把 HashBuild budget / spill / remote pipeline 终态发布主链过了一遍,没有再确认出新的高置信 correctness、robustness 或 unhappy-path 问题。LGTM.

This branch was previously deployed

1 inactive deployment
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 kind/enhancement kind/feature kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants