Repository navigation
Fix MSan use-of-uninitialized-value in JOIN-conversion partial evaluation (issue #100469, STID 1499-4a82) - #103880
Conversation
…unctions The query-plan JOIN-conversion optimizers `tryConvertAnyOuterJoinToInnerJoin` (`Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp`) and `tryConvertAnyJoinToSemiOrAntiJoin` (`convertAnyJoinToSemiOrAntiJoin.cpp`) call `filterResultForNotMatchedRows` / `filterResultForMatchedRows` to decide whether the filter is always FALSE for synthetic default-input rows. They use `ActionsDAG::evaluatePartialResult` with `skip_materialize=true`, which routes each FUNCTION node through `IFunction::executeImplDryRun`. The dry-run override of `rowNumberInAllBlocks` (and structurally similar non-deterministic functions) returns `ColumnUInt64::create(input_rows_count)` without filling the buffer. The optimizer then reads it via `getFilterResult` -> `getBool(0)`, producing two failure modes: 1. MemorySanitizer reports a use-of-uninitialized-value (issue ClickHouse#100469, STID 1499-4a82). 2. The optimizer makes a JOIN-conversion decision based on a garbage byte: when the byte happens to be 0 (FALSE), an `ANY OUTER JOIN` is silently converted to `INNER JOIN` (or an `ANY JOIN` to `SEMI`/`ANTI JOIN`), dropping rows that should have been kept. Even with initialized dry-run output, the optimizer's reasoning is unsound for non-deterministic functions: a single plan-time evaluation of `rand` or `rowNumberInAllBlocks` cannot represent the per-row runtime behaviour. Add `dagContainsNonDeterministicFunction` (parallel to the existing `dagContainsNonReadySet`) and call it from both partial-evaluation entry points. When the filter (or pre-actions) DAG contains any function whose `isDeterministic()` returns false, return `FilterResult::UNKNOWN` and leave the JOIN unchanged. Add a regression test covering ANY LEFT/RIGHT JOIN with `rowNumberInAllBlocks` and `rand` in the filter, plus PedroTadim's original simplified reproducer. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=77138227a27144afc763833bd59a93560bd193d4&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_msan%29 Closes: ClickHouse#100469
|
Pre-PR validation gate (TASK.md Phase 4 Step 9)
Session: |
|
cc @KochetovNicolai @novikd @vdimir — could you review this? Adds a |
|
Workflow [PR], commit [fabc9bd] Summary: ✅ AI ReviewSummaryThis PR fixes JOIN-conversion partial-evaluation behavior for non-deterministic functions and addresses the ClickHouse Rules
Final Verdict
|
| if (dagContainsNonReadySet(filter_dag)) | ||
| return FilterResult::UNKNOWN; | ||
|
|
||
| /// If the filter DAG contains non-deterministic functions (e.g. `rand`, `now`, `rowNumberInAllBlocks`), |
There was a problem hiding this comment.
now is deterministic in the scope of query, which means - it should work fine.
There was a problem hiding this comment.
Right — now is isDeterministicInScopeOfQuery() == true even though isDeterministic() == false. My old guard used isDeterministic and would have filtered now out as well, which was overly broad. With the function-level fix in eba94a4e3996 the guard is gone entirely, so now (and today/yesterday/currentUser/etc.) flow through partial evaluation as before.
|
|
||
| /// If the filter DAG contains non-deterministic functions (e.g. `rand`, `now`, `rowNumberInAllBlocks`), | ||
| /// we cannot soundly predict the filter result from default-input rows. Some such functions also produce | ||
| /// uninitialized data in their dry-run path (e.g. `rowNumberInAllBlocks::executeImplDryRun` returns a |
There was a problem hiding this comment.
Fix the root cause - the functions should never produce uninitialized data.
There was a problem hiding this comment.
Done — eba94a4e3996 fixes rowNumberInAllBlocks::executeImplDryRun to fill the output column with zeros (was allocating without filling), and db3cc22ee20d removes this whole guard since it is no longer needed. Audited every other executeImplDryRun override (sleep.cpp, in.cpp, UserDefinedWebAssembly.cpp, IFunctionAdaptors.cpp) — none of them produce uninitialized data; rowNumberInAllBlocks was the only contract violation.
|
@groeneai, check review comments. |
The dry-run override for rowNumberInAllBlocks allocated a ColumnUInt64 of input_rows_count rows but never filled the buffer. Callers such as ActionsDAG::evaluatePartialResult (used by the JOIN-conversion optimizers in Processors/QueryPlan/Optimizations/Utils.cpp via filterResultForNotMatchedRows / filterResultForMatchedRows) then read the column via IColumn::getBool, which MemorySanitizer flagged as use-of-uninitialized-value (issue ClickHouse#100469, STID: 1499-4a82). Fix at the source: fill the dry-run output column with zeros, keeping the contract that any returned column is fully initialized. The global rows counter is intentionally not bumped, since the dry-run path must have no side effects.
Per maintainer review on PR ClickHouse#103880: the previous commit fixes the MemorySanitizer report at the source by ensuring rowNumberInAllBlocks::executeImplDryRun returns a fully-initialized column. The dagContainsNonDeterministicFunction guard added to filterResultForNotMatchedRows / filterResultForMatchedRows is no longer needed for the MSan finding -- callers of executeImplDryRun can safely read the result without sanitizer noise. Revert the helper and the two call-site checks. The test SQL is kept as a regression for issue ClickHouse#100469 and is updated to describe the function-level fix.
|
@alexey-milovidov — root-cause fix applied per your review. Two new commits on top of the previous one:
The fix (one line, plus a comment): // src/Functions/rowNumberInAllBlocks.cpp
ColumnPtr executeImplDryRun(... size_t input_rows_count) const override
{
return ColumnUInt64::create(input_rows_count, 0); // was: create(input_rows_count) — uninitialized
}The dry-run override is preserved so the global Audit of all
Only Verification (debug build):
Diff is now 91 lines added across 3 files (function fix + the test that was already there). Re. your other comment about Session: cron:clickhouse-ci-task-worker:20260502-001500 |
Even with `rowNumberInAllBlocks::executeImplDryRun` returning a fully initialized `[0]` column (commit `eba94a4e3996`), the JOIN-conversion optimizers (`tryConvertAnyOuterJoinToInnerJoin` / `tryConvertAnyJoinToSemiOrAntiJoin`) cannot soundly predict the per-row runtime behaviour of a non-deterministic filter from a single dry-run row. For a filter such as `rowNumberInAllBlocks() = 1`, the dry-run row evaluates to `0 = 1` -> FALSE; the optimizer concludes the filter is FALSE for all not-matched rows and silently converts `ANY LEFT JOIN` to SEMI/INNER JOIN, dropping rows that would have survived at runtime. This was flagged by `clickhouse-gh[bot]` in the inline review on `04149_msan_join_optimizer_non_deterministic_filter.sql` after the previous guard-removal commit (`db3cc22ee20d`). Re-add `dagContainsNonDeterministicFunction` (parallel to the existing `dagContainsNonReadySet`) and call it from both partial-evaluation entry points (`filterResultForNotMatchedRows` in `Utils.cpp` and `filterResultForMatchedRows` in `convertAnyJoinToSemiOrAntiJoin.cpp`). When the filter (or pre-actions) DAG contains any function whose `isDeterministic` returns false, return `FilterResult::UNKNOWN` and leave the JOIN unchanged. Extend the regression test with the bot's requested case for both `ANY LEFT` and `ANY RIGHT`: a filter that is FALSE on the 1-row dry-run but TRUE for some runtime row (`rowNumberInAllBlocks() = 1`). The new assertions count the surviving rows rather than the specific row to stay robust under randomized thread settings (the value of `rowNumberInAllBlocks` depends on per-stream block ordering). Without the guard the count drops from 1 to 0. The earlier function-level fix at the source (`rowNumberInAllBlocks.cpp`) addresses the MemorySanitizer `use-of-uninitialized-value` report; this commit addresses the separate correctness concern that the optimizer's plan-time evaluation of non-deterministic functions is unsound regardless of memory initialization. Closes: ClickHouse#100469
Per @alexey-milovidov's review on PR ClickHouse#103880: > "now is deterministic in the scope of query, which means - it should work fine." Switch the new `dagContainsNonDeterministicFunction` helper from `isDeterministic()` to `isDeterministicInScopeOfQuery()` so that `now`/`today`/`yesterday`/`currentUser` etc. -- which return the same value for every row inside a single query -- continue to flow through the partial-evaluation chain in `tryConvertAnyOuterJoinToInnerJoin` and `tryConvertAnyJoinToSemiOrAntiJoin`. Functions whose per-row output varies even within one query (`rand`, `rowNumberInAllBlocks`, `blockNumber`, `nowInBlock`, `generateSerialID`, ...) still bail out to `FilterResult::UNKNOWN` -- the optimizer's single plan-time evaluation of those is not representative of the runtime behaviour. Verified locally: * `now() < toDateTime('1900-01-01')` filter still triggers `ANY LEFT JOIN -> SEMI JOIN` conversion (the filter is constant-folded to FALSE for not-matched rows, no correctness issue). * `rand() < 0` filter keeps `Strictness: ANY` (the optimizer correctly declines to reason from a single plan-time `rand()` call).
|
@alexey-milovidov — addressed your review and the follow-up bot review. Summary The MSan fix from After that commit, the bot caught a separate correctness issue: even with the dry-run output initialized to New commits on top:
Verified locally:
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=77138227a27144afc763833bd59a93560bd193d4&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_msan%29 Session: cron:clickhouse-ci-task-worker:20260502-011500 |
|
|
||
| /// `ActionsDAG::evaluatePartialResult` (called below) routes every function node through | ||
| /// `IFunction::executeImplDryRun` with `input_rows_count=1`. For non-deterministic functions | ||
| /// (`rand`, `now`, `rowNumberInAllBlocks`, ...) this single dry-run row is not representative |
There was a problem hiding this comment.
now looks misleading in this list: this guard relies on isDeterministicInScopeOfQuery, and now is deterministic in query scope (so it should not trigger the bailout).
Could we replace now with something like nowInBlock here (or otherwise clarify the wording) to keep this comment consistent with dagContainsNonDeterministicFunction?
…c_filter The regression test exercises the planner-based JOIN-conversion optimizers in `Processors/QueryPlan/Optimizations/`. The old analyzer does not run those optimizers, and it additionally rejects `PedroTadim`'s reproducer shape `WHERE (SELECT p = 1) AND ...` with `UNKNOWN_IDENTIFIER` in `TreeRewriter::collectUsedColumns`, causing the test to fail under `Stateless tests (..., old analyzer, ...)` jobs (e.g. amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel). Force the new analyzer for this test (`SET enable_analyzer = 1;`), matching sibling JOIN-conversion regression tests `03130`, `03210`, `03595`, `03623`, `04003`. Verified locally: 30 passes under old analyzer mode + 30 passes under new analyzer mode (full random settings). Issue: ClickHouse#100469
The guards in `filterResultForNotMatchedRows` and `filterResultForMatchedRows` use `isDeterministicInScopeOfQuery`, so functions like `now` / `today` / `currentUser` (deterministic within a single query) do NOT trip the bailout. The previous comments listed `now` alongside `rand` / `rowNumberInAllBlocks` in the per-row-variable group, which contradicted the predicate. Replace `now` with `nowInBlock` (genuinely per-row variable) and explicitly call out the in-scope-deterministic functions as a separate group. No behavior change.
|
Two follow-up commits addressing the new CI failure and the bot wording nit:
The PR-monitor cron flagged a 3/3-rerun failure of The MSan/soundness fix lives entirely in the planner-based path ( Verification (local debug build):
CIDB cross-PR check confirmed the failure was isolated to PR #103880 — i.e. caused by our new regression test file under old analyzer.
Pure comment fix in No behavior change. Branch tip: |
|
@groeneai, update the branch to fix tests that were temporarily broken on master. |
…filter Pick up CI test fixes that were temporarily broken on master, per @alexey-milovidov directive on PR ClickHouse#103880. Issue: ClickHouse#100469
|
@alexey-milovidov — branch updated with current master at 1c611db to pick up the CI test fixes. New PR HEAD: fabc9bd. CI is running on the merged HEAD now. Session: cron:clickhouse-ci-task-worker:20260505-184500 |
LLVM Coverage Report
Changed lines: 100.00% (18/18) · Uncovered code |
bc601b5
…1499-4a82-msan-non-deterministic-filter Fix MSan use-of-uninitialized-value in JOIN-conversion partial evaluation (issue ClickHouse#100469, STID 1499-4a82)
The query-plan JOIN-conversion optimizers
tryConvertAnyOuterJoinToInnerJoin(inProcessors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp) andtryConvertAnyJoinToSemiOrAntiJoin(convertAnyJoinToSemiOrAntiJoin.cpp) callfilterResultForNotMatchedRows/filterResultForMatchedRowsto decide whether the filter is always FALSE for synthetic default-input rows. Both helpers go throughActionsDAG::evaluatePartialResultwithskip_materialize=true, which routes each FUNCTION node throughIFunction::executeImplDryRun.The dry-run override of
rowNumberInAllBlocksreturnsColumnUInt64::create(input_rows_count)and never fills the buffer, so the optimizer's subsequentgetFilterResult->getBool(0)reads uninitialized memory. This produces two failure modes:ANY OUTER JOINis silently converted toINNER JOIN(or anANY JOINtoSEMI/ANTI JOIN), dropping rows that should have been kept.Even with initialized dry-run output, the optimizer's reasoning is unsound for non-deterministic functions: a single plan-time evaluation of
randorrowNumberInAllBlockscannot represent the per-row runtime behaviour. The fix addsdagContainsNonDeterministicFunction(mirroring the existingdagContainsNonReadySetguard) and calls it from both partial-evaluation entry points; when the filter (or pre-actions) DAG contains any function whoseisDeterministicreturns false, the helpers returnFilterResult::UNKNOWNand the JOIN is left unchanged.Regression test
04149_msan_join_optimizer_non_deterministic_filter.sqlcoversANY LEFT/ANY RIGHT JOINwithrowNumberInAllBlocksandrandin the filter, plus PedroTadim's original simplified reproducer. Verified locally on debug build (30/30 runs) and existing JOIN-conversion tests03130_convert_outer_join_to_inner_join,03210_convert_outer_join_to_inner_join_any_join,03836_array_join_in_filter_partial_evaluation,04003_array_join_in_filter_outer_to_inner_join,04104_any_join_semi_anti_not_ready_setcontinue to pass.CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=77138227a27144afc763833bd59a93560bd193d4&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_msan%29
Closes #100469.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a use-of-uninitialized-value in the JOIN-conversion query plan optimizers (
tryConvertAnyOuterJoinToInnerJoin,tryConvertAnyJoinToSemiOrAntiJoin) when the filter on top of anANYOUTERJOINcontains a non-deterministic function such asrand,now, orrowNumberInAllBlocks. The optimizer no longer attempts to constant-fold such filters and leaves the JOIN unchanged, which also prevents incorrect conversions toINNER/SEMI/ANTI JOINthat could silently drop rows.Documentation entry for user-facing changes
Version info
26.5.1.321