Repository navigation
Conversation
Set::appendSetElements appends into set_elements, a retained member, with a bare non-atomic insertRangeFrom. A JOIN runtime filter keeps its Set and reads the collected elements back when the build-side filters are merged, so a throw in the middle of that append is not confined to the failing query step: it leaves a column behind whose nested data and offsets disagree. For an Array(Variant(...)) element type the window is concrete. ColumnArray::insertRangeFrom reserves its offsets, grows the nested column, and appends its own offsets last, while ColumnVariant::size() is offsets->size() and ColumnVariant::insertRangeFromImpl grows local_discriminators and offsets in its first loop before filling the variants in its second. A MEMORY_LIMIT_EXCEEDED in that second loop therefore leaves the nested column reporting its post-append length while the outer ColumnArray's offsets still hold the pre-append total. Reading that column back raises "offsets_column has data inconsistent with nested_column" from the validating ColumnArray constructor, reached through ExactSetRuntimeFilter::mergeFrom -> insert -> Set::insertFromColumns -> convertToFullIfWrapped, which in a debug or sanitizer build aborts the server. Take a checkpoint of every element column before any modification and roll them all back on the way out, in the shape of StorageBuffer::appendBlock. Two deliberate simplifications against that precedent: rollback on an untouched column is a no-op, so no mutated-column counter is needed, and set_elements owns its columns uniquely, so nothing is ever moved out and back and no "no column to rollback" check is needed. The empty-element branch replaces the column instead of appending to it, so the replaced column is kept and restored by move rather than by checkpoint. Rolling back all keys also removes the cross-key length skew a throw at key i used to leave behind for a multi-column set.
The failure needs a race that SQL cannot force. A mid-append throw makes the
throwing BuildRuntimeFilterTransform bail out of work() early, so it wins the
finish race and RuntimeFilterLookup::add registers ITS filter, i.e. the
corrupted filter becomes the merge destination, and RuntimeFilter::merge only
ever reads the source's values column, so a corrupted destination is never
validated. 2500 iterations of the best fault-injection configuration found
(1352 faulted queries, 594 faults inside appendSetElements, 48 of them below
insertRangeFrom) produced no occurrence, so a stateless test here would be an
oracle that cannot fail.
This gtest drives the public Set::insertFromColumns with an
Array(Variant(String, UInt64)) element type, in the shape of the neighbouring
gtest_set_variants_init_exception_safety.cpp. Three properties are load-bearing:
- Both variant kinds are present in every array. With one non-empty variant
and no NULLs, ColumnVariant::insertRangeFromImpl takes the fast path, which
inserts into the variant before growing its offsets and therefore leaves no
window.
- The payload is large in bytes and small in rows, so one memory hard limit
sized in bytes selects the append over the filter() copy that precedes it
in the same loop iteration. Measured separation: a 32 MiB copy against a
128 MiB grow, with the limit set 64 MiB above the amount at arming.
- Two batches are collected with the limit lifted, so the third one has to
grow a buffer that is already full.
Without the rollback the test fails through the same frames as the recorded
stack, with
offsets_column has data inconsistent with nested_column. Data size: 192, last offset: 128
Two assertions beyond the structural one. The propagated exception's code,
because the rollback's contract is to rethrow the original rather than raise one
of its own. And the set's row count, because the hash table is filled before the
values are collected, so a full count shows the refusal landed in the collecting
step rather than in a step before it. The row count bounds the window from one
side only: it places the refusal after the hash table was filled, i.e. inside
appendSetElements, and does not by itself exclude the filter() copy in the same
loop iteration, which stays bounded by the measured separation above.
No build-system change is needed or wanted: src/CMakeLists.txt collects unit
tests with a recursive gtest*.cpp glob.
Co-Authored-By: Claude Opus 5 <[email protected]>
Set.cpp: drop the narration of the new rollback's own design and of the log/lock ordering; keep the pre-existing invariants (set_elements outlive a failed append, a checkpoint binds to its column, a failed rollback must not leave incorrect state) at the density of the StorageBuffer::appendBlock precedent.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). Two full passes plus one fix
What I checked rather than assumed, since the value of this pass is in the negatives: the rollback On whether a new gtest of this shape can be flaky, which is the fair question to ask of a One correction to my own first pass, since it is load-bearing for the question in the description: I Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260924-043500 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260924-041400 |
|
Workflow [PR], commit [14586fc] Summary: ❌
AI ReviewSummary
Final VerdictStatus: ✅ Approve. No required changes. |
Build profile diff (arm_release)Commit See the job log for details. |
`Unit tests (amd_llvm_coverage)` failed the assertion that the set's hash table
holds every row of the refused batch:
gtest_set_elements_rollback_exception_safety.cpp:116
set.getTotalRowCount() Which is: 64
3 * rows_per_batch Which is: 96
The count is short because the refusal arrived before the batch reached the
collection step, so the rollback under test never ran. That assertion exists to
catch exactly this, and every other assertion in the test held.
The cause is not the coverage build. The test armed a hard limit on the
process-wide memory tracker, which every thread of the test binary reports into,
and the 28980 unit tests run sequentially in one process: a pool left running by
an earlier test can spend the headroom between arming the limit and the append.
Allocating 96 MiB on another thread inside that window reproduces it on a debug
build, with getTotalRowCount() coming back 64 instead of 96, the CI signature
exactly. So the test was fragile on every build and coverage is only where it
landed.
The limit is now armed on this thread's own tracker, which no other thread
reports into, and the unit-test process leaves the process-wide limit unset, so
nothing else enforces one. The refused batch also drops from 32 values of 1 MiB
to 4 of 16 KiB: it only has to reach past the end of the buffer holding the
collected values, which leaves growing that buffer as the only allocation the
limit can refuse. Measured headroom window for the refusal landing on that
growth: 1 MiB to 128 MiB, against 48 MiB to 160 MiB before, with the limit now
at 32 MiB rather than at the old window's lower edge.
That also closes a way for this test to pass without testing anything: with the
large refused batch, any headroom below 48 MiB made the filter() copy preceding
the append the refused allocation, which leaves the collected values untouched
and all of the assertions holding.
src/Interpreters/Set.cpp is unchanged. Passes with the fix (--gtest_repeat=20,
20/20); without it exits 134 on "Data size: 136, last offset: 128"; with the
rollback loop body removed it fails identically; and the rollback's own logged
frames are Allocator::realloc <- ColumnString::doInsertRangeFrom <-
ColumnVariant::insertRangeFromImpl <- ColumnArray::doInsertRangeFrom <-
Set::appendSetElements.
Co-Authored-By: Claude Opus 5 <[email protected]>
|
|
||
| size_t rows = holder.key_columns.at(0)->size(); | ||
| for (size_t i = 0; i < keys_size; ++i) | ||
| try |
There was a problem hiding this comment.
It should be fine to get an exception here; why should it be propagated up across the stack and cancel the query, like any other exception in other places?
There was a problem hiding this comment.
Two questions in one, and they have different answers.
Why the exception is caught at all. A plain exception propagated up the stack is what master already does: there is no try in appendSetElements on master (src/Interpreters/Set.cpp:274-291, bare insertRangeFrom at :287), and the query already fails with MEMORY_LIMIT_EXCEEDED. That is the state STID 2632-398f is reported from, so propagation on its own is not enough. What master leaves behind is a half-appended set_elements, and those columns outlive the frame that threw, because the Set is owned by the per-query runtime_filter_lookup. The abort then comes out of ColumnArray's own consistency check (src/Columns/ColumnArray.cpp:66-69) when the elements are read back, not while they are appended: the reported stack is ExactSetRuntimeFilter<false>::insert <- RuntimeFilter::merge <- RuntimeFilterLookup::add <- BuildRuntimeFilterTransform::prepare, and that merge reaches them through source.getValuesColumn() -> getSetElements().front(). So propagating the first exception demonstrably does not prevent the second read.
The new gtest is that end to end: with Set.cpp reverted it aborts with Data size: 136, last offset: 128, with the fix it passes, and with the rollback loop body replaced by (void)i; it aborts again. So the try buys the object invariant, and the throw; only keeps master's control flow unchanged.
Whether the query should die at all. Fair question, but it cannot be answered here: appendSetElements is shared by PreparedSets.cpp:179,197 (IN sets), CreateSetAndFilterOnTheFlyTransform.cpp:117 and RuntimeFilterLookup.cpp:361, and swallowing at this level would hand the index-analysis consumers a silently short set_elements instead of a failed query.
For the runtime filter alone it is reasonable, and the layer already has the mechanism: ExactSetRuntimeFilter::finishInsert(RuntimeFilterEvaluationState &) calls markKeySetDropped() plus releaseExactValues() when the exact set outgrows its limit, and a build that hit the memory limit is the same category. If you want the filter to fail open rather than fail the query, I will add it there and not in Set. That is the incomplete-build fence the PR body asks about; #120940 tried the transform-guard version and was closed unmerged, and this Set-level shape is what @ alexey-milovidov asked for on #119545 afterwards. Say which you prefer, and whether it belongs in this PR or on top of it.
CI finish ledger - 2cad1d1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Why #121937 owns it, measured rather than assumed. praktika pinned this run's tree at For the record, the other merged gate fix in this family, #121847, WAS present in the failing tree This PR's own diff cannot reach the flagged query: it changes Session id: cron:our-pr-ci-monitor:20260924-143221 |
CI finish ledger - 0739d7dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Gates (a) to (d): 0 of 172 check runs queued or running (144 pass, 25 not selected, 3 fail), Master merge deliberately not pushed: no fix exists yet to pick up, and the reference build is Session id: cron:our-pr-ci-monitor:20260924-200137 |
|
The fixing-PR link I promised in the ledger for
Investigating that class did surface a separate live defect on the same The other two rows need no fix PR either. Session id: cron:our-pr-ci-monitor:20260925-053135 |
|
I agree with @vdimir, this is all terrible. Exceptions must bubble up unless there is a very good reason (destructor, noexcept). |
Related: #119545
Related: #120940
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Collecting the values of a JOIN runtime filter (
enable_join_runtime_filters) is now all-or-nothing: if an allocation fails part way through, the values collected so far are restored. A JOIN that exceeds a memory limit now reports that limit, instead of an internalLOGICAL_ERRORabout inconsistent column offsets.Description
enable_join_runtime_filtersis on by default, soExactSetRuntimeFiltersits on the ordinary JOIN path. It collects its values throughSet::appendSetElements, which appended into a retained member with no rollback.ColumnArray::insertRangeFromgrows the nested column before appending its own offsets, so an allocation failure in the middle left theSetholding a column whose nested data and offsets permanently disagree. Nothing restored it, and the next reader (getValuesColumn->convertToFullIfWrapped) raisedLOGICAL_ERROR: offsets_column has data inconsistent with nested_column. CI hit it twice on code-disjoint carriers: 2026-09-18 and 2026-09-23.appendSetElementsnow checkpoints every element column before any mutation and rolls back on failure, in the shape ofStorageBuffer::appendBlock(prior art: #43338). One function, one include, no setting, no ABI change; the success path only gains a checkpoint per element column. The regression test is a gtest and not a stateless test because the failure needs a race between two build-side transforms that SQL cannot force (no occurrence in 2500 fault-injection iterations).Improvementand notBug Fix: on a stock release the symptom is a confusing internal error in place ofMEMORY_LIMIT_EXCEEDED, because the abort needs a debug or sanitizer build, or the expert-onlyabort_on_logical_error.One question. The collected values are now consistent, but the filter may still be partial: master already publishes a partial filter from paths this PR does not touch (the target-type cast before the insert; an upstream exception reaching the transform's no-op hook), and a failed build's min/max range is only a prefix. I left that fence out, since it is what #120940 attempted. Do you want it here? About four files: mark an incomplete build at the
BuildRuntimeFilterTransformboundary, inherit the mark on merge, and havefinishInsertdrop the key set.Validation, and two deliberate simplifications of the precedent
New deterministic gtest,
src/Interpreters/tests/gtest_set_elements_rollback_exception_safety.cpp, oneTEST, 139 lines, mirroring the tree's owngtest_set_variants_init_exception_safety.cpp(79 lines, oneTEST, same directory, same defect class). It drives the publicSet::insertFromColumnswith anArray(Variant(String, UInt64))element type, collects two batches with no limit in force, then arms a hard limit on its own thread, sized so appending a tiny third batch has to grow the collected values and fails.Logical error: 'offsets_column has data inconsistent with nested_column. Data size: 136, last offset: 128', with the same frames as the CI stack (ColumnArrayctor <-convertToFullIfWrapped).--gtest_repeat=20-> 20/20.try/catch.Allocator::realloc<-ColumnString::doInsertRangeFrom<-ColumnVariant::insertRangeFromImpl<-ColumnArray::doInsertRangeFrom<-Set::appendSetElements.RuntimeFilterLookup,SetVariantsandMergeTreeSetIndexsuites stay green; clang-tidy is clean.Two deliberate simplifications of
StorageBuffer::appendBlock, so this is not read as an incomplete copy: there is nomutated_columnscounter, because rolling back to the current size is a no-op andset_elementsnever has columns moved out of it; and there is no "no column to rollback" check, because the empty-column branch evaluatesIColumn::mutateinto a local before touchingset_elements[i], so that element is never observably null on any path.Workflow [PR]
Sync PR [sync-upstream/pr/121898]