Repository navigation
Fix wrong result from optimize_injective_functions_in_group_by on toString(x, NULL) - #117197
Conversation
…tring(x, tz)
`FunctionConvert::isInjective` for `toString` ignored its arguments and always
reported the function injective. The two-argument `toString(value, timezone)`
form is not injective in `value`: different instants can share a formatted
string, and a NULL timezone makes the result a constant NULL of type
`Nullable(Nothing)`. `optimize_injective_functions_in_group_by` therefore
eliminated it from the grouping keys, rewriting `GROUP BY toString(number, NULL)`
into `GROUP BY number` and turning the single NULL group into one group per row:
SELECT count() FROM (SELECT 1 FROM numbers(10) GROUP BY toString(number, NULL));
-- returned 10, must be 1
Only the single-argument `toString(x)` is injective, so restrict `isInjective`
to that arity. Found by the server-side AST fuzzer correctness oracle.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [75272b1] Summary: ✅
AI ReviewSummaryThis PR narrows Findings❌ Blockers
Tests
Final Verdict❌ Request changes. The direct LLVM Coverage ReportMeasured on commit 75272b1.
Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code |
|
@groeneai review |
groeneai
left a comment
There was a problem hiding this comment.
One blocker, one test problem, one coverage gap. The Fast test failure on f7ed388e is a real consequence of the diff.
1. arguments.size() == 1 reinterprets the empty-sample_columns convention
IFunction.h:257-261 documents empty sample columns as "injective with any arguments", not "zero arguments":
NOTE: to check is function injective with any arguments, you can pass empty columns as
sample_columns(since most of the time function will ignore it anyway, and creating arguments just for checking is function injective or not is overkill).
Seven callers take that route, so toString is now non-injective for all of them: UniqInjectiveFunctionsEliminationPass.cpp:68, RemoveInjectiveFunctionsVisitor.cpp:29, TreeOptimizer.cpp:186, actionsDAGUtils.cpp:656 (isInjectiveFunction), optimizeReadInOrder.cpp:220, convertOuterJoinToInnerJoin.cpp:119, ReadInOrderOptimizer.cpp:61.
That is both Fast test failures:
02493_analyzer_uniq_injective_functions_elimination:uniq(toString(abs(materialize(number))))no longer dropstoString.03399_advanced_expr_contains_sharding_key:SELECT DISTINCT toString(id) FROM distributed_tableloses the shard-localDISTINCTand the initiator gains aDistinct (DISTINCT)step, sooptimize_distributed_group_by_sharding_keystops recognizing the key. That is a plan regression, not a reference cosmetic.
Four more are silent, with no test covering them: read-in-order through toString (optimizeReadInOrder.cpp:220, ReadInOrderOptimizer.cpp:61), the outer-to-inner join rewrite, and uniq elimination on the old analyzer.
Minimal repair, same shape:
return std::is_same_v<Name, NameToString> && arguments.size() <= 1;Empty keeps meaning "arity unknown", so every {} caller behaves exactly as on master, while OptimizeKeyExpressionsUtils.cpp:164 passes real FunctionNode::getArgumentColumns (two entries for toString(x, tz)) and the reported query stays fixed.
2. The allow_experimental_analyzer = 0 arm passes for the wrong reason
The old-analyzer rewrite is TreeOptimizer::optimizeGroupBy. Its isInjective({}) at TreeOptimizer.cpp:186 has no arity guard, and it runs unconditionally from TreeOptimizer.cpp:698, so optimize_injective_functions_in_group_by never reaches it. Measured on master 9593cfad with SELECT count() FROM (SELECT 1 FROM numbers(10) GROUP BY toString(number, NULL)):
new analyzer, opt = 1 10
new analyzer, opt = 0 1
old analyzer, opt = 1 10
old analyzer, opt = 0 10 <- the setting does not gate this path
So that arm is red on master and green here only through the over-fire in 1; with the repair above it is red again. Either guard the arity at TreeOptimizer.cpp:186 too, or drop the arm, since the setting under test is analyzer-only.
3. NULL is not the only wrong result
A real timezone is enough. Measured on master:
SELECT count() FROM (SELECT 1 FROM (SELECT arrayJoin([1730610000, 1730613600]) AS t)
GROUP BY toString(toDateTime(t), 'America/New_York'));
-- 2, and 1 with optimize_injective_functions_in_group_by = 0Both instants render 2024-11-03 01:00:00 across the DST fall-back, so one group is correct. DateTime64 collides the same way through sub-second truncation. One such case in the test would show the fix is about arity rather than about NULL.
From reading the code, not measured: actionsDAGUtils.cpp:656 and convertOuterJoinToInnerJoin.cpp:119 have no arity guard either, so after the repair in 1 they would still accept a two-argument toString as injective.
|
The premise "only the single-argument SELECT count() FROM (SELECT 1 FROM (SELECT arrayJoin([1730610000, 1730613600]) AS x)
GROUP BY toString(toDateTime(x, 'America/New_York')));
-- returns 2; correct is 1 (both instants render '2024-11-03 01:00:00' across the fold)
-- with optimize_injective_functions_in_group_by = 0: 1So neither Related: |
|
Confirmed on master Your case is a different hole from the one in my section 3: there the timezone is an argument to
|
|
Thanks @zlareb1, @groeneai — both threads land. The DateTime/DateTime64 fold hole is genuinely deeper than the arity case and tracked at #116931/#116935/#116828; agree with @groeneai's recommendation to keep this PR narrow (arity only) and leave the type-aware condition to those. The For the deeper condition when it lands elsewhere: the three measurement handles @groeneai flagged (
cc @groeneai |
The previous commit's `arguments.size() == 1` predicate over-restricted the
FunctionConvert::isInjective override: three legacy passes call
`isInjective({})` with empty sample columns —
UniqInjectiveFunctionsEliminationPass, RemoveInjectiveFunctionsVisitor, and
TreeOptimizer — and `0 == 1` is false, so even single-argument `toString(x)`
stopped reporting injective there and the following existing tests regressed:
02493_analyzer_uniq_injective_functions_elimination
03399_advanced_expr_contains_sharding_key
Loosen to `arguments.size() <= 1`: reject only when we know the call has ≥ 2
arguments, which is what the reported wrong result actually needs. The
`OptimizeGroupByInjectiveFunctionsPass` path (via
OptimizeKeyExpressionsUtils.cpp) does pass real arguments and still fires the
fix on `toString(x, NULL)`.
The one-argument `toString(DateTime)` / `toString(DateTime64)` DST-fold
non-injectivity (ClickHouse#116931, ClickHouse#116935, ClickHouse#116828) is a wider condition that belongs
in a separate change; not addressed here per @groeneai on ClickHouse#117197.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
The old query analyzer (`allow_experimental_analyzer = 0`) reaches FunctionConvert::isInjective through legacy passes that pass empty sample columns (RemoveInjectiveFunctionsVisitor.cpp:29, TreeOptimizer.cpp:186), so `arguments.size() <= 1` still returns true there and the wrapper is still eliminated. That is the same "seven callers that pass empty sample columns exactly as on master" trade-off @groeneai documented, and the type-aware condition that closes it is separately tracked at ClickHouse#116931 / ClickHouse#116935 / ClickHouse#116828. Drop the `allow_experimental_analyzer = 0` assertion in the test rather than lock in a wrong expected value; expand the file's comment to explain the scope of what this fix does and does not cover. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Re-reviewed
Two notes on the comment you left in
That call is unconditional, so on the old analyzer there is no setting-level workaround. So assertion 4 would have failed on the old analyzer too, not only assertion 5. Worth stating on whichever of #116931 / #116935 / #116828 picks this up: there the wrong result cannot be switched off. I am not asking you to widen this PR; dropping the arm is the right call and matches the project's standing position on old-analyzer test arms. Assertion 3 is inert as written. The plan changes, the count does not. Either move assertion 3 to that form or drop it: One line for the
|
| /// #116931, #116935, #116828 and is intentionally not addressed here. | ||
| bool isInjective(const ColumnsWithTypeAndName & arguments) const override | ||
| { | ||
| return std::is_same_v<Name, NameToString> && arguments.size() <= 1; |
There was a problem hiding this comment.
This still leaves the ActionsDAG key-reduction path misclassifying two-argument toString as injective. actionsDAGUtils::isInjectiveFunction asks function_base->isInjective({}) at src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:656, so removeInjectiveFunctionsFromResultsRecursively will still strip toString(a, NULL) when isPartitionKeyFunctionOfKeys runs for the per-partition optimizations.
Concrete trace: with CREATE TABLE t (a UInt32) ENGINE = MergeTree ORDER BY tuple() PARTITION BY a, SELECT count() FROM (SELECT 1 FROM t GROUP BY toString(a, NULL)) SETTINGS allow_aggregate_partitions_independently = 1, force_aggregate_partitions_independently = 1 still proves the partition key from a, calls skipMerging() in src/Processors/QueryPlan/Optimizations/useDataParallelAggregation.cpp:182-183, and returns one NULL group per partition instead of one overall group. So this fixes the query-tree GROUP BY rewrite, but not the ActionsDAG optimization family.
Can this either thread the real argument columns or arity through actionsDAGUtils::isInjectiveFunction, or explicitly decline toString when children.size() >= 2 on that path, and add a MergeTree regression test that forces allow_aggregate_partitions_independently = 1?
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units40 translation units recompiled, 285 s compile time in total, 40 of them have a recent master baseline. |
|
The |
|
Thanks — it's actually deterministic, not flaky. The failing config is That's the same trade-off @groeneai flagged upthread ("leaves the seven callers that pass empty sample columns exactly as on master") and the deeper condition is tracked at #116931 / #116935 / #116828. All four assertions in the test return 10 in that old-analyzer config, including the Two options:
I'd default to (1). Happy to push whichever you prefer. cc @groeneai |
|
Option 2 ( The setting under test is analyzer-only by design, so the scope worth stating in the file is the analyzer, not the job: That same commit is also the in-family precedent for this residual: it left the One top-of-file Either option is correct for the residual, so if you still prefer the tag, go ahead. |
The optimization under test (optimize_injective_functions_in_group_by via
OptimizeGroupByInjectiveFunctionsPass) is analyzer-only by design. Force
`SET enable_analyzer = 1` at the top of the test so it runs its assertions
against the analyzer this fix covers, regardless of the CI job's default
(old-analyzer variants would otherwise run the elimination through legacy
`isInjective({})` passes not covered by the arity condition).
Consolidate the earlier tail comment about the old-analyzer legacy passes into
the header, since the test now scopes to the new analyzer explicitly.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Style check rejects "new analyzer" / "new query analyzer" because the analyzer has been enabled by default since ClickHouse 24.3. Write "Analyzer" and `enable_analyzer = 1` instead. "old query analyzer" stays — it correctly names the legacy path the comment scopes out. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| /// #116931, #116935, #116828 and is intentionally not addressed here. | ||
| bool isInjective(const ColumnsWithTypeAndName & arguments) const override | ||
| { | ||
| return std::is_same_v<Name, NameToString> && arguments.size() <= 1; |
There was a problem hiding this comment.
FunctionConvert::isInjective still leaves the ANY OUTER JOIN to INNER rewrite unsound for two-argument toString. tryConvertAnyOuterJoinToInnerJoin descends through current_node->function_base->isInjective({}) at src/Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp:119, so toString(ts, 'America/New_York') is still treated as injective there even though this PR documents the opposite.
Concrete trace: if the aggregated side groups by ts and the join key is toString(ts, 'America/New_York'), two different ts values from the 2024-11-03 DST fold stringify to the same local time. This code still unwraps the key to ts, concludes the join key is unique, and rewrites ANY OUTER JOIN to INNER ALL, which duplicates rows instead of preserving ANY semantics.
Can the empty-sample callers that make semantic decisions here either see the real argument columns / arity, or at least reject toString once children.size() >= 2?
| /// #116931, #116935, #116828 and is intentionally not addressed here. | ||
| bool isInjective(const ColumnsWithTypeAndName & arguments) const override | ||
| { | ||
| return std::is_same_v<Name, NameToString> && arguments.size() <= 1; |
There was a problem hiding this comment.
This same ActionsDAG hole also reaches distributed sharding-key pushdown. StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression calls removeInjectiveFunctionsFromResultsRecursively at src/Storages/StorageDistributed.cpp:649, which still unwraps toString(shard_key, NULL) via actionsDAGUtils::isInjectiveFunction -> function_base->isInjective({}) at src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:656.
That makes the analyzer accept DISTINCT / GROUP BY / LIMIT BY expressions as sharding-key expressions at src/Storages/StorageDistributed.cpp:693-710, and for simple queries it returns QueryProcessingStage::Complete at :724-725. The initiator then skips the final merge even though toString(id, NULL) is a single NULL key, so SELECT count() FROM (SELECT 1 FROM dist GROUP BY toString(id, NULL)) SETTINGS optimize_skip_unused_shards = 1, optimize_distributed_group_by_sharding_key = 1 still returns one row per shard instead of one overall.
Can this path either see the real argument columns / arity, or at least refuse to unwrap toString when the ActionsDAG node has two children?
| /// #116931, #116935, #116828 and is intentionally not addressed here. | ||
| bool isInjective(const ColumnsWithTypeAndName & arguments) const override | ||
| { | ||
| return std::is_same_v<Name, NameToString> && arguments.size() <= 1; |
There was a problem hiding this comment.
arguments.size() <= 1 over-declines the two-argument form. IFunction::isInjective is allowed to inspect constant argument values, and the executor already resolves constant time zones for toString(DateTime, timezone); for fixed-offset zones such as UTC and Fixed/UTC+05:30:00, DateLUTImpl::hasFixedOffset() is true, so toString(ts, timezone) is still injective in ts.
The new unconditional arguments.size() <= 1 return means analyzer passes that do have real arguments (OptimizeKeyExpressionsUtils.cpp:164, TruncateOrderByAfterGroupByKeysPass.cpp:121) now keep toString(ts, 'UTC') in GROUP BY / LIMIT BY / ORDER BY even though the wrapper is safe to remove. That is a silent plan regression in the default-on injective optimizations.
Can this special-case constant fixed-offset time zones instead of rejecting every two-argument call?
|
@PedroTadim all green |
|
@qoega did you review the cursor bot's messages? |
|
I would prefer to create a followup issue for the cases it highlighted.. |
| size_t getNumberOfArguments() const override { return 0; } | ||
| bool isInjective(const ColumnsWithTypeAndName &) const override { return std::is_same_v<Name, NameToString>; } | ||
| /// Only the single-argument `toString(x)` is injective. The two-argument | ||
| /// `toString(value, timezone)` form is not injective in `value` (different |
|
@qoega merge with master, I enabled auto-merge |
| SELECT count() FROM (SELECT toString(number, NULL) AS k FROM numbers(10) GROUP BY k); | ||
|
|
||
| -- Single-argument toString stays injective, so this still groups per distinct value. | ||
| SELECT count() FROM (SELECT 1 FROM numbers(10) GROUP BY toString(number)); |
There was a problem hiding this comment.
This arm does not actually prove that the single-argument optimization still fires. GROUP BY toString(number) returns 10 whether the wrapper is eliminated or not, so the test stays green even if the new predicate silently stops removing valid wrappers such as toString(ts, 'UTC'). If the intent is to guard the "still injective" contract, can this assert the plan instead (for example via EXPLAIN QUERY TREE / countIf(explain ILIKE '%function_name: toString%')) or be dropped in favor of an existing test that reddens when elimination stops happening?
|
@qoega should we merge this now? |
Closes: #117194
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a wrong result from
optimize_injective_functions_in_group_byon the two-argumenttoString(x, timezone)form.FunctionConvert::isInjectivefortoStringunconditionally returnedtrueregardless of arity, soGROUP BY toString(number, NULL)(whose result is alwaysNULL, typeNullable(Nothing)) was rewritten toGROUP BY numberand produced one group per row instead of one.Documentation entry for user-facing changes
Detailed description
FunctionConvert::isInjectivefortoStringignored its arguments and always reported the function injective. The two-argumenttoString(value, timezone)form is not injective invalue: different instants can share a formatted string, and a NULL timezone makes the result a constant NULL of typeNullable(Nothing).optimize_injective_functions_in_group_by(default on) therefore eliminated the wrapper from the grouping keys and turned the single NULL group into one group per row.Minimal repro (from #117194):
Only the single-argument
toString(x)is injective, so this PR restrictsisInjectiveto that arity — the minimal correct condition.Found by the server-side AST fuzzer + correctness oracles fleet.
cc @groeneai
Workflow [PR]
Sync PR [sync-upstream/pr/117197]
Version info
26.10.1.1032-master(included in26.10and later)