Skip to content

fix: reserve hashbuild spill recovery budget - #26585

Merged
XuPeng-SH merged 7 commits into
mainfrom
codex/fix-hashbuild-spill-recovery
Aug 3, 2026
Merged

XuPeng-SH merged 7 commits into
mainfrom
codex/fix-hashbuild-spill-recovery

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 2, 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 #26586.

Related architecture issue: #26459.

What this PR does / why we need it:

Root cause

Shuffle HashBuild workers share one finite query/CN budget. A worker could retain build batches until the shared budget was nearly exhausted, then discover that it did not own every resource needed to drain them:

  • partition/materialization scratch and allocation-replacement overlap;
  • shuffle-key expression executor evaluation, including varlen and flow-control replacement peaks;
  • spill write buffers while optional coalescing cache was still charged.

A sibling worker could consume the missing headroom after retention. Recovery then failed before the first retained batch was released. This is a recovery-ownership defect, not a TPCH-Q9-specific threshold problem.

Recovery invariant and fix

Before shuffle HashBuild retains a spillable destination, the same execution generation now owns a complete recovery proof:

  1. The existing copy projection proves the largest retained destination and its logical later spill materialization.
  2. The one stable build-key executor set owns an ExpressionMemoryLease that pre-admits the complete sequential expression recovery high-water. Spill reuses that executor/lease; the former second spill executor/lease owner is removed.
  3. One rounded spill recovery lease covers mandatory partition/marshal scratch. Replacement allocation admits old+new overlap before mutation.
  4. Mandatory recovery has priority over optional 64 KiB write coalescing. On admission failure, pending optional buffers are flushed/dropped and mandatory admission is retried exactly once. A genuine over-cap request still fails closed.

Retained batches are drained oldest-first and released immediately after each successful spill. Reset, Free, cancellation, expression failure, spill I/O failure, and publication handoff each preserve exactly one cleanup owner.

Scope and performance

  • No global coordinator, new framework, configuration, goroutine, channel, or probabilistic retry.
  • Spill partitioning uses one row-id array and one reusable selected batch instead of fanout-sized vector sets.
  • Resident HashBuild adds no per-row/per-batch synchronization or I/O. The recovery token cost is O(1) per execution.
  • Merge-base to final VARCHAR_AREA_128 A/B benchmark: 5.436 ms/op to 5.359 ms/op, p=0.684; no significant regression. Allocation delta is bounded at about 40 B and 2 allocations per execution.

Validation on latest main

Rebased onto 4a747e4458.

  • mo-cgo-test -count=1 ./pkg/sql/colexec/hashbuild
  • mo-cgo-test -race -count=1 ./pkg/sql/colexec/hashbuild
  • Every current added/modified HashBuild behavioral test was measured and run separately under race; all 50 reached -count=100, including the deterministic expression-key/shared-pressure reproducer.
  • Dependent packages passed: hashjoin, dedupjoin, rightdedupjoin, spillutil, and pkg/sql/compile.
  • go build for HashBuild and go vet for HashBuild plus the issue regression passed.
  • SQL black-box regression passed in 12.74s: one CN, max_dop=8, 28 MiB cap, forced shuffle, real spill, exact result 4096, and a fresh post-query statement.
  • Post-rebase resident benchmark smoke: computed INT64 1.568 ms/op; area-backed VARCHAR 5.388 ms/op.

Review-comment closure

The P1 expression-key counterexample at old head 9b5a8125 is accepted. TestShuffleHashBuildExpressionRecoverySurvivesSharedBudgetPressure uses a real computed % shuffle key, retains the first batch, fills the same generation exactly with sibling pressure, then proves retained drain plus direct spill succeeds and all budget ownership returns to zero.

Non-goals

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

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement kind/test-ci labels Aug 2, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Aug 2, 2026
@XuPeng-SH

XuPeng-SH commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Accepted the latest P1 and fixed it on 271724a32b (rebased onto current main 59517279b8).

The review counterexample was reproduced before changing production code:

serial / serial_full x BINARY / VARBINARY
logical admitted peak = 4,571,136
physical retained      = 4,833,280

All four cases failed the same retained <= admittedPeak invariant. This confirms the issue is the allocator-capacity model, not a query-specific encoding estimate.

The fix now derives the expression peak from the physical ownership oracle used by the executor (cap(data)+cap(area)):

  • fixed data, varlena descriptors, and varlena area are modeled independently;
  • a generic O(1) upper bound uses the actual mpool.GrowCapacity contract and covers any incremental growth history whose logical requirement stays within the declared bound;
  • inline varlena results do not reserve a nonexistent area;
  • the existing per-row metadata allowance and 64 KiB allocation slack remain;
  • no row scan, result preallocation framework, encoding-format change, or spill-path special case was added.

The new regression coverage includes:

  • serial and serial_full;
  • zero-filled BINARY(128) and VARBINARY(128);
  • ordinary non-recovery first evaluation plus a second batch (the exact late-audit failure);
  • recovery N-1 / N / N+1 admission boundaries;
  • sibling-saturated budget during first evaluation and reuse;
  • physical retained-capacity audit and complete cleanup.

Final validation on the rebased head:

  • new focused matrix: -race -count=4 (repeat count derived from the measured 7.46 s run);
  • full pkg/sql/colexec/hashbuild: normal and -race;
  • targeted go vet;
  • public SQL regression with a planner-produced serial_full shuffle key, million-row build input, real spill, correct result, and a fresh health query;
  • computed-key non-spill A/B on Apple M4, 20x x 10 samples: head median ~1.56 ms/op vs parent ~1.62 ms/op, both 212 allocs/op (no measurable regression);
  • git diff --check.

Please re-review the new head.

@XuPeng-SH
XuPeng-SH requested a review from gouhongshen August 3, 2026 02:11

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

Codex automated review

The separate spill-expression lease and serial_full false-rejection blockers are fixed and withdrawn; the descriptor-scan performance concern remains fixed/non-blocking. The latest commit also fixes the exact cap(data)+cap(area) under-reservation previously reported. One distinct blocking owner remains: serial/serial_full's retained Packer is outside the recovery budget.

P1 - Charge the serial Packer to the expression recovery lease (pkg/sql/colexec/hashbuild/hashmap.go:526)

Author response: 271724a32b derives the peak from physical vector capacities and correctly fixes the prior cap(data)+cap(area) finding. Why this remains blocking: this line still converts the encoded serial width into only a result-vector peak. opSerial also retains a types.Packer, whose power-of-two class allocation is excluded by ExpressionExecutorRetainedBytes. This is a distinct owner. For one row of serial_full over four supported, zero-filled VARBINARY(65535) arguments, the encoded result is 524,292 bytes. The recovery formula reserves 1,458,288 bytes, but evaluation retains a 1,048,576-byte Packer plus 532,480 bytes of result area and a 24-byte descriptor: 1,581,080 bytes. Thus a cap between those values admits recovery while physical expression memory exceeds the hard cap; shared workers can amplify this into the OOM the budget is intended to prevent. Account the Packer's size-class capacity and growth overlap in the same lease, or preallocate it under an equivalent accounted contract, and cover the admission boundary with a real serial executor test.

@aptend aptend 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 at 271724a32b. The earlier spill-expression ownership, serial_full false-rejection, descriptor-scan, and Vector physical-capacity findings are fixed. One distinct P1 blocker remains.

P1 — Charge the retained serial Packer to the expression recovery lease

expressionResultPeak (pkg/sql/colexec/hashbuild/hashmap.go:526) converts the serial encoding bound only into a result-Vector peak. However, opSerial also retains a types.Packer; Reset preserves its backing allocation, and ExpressionExecutorRetainedBytes does not include it. Packer growth additionally allocates the replacement before releasing the old class allocation.

I reproduced this with a real one-row serial_full executor over four zero-filled VARBINARY(65535) arguments:

  • encoded result: 524,292 bytes
  • recovery lease: 1,458,288 bytes
  • retained Packer size class: 1,048,576 bytes
  • retained result Vector: 532,504 bytes
  • retained expression memory: at least 1,581,080 bytes

The preflight therefore admits 122,792 bytes less than the post-run retained owners, even before accounting for the Packer replacement overlap. With a cap in that interval—or sibling workers consuming the remaining shared generation—evaluation bypasses the hard recovery budget and can recreate the OOM condition this PR is intended to prevent.

Please account the Packer initial/retained capacity and growth overlap in the expression recovery ownership, or preallocate it under an equivalent accounted contract, and add a real serial-executor N-1/N/N+1 admission regression. Existing lease.Retained() assertions do not cover this owner because they count only mpool-backed Vector capacity.

Fresh local ordinary and full race suites passed for vector/function/hashbuild, as did focused adaptive race repetitions and dependent join/spill/compile packages; this finding is independent of CI.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Accepted both latest P1 reviews from @gouhongshen and @aptend and fixed the shared root cause on 2c3fa408d3.

The reflection is that the prior audit stopped at the existing ownership oracle: ExpressionExecutorRetainedBytes enumerated result/selected/child vectors, but the opSerial closure also owns a class-allocated Packer. Treating oracle visibility as the complete owner graph was incorrect. Reset retains that backing, and ensureSizeSlow allocates the replacement before releasing the old class, so both steady ownership and growth overlap were missing.

The fix closes that lifecycle without changing the serial format, Packer growth policy, or per-row Eval path:

  • stateful builtins can optionally expose retained non-vector backing to the existing expression ownership oracle; serial and serial_full report the real Packer class capacity;
  • HashBuild reserves the default 4 KiB Packer before constructing the executor, then preserves that ownership on failed recovery growth until executor Free;
  • the target Packer class is derived from the production encoded row bound plus the largest component append, using the real cap(buffer)+append and power-of-two class contract;
  • the existing replacement reservation now covers old retained Packer + new target Packer as part of the same executor-tree lease;
  • duplicate-result accounting duplicates only the result Vector, while recovery/reuse retain the complete executor replacement overlap.

The exact reported counterexample is now a real executor boundary test for both serial and serial_full: one row, four zero-filled VARBINARY(65535) inputs, Packer class 1 MiB, N-1/N/N+1, budget saturated by a sibling token, and two evaluations. It asserts that the physical retained oracle is greater than the result-only bound, remains within the admitted executor peak, performs no late reserve, and returns to zero only after executor Free followed by lease Release. Separate tests cover constructor N-1 and real Packer Reset/reuse/Close.

Validation on the final tree:

  • full pkg/container/types, pkg/sql/plan/function, pkg/sql/colexec, and pkg/sql/colexec/hashbuild tests;
  • focused real-owner/admission matrix under -race -count=4;
  • targeted go vet for the changed packages;
  • git diff --check.

No encoding-format change, result-preallocation framework, query-specific branch, row scan, or non-serial per-row work was added. Please re-review the new head.

@XuPeng-SH
XuPeng-SH requested review from aptend and gouhongshen August 3, 2026 02:55

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

Codex automated review

The previously blocking uncharged serial Packer ownership is fixed and withdrawn. Earlier spill-expression, serial bound, vector-capacity, and descriptor-scan topics are also fixed or accepted as non-blocking; none remain blocking. The new allocator-bound and lifecycle logic is consistent with construction, growth overlap, reset, and cleanup contracts. Focused Packer tests passed normally and under race; formatting, vet, and diff checks passed. CGo-transitive tests were unavailable locally because libmo.dylib is absent.

@ck89119

ck89119 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Deep review completed at exact head 2c3fa408d37d4b2d5cd5bc8e62b605b0ce5aa8e3.

The previously blocking uncharged serial/serial_full Packer ownership is fixed. I re-audited the complete recovery owner graph, including constructor admission, allocator size-class growth overlap, retained executor accounting, Reset/Free, evaluation failure, cancellation, spill I/O failure, generation reuse, and JoinMap handoff. I also rechecked the vector areaDisjoint fast-path invariant and its dangerous mutation surfaces. No new actionable code finding was found.

Fresh local validation on this exact head passed:

  • ordinary tests for pkg/container/types, pkg/container/vector, pkg/sql/plan/function, pkg/sql/colexec, and pkg/sql/colexec/hashbuild;
  • the same owning-package matrix under -race;
  • targeted go list, go vet, and go build;
  • public SQL regression TestHashBuildSharedBudgetRecoverySQL (PASS, 16.722s);
  • git diff --check.

Code verdict: clean. Merge readiness remains separate: the PR is currently behind main, the aggregate review decision still reflects historical requested-changes reviews, and several CI jobs are still running.

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

Approved after exhaustive review of exact head 2c3fa408d37d4b2d5cd5bc8e62b605b0ce5aa8e3. The previously blocking Packer ownership gap is fixed, no new actionable code issue was found, and the owning-package normal/race tests, vet/build, SQL recovery regression, and diff checks passed locally.

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

Re-reviewed head 2c3fa408d3. The prior P1 is fixed: serial/serial_full Packer ownership, constructor admission, growth overlap, reuse, and cleanup are now covered by the expression recovery lease. Focused adaptive race tests, full changed-package normal/race tests, dependent-package tests, build, vet, and diff checks passed. No remaining code-review blocker found; CI was not used for this conclusion.

@LeftHandCold

Copy link
Copy Markdown
Collaborator

复审结论(head bcb48b0):未发现新的 blocking issue。

这次更新仅为 merge main;相对上一版 2c3fa40,新增改动只涉及 5 个 disttae 文件,与本 PR 的 HashBuild / Vector / serial 改动零重叠,因此没有引入冲突解决或改变本 PR 语义。

我重新核对了:

  • HashBuild resident→spill/direct-spill 的预算与状态转换;
  • mandatory recovery、optional coalesce 回收及失败边;
  • serial/serial_full Packer 与 Vector 物理容量上界;
  • Reset/Free、共享 generation、FD/disk/mpool 资源释放;
  • N-1/N/N+1、共享预算饱和和恢复生命周期测试。

本地以 -p=1 定向运行 HashBuild、Packer、Vector、serial 契约测试,均通过。远端 CI 仍有任务运行中,因此这里只记录代码复审结论,不宣称整套 CI 已完成。

PR 在本次复审完成前已经合并,GitHub 已不能再提交有意义的 APPROVE;此评论用于记录最新 head 的 no-blocker 结论。

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/refactor Code refactor 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]: shuffle HashBuild can strand TPCH Q9 spill recovery under a shared budget

6 participants