Repository navigation
Fix HashJoin right-side accounting when registering a stored block fails - #116991
Conversation
HashJoin::addBlockToJoin keeps data->allocated_size equal to the sum of allocatedBytes() over data->columns, maintained incrementally. It pushed the block into data->columns, registered it with stored_columns_index->add(), and only then advanced the counter. add() grows two VectorWithMemoryTracking members and is documented as meant to throw at the limit, so a memory-limit fault between those two statements left the block stored and never accounted for. In release builds the join then under-reports its size to sizeLimits().check and to the spilling thresholds, and for a Join engine table, whose object survives a failed INSERT, the uncounted block stays for the table's lifetime. In debug and sanitizer builds doDebugAsserts() raises LOGICAL_ERROR when it next runs; the CI occurrence came from the trailing LOG_TEST in ~HashJoin, which sits after the try/catch that wraps only the statistics block, so the assertion left a destructor. Seen as Stress test (arm_tsan) on ClickHouse#112973, sha 0b48064, 'data->allocated_size != debug_allocated_size (0 != 36263)'. data->rows_to_join was incremented at the top of the function, before nine statements that can throw, so it leaked on all of them. Moving the increment to the commit point closes those paths too; nothing reads it in between and there is no early return in that range, and throws after the commit point, including insertFromBlockImpl, keep the existing balanced rollback. StoredColumnsIndex::add is made all-or-nothing in the same change. blocks and row_stores are indexed by the same block number, and size() reports blocks.size() while rowStoresData() is indexed by block_no, so a throw between the two push_backs would desynchronise them permanently. It is also what makes the rollback above safe: without it, popping the block from data->columns would leave a dangling non-null entry in blocks, which resolveEmitColumns dereferences with no liveness check. Only the shape where the tracked counter is zero against live columns is fixed. The shape where both operands are non-zero and the second is a few percent larger is a different mechanism, as is the opposite-polarity variant in releaseJoinedBlocks(restructure = true). Investigated at alexey-milovidov's request on ClickHouse#112973. Related: ClickHouse#99920 Co-Authored-By: Claude Opus 5 <[email protected]>
The test asserted only the counter the destructor assertion reads, so neither half of the change was actually observed by it. The relocated data->rows_to_join now has an SQL oracle. getAnalysisReport reports getRightTableRowCount(), which returns rows_to_join verbatim, and it surfaces as the Right: rows line of EXPLAIN ANALYZE. Reverting only the relocation prints 2 there instead of 1, with the stored rows unchanged and no server abort, since the two counters the assertion compares stay mutually consistent in that arm. The four settings and the no-parallel-replicas tag follow 04757_explain_analyze_join_filled_and_constant, which reads the same line from a Join engine table; two of them are randomized by clickhouse-test and would otherwise move the group to the other side. This arm needs no sanitizer, so the test is no longer blind outside debug and sanitizer builds. A third insert repeating an existing ANY key reaches the rollback that discards a block after it was registered. That path calls StoredColumnsIndex::clearEntry, which writes row_stores[block_no] behind a bound taken from blocks, so it is where a desynchronised pair is observable rather than merely latent. With the all-or-nothing change in add() reverted it indexes past the end of row_stores, and the same build with the change restored passes. libc++ hardening is FAST for every build type other than Debug and already checks element access, so that is an abort in a release build, not only a debug assertion. join_any_take_last_row is pinned because the arm is silently inert if it is ever 1. allocatedBytes() moves above the try so only add() and integer arithmetic remain inside it. The catch pops data->columns without clearing the index entry, unlike the sibling rollback further down, which clears it first because popping after a successful registration dangles a slot. That difference rested on StoredBlock::allocatedBytes() never allocating, which is true but not visible at the call site. add() does not modify the block, so the value is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewTwo independent reviews of this change (a cold reviewer and a separate model gate) over two ❌ Blockers: none.
💡 Noted, not blocking
|
|
Workflow [PR], commit [78c6887] Summary: ✅
AI ReviewSummaryThis PR moves the Final Verdict
LLVM Coverage ReportMeasured on commit 78c6887.
Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-9:20260829-013900 |
|
cc @rschu1ze @KochetovNicolai, could you review this? |
check_style.py rejects any functional test whose path contains `fail`, so the Style check on this pull request rejected 05048_hash_join_stored_block_registration_failure.sql. Both files of the pair are renamed to ..._registration_fault with their contents unchanged. Locally, functional_tests_check reports 1/1 failures before the rename and 0/1 after, and the renamed test still passes against the same build. Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units10 translation units recompiled, 49 s compile time in total, 10 of them have a recent master baseline. |
CI finish ledger - 22e0df2CI is fully finished at this commit. Two checks failed and both have an owner. The
Reports:
Everything that ran is green: 46 Session id: cron:our-pr-ci-monitor:20260829-063000 |
|
This PR looks like it fixes a hallucinated problem and the new "error correction" (catch block) looks weird. @harikrishnan94 Like to check in more detail? Feel free to close if the PR is chasing ghosts. |
|
Two things are checkable on master, and one thing I cannot back. Checkable: Cannot back: that this is the mechanism behind the On the shape you flagged: agreed. Reserving one more entry in both index vectors before Whether the hole is worth guarding at all is your call. If you would rather close it, that is fine by me and I will not reopen it; the |
|
@groeneai Make the PR merge-ready |
… back `addBlockToJoin` published the block into `data->columns` and only then registered it in the index and advanced the counters, so a throw inside `StoredColumnsIndex::add` left the block stored and uncounted. That was guarded with a rollback `catch`. Register and account for the block while a local list still owns it and `splice` it in afterwards instead: `splice` cannot throw, so there is no window left to roll back. Reserving both index vectors before either is appended to does the same for the index's own invariant: the appends are then non-allocating, so `blocks` and `row_stores` can no longer be left different lengths, and the second `catch` goes away too. Reserving at the call site, which is what I said I would push, is not enough on its own: the index is shared between the slots of a `ConcurrentHashJoin`, so another slot can consume the reserved entry between the reserve and the add. Doing it inside `add`, under the mutex that already serialises the appends, has no such window. Co-Authored-By: Claude Opus 5 <[email protected]>
…ry each The previous commit reserved exactly one more entry in `blocks` and `row_stores` before appending. `std::vector::reserve` takes the requested capacity literally, so capacity equalled size after every append and the next registration reallocated and copied both vectors again: 1000 blocks caused 1000 reallocations where plain `push_back` causes 10. Double the capacity instead, which keeps both appends non-allocating and restores the amortised constant cost per block that `push_back` had before. Co-Authored-By: Claude Opus 5 <[email protected]>
Deriving it from `blocks.capacity()` meant a `row_stores.reserve` that threw at the memory limit left `blocks` grown, and the next registration then doubled that already grown capacity instead of retrying the same target, so repeated failing inserts into a `Join` table could overallocate the index. Both vectors always hold the same number of entries, so the size is the stable input. Co-Authored-By: Claude Opus 5 <[email protected]>
Head branch was pushed to by a user without write access
|
Merge-ready at Both One measurement I did not have on 08-31: with master's ordering and the failpoint, the test's second I also merged master, since the branch was 3865 commits behind and its last CI run was a week old with 102 jobs dropped. One residual, also stated in the description: the test does not distinguish the paired pre-reservation from two independent appends, because after this change neither append can fail. That half rests on the appends being non-allocating plus a |
CI finish ledger - 39f7a33Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this PR, structurally: this diff is confined to
Session id: cron:our-pr-ci-monitor:20260905-120053 |
|
@groeneai Merge with master and re-run the CI. |
|
Merged master at The merge changes nothing that was approved: If |
| /// The target doubles the shared size, so growth is amortised constant per block, and a reserve | ||
| /// that threw after growing only one vector is retried at the same target. | ||
| chassert(blocks.size() == row_stores.size()); | ||
| if (blocks.size() == blocks.capacity() || row_stores.size() == row_stores.capacity()) |
There was a problem hiding this comment.
The failpoint (l. 297) is fine - even it's not really clear to me what it is good for.
The other C++ code changes reserve memory. Correct me if I'm wrong but the condition in l. 306 looks like it is by default true. That means ever call to StoredColumnsIndex::add will call reserve 2x. That looks potentially expensive.
There was a problem hiding this comment.
I think this is fine. Previously, any necessary reallocations happened implicitly inside the two push_back calls. The change moves those allocations ahead of both appends, so if either reservation hits the memory limit, neither vector gets a new entry. Once both reservations succeed, the pointer appends are non-allocating. This makes the paired append all-or-nothing with respect to allocation failures, although one vector’s capacity may already have increased.
That means ever call to StoredColumnsIndex::add will call reserve 2x.
If you mean every call, that isn't the case: the two reserve calls are guarded by the capacity check. Each successful append increases the size by one, while the reservation target is 2 * size + 1. With successful insertions, growth therefore happens O(log N) times over N blocks, preserving amortized O(1) append cost. Calls where both vectors already have spare capacity skip the reservations entirely.
There was a problem hiding this comment.
The branch fires only at a capacity boundary, so reserve is not called per add. Measured on this branch (debug build, hash join whose right side is read in 1000 blocks with max_block_size = 1000, one add per block): 1000 add calls, branch taken 10 times, at adds #1, 2, 4, 8, 16, 32, 64, 128, 256, 512, with capacity going 1, 3, 7 ... 1023. The other 990 calls only compare size against capacity twice, under the mutex the function already holds. Filling the same two containers with plain push_back, which is what happens today, reallocates 11 times each, so 22 allocations against 20 here: the reserve replaces those reallocations instead of adding any.
Why it is not left to push_back: both vectors are VectorWithMemoryTracking, so their growth is exactly where the memory-limit exception behind the reported abort is raised. Growing both first makes both appends non-allocating, so add either registers the block fully or throws before touching either vector. A throw between the two push_back calls leaves blocks one entry longer than row_stores, and from then on a block_no indexes the two inconsistently. They stay two separate arrays because the decode loops take blocksData() and rowStoresData() as spans.
The failpoint makes that throw reachable deterministically from SQL (in production it is the memory-limit exception inside registration), so the test can assert that the table contents, the right-side row count and the allocated-size accounting are unchanged after the failed INSERT.
If you would like the comment to name the capacity boundary, I will reword it and fold it into the next push rather than restart the CI run that is in flight.
Resolve the only conflict, in HashJoin::addBlockToJoin: 26.8 still increments data->rows_to_join right after computing the row count (master moved it later in #116991, which is not backported). Keep that line and take #121385's move of the key-column loop above the ASOF NULL filter unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
HashJoinright-side memory accounting when a memory limit interrupts a join build. A block could be stored without being counted, so the join under-reported its size to the memory limits and the spilling thresholds, and aJoinengine table held the memory of a failedINSERTfor the rest of its lifetime. In debug and sanitizer builds this surfaced later asLogical error: data->allocated_size != debug_allocated_size.Description
Investigated at @ alexey-milovidov's request in #112973 (comment):
Stress test (arm_tsan),Logical error: 'data->allocated_size != debug_allocated_size (0 != 36263)', report. Not caused by that pull request: none of its 42 changed files is undersrc/Interpreters/HashJoin/.Root cause.
HashJoin::addBlockToJoinkeepsdata->allocated_sizeequal to the sum overdata->columnsincrementally: it pushes the block, registers it withstored_columns_index->add(), and only then advances the counter.add()grows two memory-tracked vectors and is meant to throw at the limit, so a fault there leaves the block stored and uncounted.data->rows_to_join, incremented at the top of the function, leaks the same way.The change removes that window instead of unwinding it, as @ rschu1ze asked. The block is built in a local list, registered and accounted for, then moved into
data->columnswithsplice, which cannot throw;tryRerangeRightTableDataImplalready registers blocks held by a local list.addgrowsblocksandrow_storesbefore appending to either, so both appends are non-allocating and cannot leave the two different lengths. Nocatchblock remains. I do not touch~HashJoin: silencing the assertion there would hide the whole class.Scope. The
0 != Nshape only. The both-operands-non-zero shape (#111573) and theN != 0variant inreleaseJoinedBlocks(restructure = true)are different mechanisms, tracked by #99920.Validation. On master's ordering plus the failpoint, the second
INSERTaborts a debug server with(0 != 256)fromdoDebugAssertsviaaddBlockToJoin: the same assertion and the same left operand as the CI signature. With the change the test passes 5 of 5. Reserving exactly one entry per block would have made registration quadratic (1000 blocks: 1000 reallocations against 10), so the target doubles the shared size. Disclosed residual: the test does not distinguish the paired pre-reservation from two independent appends, because after the change neither append can fail; that half rests on the appends being non-allocating plus achasserton the two lengths.Workflow [PR]
Sync PR [sync-upstream/pr/116991]