Repository navigation
Enforce invariant that ActionsDAG::Node::column is always ColumnConst - #100226
Conversation
|
Workflow [PR], commit [de872f1] Summary: ❌
AI ReviewSummaryThis PR enforces the Findings❌ Blockers
Tests
Final Verdict
|
…nst` Always wrap `ColumnSet` in `ColumnConst` at all creation sites and add an assertion in `ActionsDAG::addNode` that rejects non-const columns (except for INPUT and PLACEHOLDER nodes). The `addInput(ColumnWithTypeAndName)` overload now strips non-const columns, keeping only propagated constants. Since `ColumnSet` is now always inside `ColumnConst`, `FunctionIn` disables `useDefaultImplementationForConstants` to avoid the framework changing `input_rows_count` from 0 to 1 during header computation with unready sets. Instead, it handles constant unwrapping for the left argument manually and returns `ColumnConst` results for empty sets and const inputs explicitly. `FilterTransform` no longer calls `expression->execute()` in its constructor (which would fail with unready sets). It uses `ActionsDAG::updateHeader` (dry-run evaluation) for the initial header, then re-evaluates the filter via `expression->execute` in `prepare()` once sets are ready (`output.isNeeded()`), enabling constant-fold early exit for expressions like `WHERE x IN (empty set)`. The old analyzer's `ExpressionAnalysisResult` had the same issue — it called `ExpressionActions::execute` on sample blocks for early constant folding of WHERE/PREWHERE before sets were built. Replaced with `ActionsDAG::updateHeader` which uses dry-run evaluation. Propagate `dry_run` through lambda execution: `ColumnFunction::reduce`, `ExecutableFunctionExpression`, and `FunctionArrayMapped` now forward the flag so that `FunctionIn` inside lambdas (e.g. `arrayExists(x -> x IN ...)`) correctly returns placeholder results during dry-run evaluation. Remove `ExpressionActions::checkColumnIsAlwaysFalse` — superseded by the general constant-fold check in `FilterTransform::prepare`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…gTransform` `FilterTransform::prepare` used `expression->execute(header)` to re-evaluate the filter once output is needed. This fails for mutations where `DelayedPorts` delays data flow but not the `isNeeded` signal, so sets may not be ready yet. Use `ActionsDAG::updateHeader` (dry-run) instead. `TotalsHavingTransform` constructor had the same issue — add a comment documenting the existing `updateHeader` usage. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
c8619f8 to
385365d
Compare
…for `ColumnSet` Since `ColumnSet` is now always wrapped in `ColumnConst`, the bare `checkAndGetColumn<ColumnSet>` check no longer finds it. Add `checkAndGetColumnConstData` as the primary check so that sets from subqueries are properly found and built before the DAG is executed. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test checks that sets are not built when `use_skip_indexes = 0`. However, when `auto_statistics_types` is set (via random MergeTree settings fuzzing), the statistics machinery builds the set as a side effect, causing `throwIf(1)` to fire unexpectedly. Disable `use_statistics` in the EXPLAIN queries to prevent this. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Same root cause as `02707_skip_index_with_in`: when `auto_statistics_types` is set via random MergeTree settings fuzzing, the statistics machinery changes the query plan (removing `CreatingSet` nodes). Disable `use_statistics` to keep the plan stable. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When `auto_statistics_types` is set via random MergeTree settings fuzzing, the statistics machinery reads extra rows, exceeding the `max_rows_to_read` limit the test relies on. Disable `use_statistics` in both the base test and the `_with_null` variant. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The nested `arg->reduce()` calls in the short-circuit argument handling were not forwarding the `dry_run` flag, dropping the dry-run context for nested lambda arguments. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
| if (set->getTotalRowCount() == 0) | ||
| return ColumnConst::create(ColumnUInt8::create(1, negative), input_rows_count); | ||
|
|
||
| if (input_rows_count == 0) |
There was a problem hiding this comment.
executeImpl now checks future_set->get() before the input_rows_count == 0 fast path. In non-dry_run execution this means an empty block can now throw Not-ready Set is passed ... if set creation is delayed, even though with zero rows we should be able to return an empty result without touching set readiness.
Could we keep the zero-row short-circuit for non-dry_run (as before), and keep the new empty-set constant handling specifically for dry_run header evaluation?
There was a problem hiding this comment.
I think this will hide the potential error behavior. To evaluate a header, we execute with dry_run. In other cases, I think it's better to throw an error even if input_rows_count == 0.
I will keep the code as is if the tests pass.
There was a problem hiding this comment.
I still think this is a real behavior regression.
FilterTransform::doTransform executes the expression with num_rows_before_filtration (runtime path, not dry_run). If a zero-row chunk is processed before the set is ready, FunctionIn::executeImpl now throws at future_set->get() / Not-ready Set is passed... before it reaches the input_rows_count == 0 branch.
For zero input rows we should be able to return an empty result without touching set readiness. Throwing here turns an empty-block no-op into a query exception.
Can we restore the zero-row fast path for non-dry_run execution (while keeping the new dry-run behavior for header evaluation)?
There was a problem hiding this comment.
I still don't think it's a regression.
FilterTransform::doTransform should not be run when there is not-ready set. It does not matter if input_rows_count is zero or not.
There was a problem hiding this comment.
I re-checked this against the current code and the concern is still live.
ISimpleTransform::work still invokes transform even when chunk.getNumRows() == 0 (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform forwards that num_rows_before_filtration to expression->execute (src/Processors/Transforms/FilterTransform.cpp:179). In FunctionIn::executeImpl, the non-dry_run path now calls future_set->get() and throws for not-ready sets before reaching if (input_rows_count == 0) (src/Functions/in.cpp:109-124).
So an empty runtime chunk can now fail with Not-ready Set is passed ... where it previously returned an empty result. This is a behavior regression: zero-row execution should be a no-op with respect to set readiness.
Could we restore the zero-row fast path for non-dry_run execution (while keeping the dry-run header behavior)?
There was a problem hiding this comment.
I re-checked this on the current head and the regression is still present.
FunctionIn::executeImpl still calls future_set->get() (and throws on not-ready sets) before the input_rows_count == 0 branch (src/Functions/in.cpp, lines 109-124). Runtime execution can still hit this path with empty chunks: ISimpleTransform::work always calls transform even for zero-row chunks (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform forwards num_rows_before_filtration to expression->execute (src/Processors/Transforms/FilterTransform.cpp:179).
So a zero-row runtime chunk can still fail with Not-ready Set is passed ... instead of behaving as a no-op. Could we restore the zero-row fast path for non-dry_run execution (while keeping the dry-run/header behavior)?
There was a problem hiding this comment.
I re-checked the current head and the concern is still live.
In FunctionIn::executeImpl, the non-dry_run path still calls future_set->get() (and can throw Not-ready Set is passed ...) before the input_rows_count == 0 branch. Runtime can still pass empty chunks through this path: ISimpleTransform::work invokes transform even for zero-row chunks, and FilterTransform::doTransform forwards that row count to expression->execute.
So an empty runtime chunk can still raise an exception instead of behaving as a no-op. Please restore the zero-row short-circuit before set-readiness checks for non-dry_run execution (while keeping the current dry-run/header behavior).
There was a problem hiding this comment.
Re-checked on the latest head (da5be0d) and this regression is still present.
FunctionIn::executeImpl still resolves future_set->get() before if (input_rows_count == 0), so a not-ready RHS set still throws Not-ready Set is passed ... even for an empty input chunk. Runtime can still reach this path with zero rows: ISimpleTransform::work always calls transform (src/Processors/ISimpleTransform.cpp:100), and FilterTransform::doTransform passes that row count into expression->execute (src/Processors/Transforms/FilterTransform.cpp:179).
Please restore the zero-row fast path for non-dry_run execution before set-readiness checks (while keeping the current dry-run/header behavior).
There was a problem hiding this comment.
Re-checked on current head (da5be0d): this is still a behavior regression.
In FunctionIn::executeImpl, future_set->get() is still evaluated before if (input_rows_count == 0), so a not-ready RHS set can still throw Not-ready Set is passed ... even for an empty runtime chunk.
Runtime can reach this path with zero rows: ISimpleTransform::work still calls transform on empty chunks, and FilterTransform::doTransform forwards that row count to expression->execute.
Please restore the zero-row fast path for non-dry_run execution before set-readiness checks (keeping current dry_run handling for header evaluation).
|
Related to #90363 |
| if (res.type != ActionType::PLACEHOLDER) | ||
| { | ||
| const auto valid_column = !res.column || (res.column->isConst() || typeid_cast<const ColumnSet *>(res.column.get()) != nullptr); | ||
| if (!valid_column) | ||
| res.column = nullptr; | ||
| if (res.column && !isColumnConst(*res.column)) | ||
| throw Exception(ErrorCodes::LOGICAL_ERROR, | ||
| "ActionsDAG node column must be a ColumnConst, got {} for '{}'", | ||
| res.column->getName(), res.result_name); | ||
| } |
There was a problem hiding this comment.
Maybe let's do this check before we emplace the node inside nodes?
Also, the AI description states: that rejects non-const columns (except for INPUT and PLACEHOLDER nodes).. It would still reject an INPUT node.
There was a problem hiding this comment.
Never trust AI :)
| auto column_set = ColumnSet::create(1, std::move(set)); | ||
|
|
||
| if (set_is_created) | ||
| column.column = ColumnConst::create(std::move(column_set), 1); | ||
| else | ||
| column.column = std::move(column_set); | ||
| column.column = ColumnConst::create(std::move(column_set), 1); |
There was a problem hiding this comment.
| auto column_set = ColumnSet::create(1, std::move(set)); | |
| if (set_is_created) | |
| column.column = ColumnConst::create(std::move(column_set), 1); | |
| else | |
| column.column = std::move(column_set); | |
| column.column = ColumnConst::create(std::move(column_set), 1); | |
| column.column = ColumnConst::create(ColumnSet::create(1, std::move(set));, 1); |
| { | ||
| auto header = expression->getActionsDAG().updateHeader(getInputPort().getHeader()); | ||
| auto & column = header.getByPosition(filter_column_position).column; | ||
| if (column) |
There was a problem hiding this comment.
When it is possible to not have a column? Maybe let's throw a LOGICAL_ERROR.
There was a problem hiding this comment.
Yes, usually we create columns in the header. But I don't want to fix it now, cause we don't strictly check this invariant
| /// where the result becomes known only after the set is built. | ||
| /// Use updateHeader (dry-run) because sets may not be ready yet even when | ||
| /// output.isNeeded() is true (e.g. delayed set creation in mutations). | ||
| if (!are_prepared_sets_initialized && output.isNeeded()) |
There was a problem hiding this comment.
Maybe we can also skip the re-evaluation when always_false is already set. I am not sure if it worth the clutter or not, but thought will mention it.
| if (!column_set) | ||
| column_set = checkAndGetColumn<ColumnSet>(node.column.get()); |
There was a problem hiding this comment.
If we wrap the set in const column, how is it possible to not have it as const column? Especially because below we don't do this. Maybe it worth a comment if this really the case.
| if (!column_set) | |
| column_set = checkAndGetColumn<ColumnSet>(node.column.get()); |
There was a problem hiding this comment.
I'd like to fix it in a follow-up PR
`FunctionCapture` (the IFunctionBase backing a lambda) inherited the default `isSuitableForConstantFolding() == true`, so the analyzer would happily fold `arrayMap(x -> f(x), [...const array...])` even when `f` was non-deterministic or referenced an IN set whose RHS hadn't been built yet. The folded value (computed with `dry_run=true`) would be cached on the DAG node and reused at execution time, producing wrong results — most visibly for non-deterministic WASM UDFs whose dry-run returns defaults (test `04212_bare_function_name_as_lambda_wasm`). Walk the lambda's inner DAG and propagate the existing constant-folding suitability up: - A FUNCTION node disqualifies the lambda if its `function_base` reports `isSuitableForConstantFolding() == false`. - A COLUMN node disqualifies the lambda if it wraps a `ColumnSet` whose `FutureSet` isn't ready — same check `getFunctionArguments` already performs for direct children of a function node. - ARRAY_JOIN and PLACEHOLDER nodes inside a lambda also disqualify it. This lets `addFunctionImpl`'s `all_const` check fall through cleanly: with the lambda's `node.column` left null, the outer higher-order function isn't const-folded either, and the inner functions run for real at execution time. While here: also stop forwarding the outer `dry_run` flag into the lambda body in `ExecutableFunctionExpression::executeImpl`. With the suitability check above, this can't reach a non-deterministic call through constant folding anymore, but reverting the propagation keeps the lambda boundary opaque (matches pre-PR behaviour) and avoids similar surprises if anyone else ever dry-runs through a lambda. Adjust `evaluateConstantExpression` to apply `cloneResized(1)` after both the new- and old-analyzer branches: DAG nodes now hold size-zero ColumnConsts (per the `addColumn` invariant), so the existing `empty()` check would otherwise reject a perfectly valid constant. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> (cherry picked from commit e63378a)
This reverts commit a19a79b.
| /// output.isNeeded() is true (e.g. delayed set creation in mutations). | ||
| if (!are_prepared_sets_initialized && output.isNeeded()) | ||
| { | ||
| are_prepared_sets_initialized = true; |
There was a problem hiding this comment.
are_prepared_sets_initialized is set to true before we know that sets are actually ready.
In this same block we note that sets may still be unready even when output.isNeeded() == true. If that happens, this one-shot updateHeader run sees a placeholder/non-constant result and we never re-check after the set becomes ready, so always_false stays false and we miss the intended early-stop optimization for WHERE ... IN (empty set).
Can we keep re-evaluating until sets are definitely initialized (for example, set this flag only after the pipeline leaves the pre-init phase, as in the previous status != PortFull logic)?
There was a problem hiding this comment.
I think the comment mentions a corner case, and this should not normally happen. Sets should already be build when the port is needed. Otherwise, we get not-ready set in work(). Re-evaluation might be expensive
LLVM Coverage Report
Changed lines: 93.49% (201/215) | lost baseline coverage: 5 line(s) · Uncovered code |
Per @Algunenano review on PR ClickHouse#105675: dry_run has only 3 real use cases in the codebase, and the original ClickHouse#105650 fuzzer finding is already masked on master by ClickHouse#100226 (ColumnConst node invariant + dry_run propagation in lambda execution). Adding more dry_run plumbing without a current behavioural bug to back it is unjustified. Keep the regression test (04274_105650_isNotDistinctFrom_string_group_by) so the fuzzer query and a minimised isNotDistinctFrom + WITH ROLLUP form remain exercised on master HEAD.
…s-const Enforce invariant that `ActionsDAG::Node::column` is always ColumnConst
…d analyzer
The old analyzer replaces `in` with `inIgnoreSet` while it only needs the
types, passing the left operand as the stand-in for the set that is not built
yet. The general typing rule wraps the result in `LowCardinality` only when
every other argument is a constant, so two full `LowCardinality` arguments
typed the expression as plain `UInt8`, while executing the real `in` against
the constant `Set` column yields `LowCardinality(UInt8)`.
A query reading such a column across a subquery boundary then recorded
`UInt8` in the outer `ActionsDAG` and got `LowCardinality(UInt8)` in the
header, failing the type check in `ActionsDAG::updateHeader`:
SET enable_analyzer = 0;
SELECT tuple(*) FROM (SELECT s, s IN (SELECT 'a') AS f FROM t);
-- Unexpected return type from tuple. Expected Tuple(LowCardinality(String), UInt8).
-- Got Tuple(LowCardinality(String), LowCardinality(UInt8)). (LOGICAL_ERROR)
Pass a constant `UInt8` as the stand-in instead. It is indistinguishable from
the real `Set` argument in every dimension the typing rule inspects, so
analysis and execution agree by construction for all eight `in` variants and
every operand shape. A `Set`-typed stand-in would mirror execution more
literally, but the window-definition expressions built by
`getRootActionsNoMakeSet` end up in an executed plan, and a `ColumnSet` with
no set behind it would be dereferenced when such a plan is serialized.
`allow_experimental_analyzer = 1` was fixed for the same root cause in
ClickHouse#114229, whose test is tagged
`no-old-analyzer`; the divergence appeared when `ColumnSet` became always
constant in ClickHouse#100226.
The fold added in this PR refuses a storage-backed set, because an `INSERT` grows
it in place after planning. `executeImpl` still returned a `ColumnConst` for any
empty set, so header evaluation produced a constant where the DAG node stayed a
function, which is the mismatch this PR is about. An empty `ENGINE = Set` table
under `ARRAY JOIN` therefore still threw:
CREATE TABLE s (x Int) ENGINE = Set;
SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN s; -- Code: 44
Measured: correct on 26.3.23.2, `Code: 44` on 26.7.6.15, on pristine master and on
the previous head of this PR. So it is the same regression as the tuple-set carrier
rather than an older bug, and the description's claim that only the tuple-set
carrier throws on master was wrong.
Both paths now use `isImmutableEmptySet`, so a set kind is constant in the DAG and
in the header or in neither. An empty subquery set already answered correctly for
the mirror-image reason: `FutureSetFromSubquery::get` returns null during analysis,
so header evaluation never saw a constant there.
The always-false exit of ClickHouse#100226 is unaffected: a literal `IN ()` is a tuple set
and still folds to `Filter column: 0`. For the excluded kinds the empty set now
goes through `Set::execute`, which returns an all-`negative` column.
Every stateless test using `ENGINE = Set` (25 files) plus the empty-subquery-set
and plan-shape tests ran on the previous head and on this commit: 28 of 29
byte-identical, the only difference being the new arms of this PR's test. The new
empty-storage arm throws `Code: 44` on the previous head.
An ARRAY JOIN with a WHERE filter on a different column against an empty IN set was rejected with Code: 44. Cannot convert column `in(...)` because it is non constant in source stream but must be constant in result. (ILLEGAL_COLUMN) as in CREATE TABLE t (a Int, b Int) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO t VALUES (1, 2); SELECT count() FROM t ARRAY JOIN [b] AS x WHERE a IN (); FunctionIn disables the default constant-folding wrapper and folds by hand, but it never declared the fold it actually performs: for a set that is built and empty, executeImpl returns a ColumnConst whatever the left operand is. The DAG answers a different question. With a non-constant left operand getFunctionArguments reports all_const = false, so tryFoldFunctionToConstant calls getConstantResultForNonConstArguments, which FunctionIn did not override, so the node stayed non-constant. Yet ActionsDAG::updateHeader separately executes the function at input_rows_count = 0 and does reach the empty-set branch, so the header column is a ColumnConst. ARRAY JOIN rebuilds the block from the non-constant node, which is what forces the two headers to be compared, so blocksHaveEqualStructure fails and makeConvertingActions throws. The asymmetry became reachable in ClickHouse#100226, which moved the empty-set check ahead of the input_rows_count == 0 early return; before that the branch returned a non-constant column and both sides agreed. Reverting that ordering was rejected because it would re-break the ConstantFilterDescription always-false exit in FilterTransform::prepare() that ClickHouse#100226 was written for. Adding the override keeps both properties. The fold applies only when the set is already built (a not-yet-built subquery set may still turn out non-empty) and empty, and when the result type carries no Nullable: NULL IN () is NULL rather than 0, so folding those to UInt8 would produce wrong results. LowCardinality(String) operands and the notIn and nullIn variants were failing the same way and are covered by the same override. Measured against pristine master, 10 of 32 probed query shapes move from Code: 44 to the correct value and the other 22 are byte-identical. The new test's expected values were cross-checked against unpatched master's own working shape (with prewhere optimizations disabled) so they encode pre-regression semantics. Removing only the Nullable guard makes NULL IN () return 0, which the test catches. Re-running the failures of the whole _in test pattern against pristine master under an identical workload showed no regressions across the 248 tests run on both arms. Closes: ClickHouse#116018
Opus 4.6
Always wrap `ColumnSet` in `ColumnConst` at all creation sites and add an assertion in `ActionsDAG::addNode` that rejects non-const columns (except for INPUT and PLACEHOLDER nodes). The `addInput(ColumnWithTypeAndName)` overload now strips non-const columns, keeping only propagated constants.Since
ColumnSetis now always insideColumnConst,FunctionIndisablesuseDefaultImplementationForConstantsto avoid the framework changinginput_rows_countfrom 0 to 1 during header computation with unready sets. Instead, it handles constant unwrapping for the left argument manually and returnsColumnConstresults for empty sets and const inputs explicitly.FilterTransformno longer callsexpression->execute()in its constructor (which would fail with unready sets). It usesActionsDAG::updateHeader(dry-run evaluation) for the initial header, then re-evaluates the filter viaexpression->executeinprepare()once sets are ready (output.isNeeded()), enabling constant-fold early exit for expressions likeWHERE x IN (empty set).The old analyzer's
ExpressionAnalysisResulthad the same issue — it calledExpressionActions::executeon sample blocks for early constant folding of WHERE/PREWHERE before sets were built. Replaced withActionsDAG::updateHeaderwhich uses dry-run evaluation.Propagate
dry_runthrough lambda execution:ColumnFunction::reduce,ExecutableFunctionExpression, andFunctionArrayMappednow forward the flag so thatFunctionIninside lambdas (e.g.arrayExists(x -> x IN ...)) correctly returns placeholder results during dry-run evaluation.Remove
ExpressionActions::checkColumnIsAlwaysFalse— superseded by the general constant-fold check inFilterTransform::prepare.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Documentation entry for user-facing changes
Version info
26.6.1.92