Skip to content

[Design]: replace estimator-driven HashBuild admission with allocation-accounted memory ownership #26459

Closed

Description

@aptend

Context

PR #25837 introduced finite hierarchical HashBuild admission and bounded spill to stop the real OOM in #25782. That safety direction is necessary, but the implementation still uses operation-level estimates as hard admission facts. Subsequent regressions show that this model is not converging: each new data shape exposes another mismatch between a logical estimate and the allocator's physical behavior.

This issue is the umbrella for replacing estimator-driven hard rejection with one allocation-accounted ownership model. It is not a request to raise caps, exempt workloads, or add another type/function-specific multiplier.

Confirmed history

Incident Symptom Confirmed mismatch Status
#25782 / PR #25837 HashBuild bypassed spill and caused node OOM hash table growth was not admitted at allocation boundaries initial bounded-budget system merged
#26174 / PR #26178 fulltext INSERT requested 18.72 GB with about 1.29 GB used current ingress, retained tail, const materialization, and future drain were conflated fixed locally
#26192 / PRs #26231 and #26318 LOAD DATA rejected runtime-filter 3x and whole-payload multipliers double-counted retained owners fixed locally
#26413 / PR #26438 Hive external-table self-join rejected 50K-row ingress was estimated differently from CopyIntoBatches' real 8192-row segmentation and allocator rounding fixed locally and real SQL verified
#26454 string-expression join rejected immediately TEXT maximum 64 MiB was multiplied by 8192 rows and recursively summed with CAST/CONCAT nodes, producing exactly 551,368,048,640 bytes while used memory was about 1.48 GB and observed peak was about 6-7 GB open
#26186 spill transition could under-account ingress overlap isolated estimates missed a simultaneously-live ownership state closed follow-up
#26433 / PR #26455 retained ExpressionExecutor capacity could be under-counted or double-charged across reuse reservation lifetime did not follow physical retained capacity lifetime in progress

Related spill ownership work: #26408 and PR #26412.

The false rejections and under-accounting are opposite outcomes of the same design problem. Making an estimate more conservative prevents one OOM path but creates false rejection; relaxing it restores workloads but can lose a real allocation peak.

Root design problem

The current implementation mixes three separate concerns:

  1. Ownership ledger: which live allocation is charged, who owns it, and when it is released.
  2. Operation prediction: how much a future batch copy, expression tree, marshal, or spill transition might allocate.
  3. Pressure response: reclaim, spill, reduce a batch, disable optional work, or return a controlled error.

An inexact prediction currently feeds hard admission. Examples include type maximum multiplied by row count, empirical payload multipliers, logical Batch.Size/Allocated extrapolation, and recursive expression-tree maxima. None is a reliable representation of the next physical allocation.

Required invariant

Hard admission must use one source of truth:

accounted memory used
==
sum of live accounted allocator capacities
+ explicitly owned, bounded non-allocator scratch

A prediction may choose to spill early, but it must never by itself decide that a valid SQL statement cannot run.

For every owned allocation:

  • admission happens before physical allocation;
  • allocation failure rolls admission back;
  • reuse/Reset retains both capacity and charge;
  • ownership transfer moves one charge exactly once;
  • Free releases physical memory and charge together;
  • cancellation and every error path preserve the same invariant.

Proposed architecture

1. Generic allocation account

Introduce a low-level MemoryAccount/AllocationAccount contract outside the SQL operator layer. HashBuildBudgetGeneration initially implements it; the abstraction must not be HashBuild-specific so other spillable operators can adopt it later.

The account returns an exactly-once allocation lease. Estimates do not create retained leases.

2. Account-aware allocator growth

Add account-aware mpool allocation/growth entry points, with the charge associated with allocation metadata rather than duplicated in operator fields.

For a new allocation:

  1. determine the actual capacity requested from mpool;
  2. reserve that capacity;
  3. allocate;
  4. attach the lease to the allocation;
  5. roll back the lease if allocation fails.

For growth from oldCap to logical required:

  1. use the same mpool.GrowCapacity(oldCap, required) calculation as Grow/Grow2 to obtain newCap;
  2. keep the old allocation and its lease live;
  3. reserve the complete newCap replacement allocation before growth;
  4. allocate and copy;
  5. publish the replacement;
  6. free the old allocation, which releases the old lease;
  7. retain only the new allocation lease.

This accounts for the real allocate-copy-free overlap without a multiplier or a delta guess. An allocation that cannot be admitted is rejected before allocator state changes.

The allocation's account identity must survive cross-owner Free and vector/operator handoff. A mutable process-wide "current account" is not acceptable because child pipelines share a BaseProcess and can run concurrently.

3. Vector and expression integration

Vectors created for HashBuild-owned batches and expression results carry an optional allocation account. Data and varlen-area buffers inherit it on every grow.

FunctionResult and ExpressionExecutor must use the accounted vectors. Fixed-width headers are admitted from actual row/type size. Varlena payload is admitted from actual append/grow requirements, not SQL type maximum.

Unbounded Go-heap scratch in the controlled path must be removed or explicitly leased. For example, CONCAT currently builds temporary Go strings before AppendBytes; it should write through an accounted result buffer or use a bounded explicit scratch owner. Otherwise allocator accounting cannot claim to cover the expression peak.

4. Unified pressure response

A real allocation admission failure is typed pressure, not an invalid-budget invariant failure:

  1. release reclaimable retained state and/or start spill;
  2. retry the same logical work after reclaim;
  3. if one expression/input batch still cannot fit, reduce the processing batch without changing results;
  4. if one real row/value exceeds the finite cap, return a controlled error reporting the actual requested capacity;
  5. optional structures such as runtime filters may degrade to PASS when their exact allocation cannot be admitted.

ErrHashBuildBudgetInvalid is reserved for corrupted lifecycle/arithmetic/state invariants, not ordinary resource pressure.

5. Estimator demotion and deletion

Once a path is allocation-accounted, remove its hard-reservation estimator. In particular, recursive expressionTypePeak/expressionVectorPeak, payload multipliers, and source-to-destination capacity extrapolation must not remain as independent hard gates.

Estimators may remain only as scheduling hints for early spill and must be observationally distinguishable from exact allocation admission.

Migration plan

  1. Allocation primitive: account/lease interface; account-aware mpool alloc/grow/free; exact overlap and rollback tests.
  2. Container ownership: accounted Vector/Batch buffers; reuse, Reset, Free, Dup, and handoff rules.
  3. Expression path: FunctionResult/ExpressionExecutor integration; bounded non-mpool scratch; remove type-maximum hard admission.
  4. HashBuild path: migrate copied batches, hashmap auxiliary storage, expression keys, spill/re-spill readers/writers, scatter buffers, and runtime-filter buffers; delete superseded estimators.
  5. Pressure control: one reclaim/spill/retry/reduce-batch state machine shared by HashJoin, DedupJoin, and RightDedupJoin.
  6. Generalization: make the same allocation account usable by other spillable operators instead of creating another operator-specific budget system.

Implementation may be split into reviewable PRs, but the existing lifetime PR must not be treated as the final fix while hard rejection still depends on theoretical expression peaks.

Acceptance criteria

Accounting properties

  • After every alloc/grow/reuse/reset/free/transfer/failure event, budget used equals the live accounted physical capacities plus named explicit scratch.
  • Admission failure occurs before physical allocation and leaves both mpool and budget state unchanged.
  • Allocate-copy-free overlap is exact for the allocator's actual growth rule.
  • Reset preserves retained charge; Free/cancellation/error returns it exactly once.
  • No unbounded HashBuild-owned Go-heap allocation remains outside the account.

Behavioral properties

Test matrix

  • randomized/property tests over fixed and varlen vectors, const/shared area, partial selections, and random payload distributions;
  • exact-cap and one-byte-short boundary tests at every allocation/growth step;
  • fault injection before reserve, after reserve, during allocation, before publish, and during cleanup;
  • reuse across batches and execution generations;
  • cancellation and errors through HashJoin, DedupJoin, RightDedupJoin, spill, and re-spill;
  • race tests and repeated cleanup tests;
  • real regressions for the incidents above;
  • TPCH spill and non-spill performance validation.

Performance properties

  • no budget mutex or reservation per row;
  • admission runs only on actual allocation/growth or explicit scratch acquisition;
  • steady-state reuse with sufficient capacity adds no allocation-account call;
  • benchmarks cover vector append/grow, expression evaluation, normal HashBuild, and spill/re-spill.

Non-goals

  • raising the 40 GiB cap to hide false estimates;
  • exempting LOAD DATA or particular SQL templates;
  • special-casing TEXT, CONCAT, CASE, or individual schemas;
  • weakening the original no-OOM requirement;
  • treating estimator tuning as completion.

Completion definition

This issue is complete only when hard HashBuild memory admission is driven by owned physical allocation capacity, all HashBuild-owned unbounded memory is inside the account or explicitly bounded, the listed regressions pass, and estimator-only false rejection is structurally impossible rather than merely absent from the current test set.

Metadata

Metadata

Assignees

Labels

kind/designseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions