Skip to content

Fix HashJoin right-side accounting when registering a stored block fails - #116991

Merged
harikrishnan94 merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-hash-join-stored-block-registration-accounting
Sep 7, 2026
Merged

harikrishnan94 merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-hash-join-stored-block-registration-accounting

Conversation

@groeneai

@groeneai groeneai commented Aug 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed HashJoin right-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 a Join engine table held the memory of a failed INSERT for the rest of its lifetime. In debug and sanitizer builds this surfaced later as Logical 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 under src/Interpreters/HashJoin/.

Root cause. HashJoin::addBlockToJoin keeps data->allocated_size equal to the sum over data->columns incrementally: it pushes the block, registers it with stored_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->columns with splice, which cannot throw; tryRerangeRightTableDataImpl already registers blocks held by a local list. add grows blocks and row_stores before appending to either, so both appends are non-allocating and cannot leave the two different lengths. No catch block remains. I do not touch ~HashJoin: silencing the assertion there would hide the whole class.

Scope. The 0 != N shape only. The both-operands-non-zero shape (#111573) and the N != 0 variant in releaseJoinedBlocks(restructure = true) are different mechanisms, tracked by #99920.

Validation. On master's ordering plus the failpoint, the second INSERT aborts a debug server with (0 != 256) from doDebugAsserts via addBlockToJoin: 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 a chassert on the two lengths.


Workflow [PR]
Sync PR [sync-upstream/pr/116991]

groeneai and others added 2 commits August 29, 2026 00:06
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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two independent reviews of this change (a cold reviewer and a separate model gate) over two
rounds, adjudicated against the recorded measurements. The second round found nothing.

❌ Blockers: none.

⚠️ Major, agreed and fixed

  • The regression test observed neither half of the fix. Raised independently by both reviews.
    doDebugAsserts checks allocated_size only, so it cannot see the rows_to_join relocation,
    and JoinSource::generate reads data->maps, so the uncounted block is invisible to a
    SELECT in either arm. Fixed by two additive arms: an EXPLAIN ANALYZE Right: rows
    assertion, which reads rows_to_join directly and works in release builds too, and a
    duplicate-key INSERT that drives the no-insert rollback into StoredColumnsIndex::clearEntry.
    Each of the three parts of the change was then reverted on its own and each is caught.
  • The reason recorded for the second hunk being untestable was incomplete. clearEntry writes
    row_stores[block_no] unconditionally behind a bound taken from blocks, so a desynchronised
    pair is reachable without a second failpoint. libc++ hardening is FAST for every ClickHouse
    build type other than Debug and FAST already checks element access, so the consequence is a
    process abort in a release build, not only a debug assertion and not a silent out-of-bounds
    write.
  • Three claims in earlier drafts of this description were refuted by the change's own
    measurements
    and corrected before publication: the pre-fix insert aborts the server rather
    than reporting an ordinary error; a Join engine table retains the failed insert's memory, not
    its rows, since the rows never reach the hash map; and the second hunk's release-build
    consequence is the abort above.

💡 Noted, not blocking

  • allocatedBytes() is read before the try, which is what makes the rollback's pop_back
    correct without a tombstone: the only statement left inside the try that can throw is the
    registration itself, so a caught throw means nothing was ever registered.
  • The pop-versus-null-tombstone asymmetry between the two rollbacks is intentional: a failed
    registration never returned a block number and inserted nothing, so reusing it is safe, while
    the no-insert path's number was already handed to the probe and must survive as a null entry.
    add() holds its mutex across the whole rollback, which matters because ConcurrentHashJoin
    assigns one shared index to all of its slots.
  • Also noticed while enumerating the invariant's carriers, and deliberately not part of this
    change: tryRerangeRightTableDataImpl registers each merged block as it is built but only
    swaps the list in at the end of the walk, so a throw partway through leaves dangling entries in
    the index. Different mechanism from the accounting bug fixed here, pre-existing, and I have not
    reproduced it, so I am not raising it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 29, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 29, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78c6887]

Summary: ✅


AI Review

Summary

This PR moves the HashJoin stored-block commit point so a failure in StoredColumnsIndex::add cannot leave a right-side block stored but unaccounted, hardens StoredColumnsIndex::add so its blocks and row_stores vectors grow together before either append, and adds a failpoint-based regression test for the failure path. I reviewed the current head, the full PR discussion, and the touched HashJoin / RowRefs code paths; I did not find a remaining correctness, concurrency, or evidence gap in the diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 78c6887.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT stored_columns_index_throw_on_add, a failing INSERT into a Join engine table, then a second INSERT. 100% on demand, no timing dependence. The natural CI trigger is not deterministic by arithmetic: add() is about 2 of the query's tens of thousands of allocations under memory_tracker_fault_probability=0.001, which is why a failpoint is needed.
b Root cause explained? Yes. HashJoin::addBlockToJoin maintains data->allocated_size == sum(allocatedBytes) incrementally: it pushes the block into data->columns, registers it via stored_columns_index->add(), then advances the counter. add() grows two memory-tracked vectors and is documented as meant to throw at the limit, so a memory-limit fault between those statements leaves the block stored and uncounted, giving 0 against live columns. Confirmed against the CI job's own symbolized throw stack.
c Fix matches root cause? Yes, at the source site: the counters are made atomic with the container mutation. I deliberately do not touch ~HashJoin; silencing the assertion there would be a symptom guard and would delete the CI signal for this whole class. The narrower "skip the assert while unwinding" variant would not even have fired: the destructor ran inside a catch after rethrow(), so std::uncaught_exceptions() was 0.
d Test intent preserved / new tests added? No existing test changed, and the new test is additive only: the failed-insert arm, the second insert and the 2 2 oracle are unchanged, and the reference gained one line and lost none. Each half of the fix now has its own live arm - the accounting relocation is observed through the Right: rows line of EXPLAIN ANALYZE, and the index hunk through a third insert whose duplicate ANY key drives StoredColumnsIndex::clearEntry. The test still reddens before the fix in every build where doDebugAsserts() is compiled in.
e Both directions demonstrated? Yes, on Build-ID-asserted binaries: six arms plus an attribution control. With the fix, OK and the reference matches. Both hunks reverted, and the accounting hunk alone reverted: the second insert reports data->allocated_size != debug_allocated_size (0 != 256) and the server aborts, the left operand matching the CI signature 0 != 36263. Relocation alone reverted: no abort, but Right: rows reads 2 instead of 1. Index hunk alone reverted: the server aborts with vector[] index out of bounds inside clearEntry, and the same build with the hunk restored passes. On a 91-test join-engine suite the pre-fix server aborted with the CI signature while the fixed server completed all 91.
f Fix is general across code paths? 12 sites of the four accounting invariants were enumerated; 2 were broken and both are fixed. SpillingHashJoin and GraceHashJoin have defaulted destructors and ConcurrentHashJoin wraps per-slot HashJoins, so all three are carriers of the symptom and all three are covered without a per-wrapper change, consistent with this signature appearing on arm_tsan, amd_tsan, arm_msan and azure amd_tsan. One further site is knowingly out of scope and named in the description: releaseJoinedBlocks(restructure = true), which is the opposite polarity and a second root cause.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect is counter bookkeeping and is independent of column types, wrappers and values: the window is entered once per stored block for every join algorithm and every right-side schema, and allocatedBytes() is type-agnostic. The test uses the smallest reachable case, one row in a fresh join, which is also the only shape that can produce the 0 != N operand pair.
h Backward compatible? Yes. No setting, no default, no serialization format and no on-disk change; SettingsChangesHistory.cpp untouched. Both new catch blocks rethrow, so no success path changes behaviour and no error is newly swallowed.
i Invariants and contracts preserved? The two repaired are data->allocated_size == sum(allocatedBytes over data->columns) and blocks.size() == row_stores.size() (the latter is asserted nowhere). data->rows_to_join was measured directly: after the failed insert it is back to 0 along with allocated_size and the column count, and system.tables reads identically before and after the failed insert, where total_bytes goes through getTotalByteCount() and therefore through the assertion. nullmaps_allocated_size is untouched. Locking is unchanged: the new try sits inside the existing lock_guard region and adds no lock, pop_back is noexcept, and the generation counter is skipped on the throw path, which is correct because nothing was added.

Session id: cron:clickhouse-review-slot-9:20260829-013900

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 29, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @KochetovNicolai, could you review this? HashJoin::addBlockToJoin pushed the block into data->columns and registered it with stored_columns_index->add() before advancing data->allocated_size, so a memory-limit fault inside add() left the block stored and uncounted, which is the 0 != N logical error seen on Stress tests; the fix commits the three right-side counters at one point and makes add() all-or-nothing.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78c688777 with master e568d262d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

10 translation units recompiled, 49 s compile time in total, 10 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 22e0df2

CI is fully finished at this commit. Two checks failed and both have an owner. The Style check failure from the previous commit is gone: Style check and Fast test are OK here.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / test_rename_column::test_rename_distributed_parallel_insert_and_select, test_insert_into_distributed::test_table_function, test_backup_restore_on_cluster/test_concurrency::test_replicated_table, Timeout the shard overran the two-hour pytest --session-timeout: its invocation ran 7244s against the 7200s budget, while sibling shards 1/6, 3/6, 4/6 and 5/6 finished in 5914s, 6707s, 6189s and 6547s. The three tests each hit the 900s per-test limit, with docker compose ... stop timing out after 300s and one clickhouse client query after 600s, on a node reporting peak RAM 99.7% of 61.78GB, 42% of runtime stalled on memory and 45% on IO. Not caused by this PR: the same binary passed shards 1/6, 3/6, 4/6 and 5/6 outright, and these three tests carry 1, 1 and 0 failure rows in other pull requests over 14 days and none on master. #116591 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) the shard was killed 50 minutes in, exit code: -9 at 04:21:33Z, on a node reporting peak RAM 99.5% of 61.78GB. It published 838 tests, all passing, and no failing test, so the job status is the entire failure. #112984 (ours, open)

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116991&sha=22e0df21fadeaa26d6af7d80ef55ec9130329c5b&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116991&sha=22e0df21fadeaa26d6af7d80ef55ec9130329c5b&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%206%2F6%29

Finish Workflow also reports FAIL, from new_tests_check.py concluding passed: none. That is the praktika aggregator and it carries no separate defect: both shards above are in CORE_BLOCKING_JOB_NAMES (ci/workflows/pull_request.py:48-51) and every later job is set_run_after them, so the three functional and unit Bugfix validation arms were DROPPED and no per-arch verdict could exist. The same cascade dropped 102 of the 176 praktika nodes. Fixing either shard death removes it.

Everything that ran is green: 46 OK praktika nodes, and 114891 rows in the CI database at this commit with exactly 4 failures, all of them in shard 2/6. For scale: Fast test 11189 OK, Stateless tests (amd_debug, parallel) 13209 OK, Stateless tests (arm_binary, parallel) 13329 OK, Unit tests (asan_ubsan) 20452 OK.

Session id: cron:our-pr-ci-monitor:20260829-063000

@rschu1ze

Copy link
Copy Markdown
Member

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Two things are checkable on master, and one thing I cannot back.

Checkable: data->columns.emplace_back publishes the block at HashJoin.cpp:942, data->allocated_size is advanced four lines later at :946, and the only fallible statement in between is StoredColumnsIndex::add. Its two containers are VectorWithMemoryTracking precisely so that they throw: "use the throwing memory tracker so a huge build fails the query at the limit instead of letting the process get OOM-killed" (RowRefs.h:489). A throw there leaves one block stored and uncounted, which is the data->allocated_size != debug_allocated_size (0 != N) text verbatim, with 0 because it is the first block. data->rows_to_join at :903 leaks the same way on every throwing statement before the commit point.

Cannot back: that this is the mechanism behind the 0 != 36263 assertion I was asked to investigate. On pristine master I could not land a real MEMORY_LIMIT_EXCEEDED inside add, either by sweeping max_memory_usage across the failing band (about 500 positions) or with memory_tracker_fault_probability; those two allocations are a vanishing fraction of the several thousand in the query. So the failpoint models the throw rather than provoking it, and attributing the CI report to this path is inference, not measurement.

On the shape you flagged: agreed. Reserving one more entry in both index vectors before :942 makes the registration non-allocating, so the commit point cannot throw and neither catch is needed. That is what I would push instead.

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 Stress test (arm_tsan) assertion stays open either way and I will keep after the mechanism.

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

LGTM

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Make the PR merge-ready

groeneai and others added 4 commits September 5, 2026 04:16
… 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]>
auto-merge was automatically disabled September 5, 2026 06:53

Head branch was pushed to by a user without write access

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Merge-ready at 39f7a33.

Both catch blocks are gone, which is what I said I would push. The block is built in a local list, registered and accounted for, then moved into data->columns with splice, which cannot throw; StoredColumnsIndex::add grows both index vectors before appending to either, so both appends are non-allocating. Reserving at the call site, the form I proposed on 08-31, is not enough on its own: the index is shared between the slots of a ConcurrentHashJoin, so another slot can take the reserved entry between the reserve and the add. Inside add, under the mutex that already serialises the appends, there is no such window.

One measurement I did not have on 08-31: with master's ordering and the failpoint, the test's second INSERT aborts a debug server with Logical error: 'data->allocated_size != debug_allocated_size (0 != 256)', raised by doDebugAsserts through addBlockToJoin. That is the same assertion and the same left operand as the report on #112973. It still does not prove the CI instance took this path, but the window is reproducible on demand now rather than argued.

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 chassert on the two lengths, not on an oracle.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 39f7a33

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) oracle false mismatch: both DQP arms read default.tmp, which 03322_initial_query_start_time_check.sql creates as a VIEW over initialQueryStartTime() and now(), so two executions of the same text legitimately return different values. The fuzzed query names only the view, so the oracle's non-deterministic-function gate, which matches function names in the query AST, never sees them. #117200 (external, open)

Mergeable Check and PR are aggregators of the row above, so they do not get their own lines.

Not caused by this PR, structurally: this diff is confined to HashJoin.cpp, RowRefs.cpp and
FailPoint.cpp, while the fuzzed query is SELECT it, t FROM default.tmp and contains no join, so
there is no path from the diff to an optimizer-dependent divergence. The same carrier also errored on
unrelated PR #91358 on 2026-09-03, and this oracle job errored on 3 to 12 distinct PRs per day over
the last 8 days with 0 occurrences on master.

Mergeable Check is red only because of that one job, so merging stays blocked until it is re-run
green or #117200 lands.

Session id: cron:our-pr-ci-monitor:20260905-120053

@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Merge with master and re-run the CI.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master at e568d262dc86ddfaa8a3f2016797c0b35e937206 and pushed 78c6887. The branch was 813 commits behind; CI is running on the new head.

The merge changes nothing that was approved: git diff origin/master HEAD has the same patch-id (d60c8e3e) and byte-identical +/- lines as 39f7a33, i.e. still the same 5 files, +66/-4. The only file master had also touched is FailPoint.cpp, where it added two failpoints next to mine.

If AST fuzzer (amd_release, oracle) comes back red, it is the same false positive as in the ledger above: the fuzzed query reads a view that selects initialQueryStartTime() and now(), so two executions cannot agree, and the oracle matches function names in the query AST without resolving views. #117200 would remove that check but has not landed, and the fuzzer seed is random.

/// 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())

@rschu1ze rschu1ze Sep 6, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit b706919 Sep 7, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
vdimir pushed a commit that referenced this pull request Nov 13, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants