Repository navigation
Cherry pick #112327 to 25.8: Fix use-after-free on a sparse join key in a direct dictionary join - #114796
Cherry pick #112327 to 25.8: Fix use-after-free on a sparse join key in a direct dictionary join#114796robot-clickhouse-ci-2 wants to merge 10 commits into
Conversation
…join getColumnVectorData materializes its key column into a function-local ColumnPtr and returns a PaddedPODArray reference into that local. It copied the data into the caller's backup_storage only when the input was Const. That was safe for a dense column, because every conversion is a no-op returning getPtr() and the caller's own ColumnPtr keeps the buffer alive. It is not safe when the column has to be materialized: ColumnSparse::convertToFullColumnIfSparse, ColumnReplicated::convertToFullColumnIfReplicated and the ColumnTuple branch of recursiveRemoveSparse each allocate a new column that nothing else owns, so the returned reference dangles as soon as the function returns. Take the copy whenever a conversion produced a different column (full_column.get() != column.get()). Pointer identity covers Const, Sparse, ColumnReplicated and Tuple nesting any of them with one predicate, and it is fail-closed for any representation added later. The previous Const check is strictly subsumed, because ColumnConst::convertToFullColumn returns either the inner column or a replicate result and never the ColumnConst itself. The dense path adds no copy: measured zero copies at both live call sites for a dense key and one copy at each for a sparse key. Reachable through IDictionary::getByKeys (join_algorithm = 'direct'), whose own removeSpecialRepresentations call sits inside a Nullable-only branch, so a non-Nullable sparse key passes through unmaterialized. The dictGet family cannot reach it because IFunction pre-converts sparse and replicated arguments. Two live sites today, both in FlatDictionary (hasKeys and getColumn); the other twelve are hierarchy-only and are fixed by the same change. Found by CI on #109225 and reproduced on unmodified master. Reported as an ASAN heap-use-after-free (allocated in ColumnSparse::convertToFullColumnIfSparse, freed at the end of getColumnVectorData, read in FlatDictionary::hasKeys) and as a PaddedPODArray bounds logical error from the same read. Adds 04652_direct_join_dictionary_sparse_key, which covers both live call sites, the aggregation shape from the report and a key carried through ARRAY JOIN over a sparse column. It pins results against a dense table and against join_algorithm = 'hash' rather than hand-written constants, and asserts that the key really is sparse and that DirectKeyValueJoin is still chosen so it cannot pass vacuously.
The previous fixture could not distinguish a correct lookup from one blind to the sparse default key 0. The dictionary attribute for key 0 was 0, which is exactly the value a LEFT JOIN miss writes, and the probe key range equalled the dictionary key range, so there were no absent keys at all: sum(r.v) was 380000 whether or not every key-0 row resolved. The mutation arm only proved the test catches the freed-memory abort, not a silently wrong result, which is what a release build produces. The dictionary attribute is now (key + 1) * 10, so r.v = 0 means unambiguously "key not found", and the probe range (25 keys) exceeds the dictionary range (20 keys), so real misses exist. The assertions pin the matched and missing row counts and key 0's real attribute value. Each new assertion was verified to be load-bearing by re-running against a dictionary that deliberately omits key 0: every asserted number changes. The serialization guard now covers both sparse tables and asserts presence of the Sparse kind per table rather than reading a single distinct value, so it survives a multi-part fixture and pins the sparse base of the ARRAY JOIN case too. Writing either table densely on purpose makes it fail. The ARRAY JOIN comment no longer claims the query distinguishes lazy from eager replication: ColumnSparse::replicate returns a ColumnSparse, so both arms hand a materializing column to the helper. What the row exercises is a key carried through ARRAY JOIN over a sparse base column. No change to src/.
…urate comment The test distinguishes a dictionary hit from a miss by the attribute value, so the representation of a miss has to be fixed. With join_use_nulls = 1 the right attribute becomes Nullable and a miss is NULL instead of the type default 0, and countIf counts a NULL condition as false, so the two lines counting misses would report 0. The Stress check injects join_use_nulls = 1 on every third thread via --client-option, which wins over the runner's randomized settings, so this was reachable deterministically rather than as a coin flip. Pin the setting at file level, as 71 other stateless tests already do. No fixture, query or reference value changes. The comment above the copy guard claimed that a differing pointer proves full_column is the data's only owner. That is not true for a one-row ColumnConst: ColumnConst::convertToFullColumn returns the inner column unchanged when size is 1, and that member is kept alive by the caller's own ColumnPtr. The guard is still correct, since copying there is conservative and on a cold path, so only the wording changes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The regression test asserted sum(r.v) over the joined result and compared that total against the dense-key and hash-join runs. Every present key in the fixture appears the same number of times (160 rows each, 25 keys), so any lookup bug that permutes attribute values among the present keys while leaving key 0 and the miss set alone preserves the total, preserves the hit/miss counts, and preserves both cross-checks (the permutation applies to both sides of each comparison). Measured: with the dictionary source mutated to a sum-preserving permutation of its values, differing on 18 of 19 keys, the test produced output byte-identical to the reference. Each attribute-read row now also counts the rows whose value equals the one belonging to their own key, and the two cross-checks compare the whole grouped (key, value, count) mapping instead of a total. Grouping by both columns also surfaces a key whose rows disagree with each other. The use-after-free arm is unchanged: reverting the getColumnVectorData predicate to the Const-only form still aborts the test while producing the same reference line as before.
hasKeys is the function that read the freed buffer, and its result is the presence mask. getByKeys applies that mask to the returned right key column only: attributes are fetched independently, and with join_use_nulls = 0 they are not nullable, so nothing else in a LEFT ALL JOIN reflects the mask. The test referenced only l.j and r.v, so a completely wrong mask produced the expected output. Verified by forcing the mask to report every row as present: the previous assertions did not move at all. The presence row now also counts, per row, that a present key returns its own key and an absent key returns the blanked default.
Key 0 is the sparse default of the fixture and therefore the key the test cares about most, but a right key blanked for an unmatched row is also 0, so r.j = l.j holds whether or not the presence mask found it, and the attribute is fetched independently and returns its value either way. Verified by making hasKeys report key 0 absent: nothing in the test moved. Under join_use_nulls = 1 an unmatched row yields NULL for the right key, which distinguishes the two cases, so the new statement asks for that value with a statement-level SETTINGS clause. That keeps it independent of both the file-level pin and the setting the Stress check injects.
A Tuple column never reaches the ownership branch, because the ColumnVector<T> check above it throws first: recursiveRemoveSparse preserves the outer ColumnTuple. The predicate is unchanged, only the carrier list in the comment was wrong. The presence-row comment claimed its two right-key counts catch any mask error. They do not catch a lost key 0, whose blanked right key is also 0; that is what the nullable-key statement below them is for. Comment text only, no code token changed.
…se-key-dangling-podarray
…ngling-podarray Fix use-after-free on a sparse join key in a direct dictionary join
|
This cherry-pick conflicts in The conflict is that
Leaving this PR open for whoever owns the automation to close or supersede - I have not touched its |
|
Dear @alexbakharew, @groeneai, this cherry-pick PR has not been updated for 3d0h8m13s. Please resolve the conflicts to backport #112327, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity. |
Backport of ClickHouse#112327 to 25.8. The robot cherry-pick (ClickHouse#114796) conflicts in src/Dictionaries/DictionaryHelpers.h because the materializing call in getColumnVectorData is removeSpecialRepresentations on master and recursiveRemoveSparse here; removeSpecialRepresentations does not exist on this branch. The resolution keeps 25.8's call and takes the fix's predicate, so the resolved change is the same 8 insertions and 7 deletions as the merged commit. 25.8 is affected. On the official 25.8.30.17 binary the amplified repro (a 2M-row sparse probe joined to a FLAT dictionary with join_algorithm = 'direct') segfaults in 2 of 7 runs, and with jemalloc junk filling it fails 4 of 4 with "Invalid number of rows in Chunk ... expected 65409, got 0". Writing the same data densely passes. A value comparison alone cannot see this: freed but intact memory still returns the right numbers, which is why both arms agreed until the freed page was poisoned. Verified in both directions with a clang-19 Debug build, 25.8's pinned compiler, build ids asserted against the running server. The pristine branch aborts on the first assertion of the ported test, at PODArray::operator[] inside FlatDictionary::hasKeys reached through IDictionary::getByKeys and DirectKeyValueJoin::joinBlock, which is the mechanism reported on master. With the fix the test passes and the repro returns the correct result 3 of 3 runs. The test carries one branch adaptation: enable_lazy_columns_replication does not exist on 25.8 and is rejected as an unknown setting, so it is dropped from the ARRAY JOIN statement. The statement and every assertion are kept. The comment drops ColumnReplicated from the carrier list because that class does not exist here. Co-Authored-By: Claude Opus 5 <[email protected]> The test comments describe what each statement asserts at the SQL level and no longer name C++ functions or classes, per the review of the master commit. The statements and the reference are unchanged: stripping comments from both revisions yields byte-identical SQL (md5 5a88d22c5d3f4aedbdeb8befef6c0ef9), and both format to the same AST.
|
Dear @alexbakharew, @groeneai, this cherry-pick PR has not been updated for 7d0h5m12s. Closing automatically. If you still want to backport #112327, please resolve the conflicts and reopen this PR. |
Original pull-request #112327
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job