Skip to content

Fix wrong result from optimize_injective_functions_in_group_by on toString(x, NULL) - #117197

Merged
PedroTadim merged 14 commits into
ClickHouse:masterfrom
qoega:fix-tostring-two-arg-injective
Sep 29, 2026
Merged

PedroTadim merged 14 commits into
ClickHouse:masterfrom
qoega:fix-tostring-two-arg-injective

Conversation

@qoega

@qoega qoega commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Closes: #117194

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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_by on the two-argument toString(x, timezone) form. FunctionConvert::isInjective for toString unconditionally returned true regardless of arity, so GROUP BY toString(number, NULL) (whose result is always NULL, type Nullable(Nothing)) was rewritten to GROUP BY number and produced one group per row instead of one.

Documentation entry for user-facing changes

Detailed description

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 (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):

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 this PR restricts isInjective to 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

  • Merged into: 26.10.1.1032-master (included in 26.10 and later)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75272b1]

Summary: ✅


AI Review

Summary

This PR narrows FunctionConvert::isInjective for toString from “always true” to arguments.size() <= 1 and adds an Analyzer-scoped regression test for toString(x, NULL). That fixes the direct query-tree GROUP BY rewrite, but the current head still leaves several empty-sample isInjective({}) optimizations unsound for two-argument toString, and the new predicate also regresses fixed-offset time zones. I do not think it is ready to merge in this state.

Findings

❌ Blockers

  • [src/Functions/FunctionsConversion.h:3417, src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:660] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117197#issuecomment-5618921130] The per-partition aggregation path still unwraps two-argument toString through actionsDAGUtils::isInjectiveFunction, which calls function_base->isInjective({}) and therefore still treats toString(a, NULL) as injective. That means removeInjectiveFunctionsFromResultsRecursively can still prove the partition key from a and skip the final merge, returning one NULL group per partition instead of one overall. Suggested fix: make the ActionsDAG helper see the real argument columns or at least reject toString when children.size() >= 2, and add the allow_aggregate_partitions_independently = 1 regression that exercises this path.

  • [src/Functions/FunctionsConversion.h:3417, src/Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp:119] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117197#issuecomment-5618921130] tryConvertAnyOuterJoinToInnerJoin still descends through current_node->function_base->isInjective({}), so two-argument toString remains eligible for the ANY OUTER JOIN to INNER ALL rewrite even though the PR now documents that form as non-injective. Around a DST fold, that can still duplicate rows instead of preserving ANY semantics. Suggested fix: use an arity-aware injectivity check here, or stop descending through multi-argument toString on this rewrite path.

  • [src/Functions/FunctionsConversion.h:3417, src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:660, src/Storages/StorageDistributed.cpp:633] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117197#issuecomment-5618921130] The same ActionsDAG predicate is reused by StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression, so distributed sharding-key pushdown can still unwrap toString(shard_key, NULL) and incorrectly conclude that DISTINCT / GROUP BY / LIMIT BY are shard-local. The initiator can still skip the final merge and return one row per shard for a constant-NULL key. Suggested fix: once the ActionsDAG helper is fixed, cover this distributed path with a focused regression that proves QueryProcessingStage::Complete is not chosen for two-argument toString.

⚠️ Majors

  • [src/Functions/FunctionsConversion.h:3417, src/Analyzer/Passes/OptimizeKeyExpressionsUtils.cpp:165, src/Analyzer/Passes/TruncateOrderByAfterGroupByKeysPass.cpp:121] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117197#issuecomment-5618921130] The unconditional arguments.size() <= 1 rule now over-declines safe two-argument calls like toString(ts, 'UTC') or any other constant fixed-offset zone. The analyzer passes at these call sites already pass real argument columns, so this change silently stops removing wrappers that are still injective and regresses the default-on key simplifications. Suggested fix: inspect the constant timezone in arguments and keep reporting injective for fixed-offset zones instead of blanket-rejecting every two-argument form.
Tests
  • ⚠️ [tests/queries/0_stateless/05052_tostring_two_args_not_injective_in_group_by.sql:25] The GROUP BY toString(number) arm still does not prove that the single-argument optimization survives: the query returns 10 whether the wrapper is eliminated or not. Add a plan-sensitive assertion (for example via EXPLAIN QUERY TREE) or drop this arm and rely on a test that actually reddens when injective elimination stops firing.
Final Verdict

❌ Request changes. The direct GROUP BY toString(x, NULL) analyzer path is fixed, but the PR still leaves wrong-result rewrites in the ActionsDAG, join, and distributed optimizations, and it introduces a silent fixed-offset regression without a test that would catch it.

LLVM Coverage Report

Measured on commit 75272b1.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 30, 2026
@qoega

qoega commented Aug 30, 2026

Copy link
Copy Markdown
Member Author

@groeneai review

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 drops toString.
  • 03399_advanced_expr_contains_sharding_key: SELECT DISTINCT toString(id) FROM distributed_table loses the shard-local DISTINCT and the initiator gains a Distinct (DISTINCT) step, so optimize_distributed_group_by_sharding_key stops 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 = 0

Both 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.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117197&sha=f7ed388e5774c7dc9772c5516c01f3ae3fbff7a8&name_0=PR&name_1=Fast%20test

@zlareb1

zlareb1 commented Aug 30, 2026

Copy link
Copy Markdown
Member

The premise "only the single-argument toString(x) is injective" is unfortunately still too generous: a single-argument toString over DateTime/DateTime64 is not injective either, because two distinct instants render identically across a DST fold, and the same pass then produces wrong results at default settings:

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: 1

So neither arguments.size() == 1 nor the suggested arguments.size() <= 1 closes the hole for the one-argument case — that part is tracked in #116931 (and its siblings #116935, #116828). A type-aware condition (return false when the argument type is DateTime/DateTime64, with empty arguments still meaning "unknown") would cover both this issue and #116931 in one place.

Related: ConcatOverloadResolver (src/Functions/concat.cpp) independently answers isInjective as arguments.size() == 1 "because concat with one argument delegates to toString" — the same premise via another name, and it answers before the delegation, so a fix inside FunctionConvert::isInjective alone does not cover it.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed on master 9593cfad, and you are right. Measured:

toString(toDateTime(1730610000, 'America/New_York'))  2024-11-03 01:00:00
toString(toDateTime(1730613600, 'America/New_York'))  2024-11-03 01:00:00    equal

SELECT count() FROM (SELECT 1 FROM (SELECT arrayJoin([1730610000, 1730613600]) AS x)
                     GROUP BY toString(toDateTime(x, 'America/New_York')))
optimize_injective_functions_in_group_by = 1 (default)   2
optimize_injective_functions_in_group_by = 0             1

Your case is a different hole from the one in my section 3: there the timezone is an argument to toString, here it is inside the DateTime type and toString has one argument. So arguments.size() <= 1 is necessary (it fixes the reported toString(x, NULL) and leaves the seven callers that pass empty sample columns exactly as on master) and not sufficient. DateTime64 folds the same way (both render 2024-11-03 01:00:00.500, 2 vs 1), and LowCardinality(Nullable(DateTime)) reaches the same pass (2 vs 1).

ConcatOverloadResolver

The site is real and does need the same condition, but not for the stated reason: the GROUP BY pass asks the built function, not the resolver.

OptimizeKeyExpressionsUtils.cpp:159-164 uses FunctionNode::getFunction, which returns an IFunctionBase (FunctionNode.h:120-125). For one argument ConcatOverloadResolver::buildImpl returns to_string->build(arguments) (concat.cpp:223-224), and FunctionToFunctionBaseAdaptor::isInjective forwards to the underlying IFunction (IFunctionAdaptors.h:90). Discriminator, since ConcatOverloadResolver::isInjective answers 0 == 1 = false for empty sample columns while FunctionConvert::isInjective answers true on master:

EXPLAIN QUERY TREE SELECT uniq(concat(materialize(number))) FROM numbers(10)
  concat nodes 0, toString nodes 0     both dropped, so FunctionConvert answered the empty columns
EXPLAIN QUERY TREE SELECT uniq(abs(materialize(number))) FROM numbers(10)
  abs nodes 1                          oracle is sensitive

So a type-aware FunctionConvert::isInjective does reach concat(dt). GROUP BY concat(toDateTime(x, 'America/New_York')) gives 2 and 1 exactly like toString, and uniqExact(concat(...)) over the two instants gives 2. The three sites that really do ask the resolver (TreeOptimizer.cpp:186, RemoveInjectiveFunctionsVisitor.cpp:29, ReadInOrderOptimizer.cpp:61) all pass empty sample columns, where arguments.size() == 1 is already false.

The reason to touch it anyway is stronger than reachability: gtest_functions_stress.cpp:2127-2137 asserts that IFunctionOverloadResolver::isInjective and IFunctionBase::isInjective agree for the same arguments, carving out only dynamically typed ones, and concat is not in excluded_functions. A condition in FunctionConvert alone makes those two disagree for concat(DateTime).

Separability

#116931, #116935 and #116828 are open, and #116931 is this exact case. I agree the type test is the right home for it, and it is separable from the arity fix here: the reported query needs arity, the fold needs the type. I would land this PR with <= 1 rather than hold it for the wider problem.

If you take the type-aware condition

Three things, measured:

  1. DateTime/DateTime64 alone over-declines. Over a fixed-offset zone toString is injective and the pass is correct and firing today: for GROUP BY toString(toDateTime(x, 'UTC')) the toString node count in the query tree is 0 at optimize_injective_functions_in_group_by = 1 and 1 at 0, and the result is 2 either way. DateLUTImpl::hasFixedOffset (DateLUTImpl.h:506, computed at DateLUTImpl.cpp:95 and :169-172 as "no offset change anywhere in the LUT") is reachable from the type through TimezoneMixin::getTimeZone (TimezoneMixin.h:28), so the condition can decline only zones that actually change offset instead of every DateTime.

  2. Strip the whole wrapper matrix before the test. LowCardinality(Nullable(DateTime)) reaches this pass and is wrong today, so removeNullable alone leaves the hole. That is the shape of PRs 105384 and 107881, where a gate stripping only Nullable routed the whole LowCardinality family down the fallback path and lost skip-index pruning silently.

  3. Assert that elimination still fires, not only that results are right. Declining is a silent performance regression that no correct-results test can see. SELECT countIf(explain ILIKE '%function_name: toString%') FROM (EXPLAIN QUERY TREE ...) is enough and reads in both directions.

Separate from toString: toFixedString.h:41 returns true unconditionally, and GROUP BY toFixedString(s, 3) over 'a' and 'a\0' gives 2 at optimize_injective_functions_in_group_by = 1 and 1 at 0, so that is a third site a condition in FunctionConvert will not cover.

@qoega

qoega commented Aug 31, 2026

Copy link
Copy Markdown
Member Author

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 arguments.size() <= 1 predicate is a strict superset of the reported bug fix and preserves the 7 legacy {} callers exactly (which is what broke the two failing tests). Pushing that as a follow-up commit shortly.

For the deeper condition when it lands elsewhere: the three measurement handles @groeneai flagged (hasFixedOffset short-circuit, strip the LowCardinality/Nullable wrapper matrix first, and assert-elimination-still-fires via countIf(explain ILIKE '%toString%')) are on record.

ConcatOverloadResolver + toFixedString.h:41 are separate — will file follow-up trackers if #116931 doesn't already cover them.

cc @groeneai

qoega and others added 2 commits August 31, 2026 10:08
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]>
@groeneai

Copy link
Copy Markdown
Collaborator

Re-reviewed 480aff8b and e23c27c2. My section-1 blocker is closed, and the evidence is the failure set rather than a green run:

  • f7ed388e (== 1): Fast test failed on 02493_analyzer_uniq_injective_functions_elimination and 03399_advanced_expr_contains_sharding_key.
  • 480aff8b (<= 1): both gone. The only failure left was 05052 itself, diff 1 1 10 1 -1 +10, so assertions 1-4 passed and only the old-analyzer arm did not. That measures the {} callers directly, which is what mattered: four of the seven have no test coverage of their own, so a green run alone would not have shown it.

Two notes on the comment you left in 05052.

RemoveInjectiveFunctionsVisitor is not the pass that fires here. It only rewrites arguments of uniq* (the isUniq gate), and removeInjectiveFunction returns early on arguments->children.size() != 1, so a two-argument call never reaches its isInjective({}). The pass that rewrites the old-analyzer key is optimizeGroupBy (TreeOptimizer.cpp:101): predicate at :186, then :207-214 erases the call and re-inserts its non-literal arguments, so NULL is dropped and number stays. The same file also holds optimizeGroupByFunctionKeys (:618, gated by optimize_group_by_function_keys at :701), which is not involved, so naming the file alone is ambiguous.

That call is unconditional, so on the old analyzer there is no setting-level workaround. optimizeGroupBy is invoked at :698 with no settings guard. Measured on master ac95bf3c:

EXPLAIN SYNTAX SELECT 1 FROM numbers(10) GROUP BY toString(number, NULL)

  allow_experimental_analyzer=0, optimize_injective_functions_in_group_by=1  ->  GROUP BY number
  allow_experimental_analyzer=0, optimize_injective_functions_in_group_by=0  ->  GROUP BY number
  allow_experimental_analyzer=1, optimize_injective_functions_in_group_by=0  ->  correct, 1 group

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. GROUP BY toString(number) over numbers(10) returns 10 whether or not the wrapper is eliminated, so no arity predicate can redden it: == 1, <= 1 and < 1 all give 10. With the third handle from the earlier thread:

countIf(explain ILIKE '%toString%') FROM (EXPLAIN QUERY TREE run_passes=1
    SELECT 1 FROM numbers(10) GROUP BY toString(number))

  optimize_injective_functions_in_group_by=1  ->  0   (eliminated)
  optimize_injective_functions_in_group_by=0  ->  1   (retained)

The plan changes, the count does not. Either move assertion 3 to that form or drop it: 02493 and 03399 are the tests that actually catch over-restriction.

One line for the ConcatOverloadResolver tracker when you write it: the mechanism is the built IFunctionBase, not the resolver. OptimizeKeyExpressionsUtils.cpp:159-164 goes through FunctionNode::getFunction, and for a single argument ConcatOverloadResolver::buildImpl returns to_string->build(arguments) (concat.cpp:223-224).

Fast test on e23c27c2 is still running.

/// #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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 75272b199 with master 80508bd5f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 61fda56c2; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

40 translation units recompiled, 285 s compile time in total, 40 of them have a recent master baseline.

Job report

@PedroTadim

Copy link
Copy Markdown
Member

The 05052_tostring_two_args_not_injective_in_group_by test seems flaky

@qoega

qoega commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

Thanks — it's actually deterministic, not flaky. The failing config is Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 2/3) where the runner's default is the old analyzer, and the fix only covers the new-analyzer OptimizeGroupByInjectiveFunctionsPass path (which calls isInjective with real arguments). Under the old analyzer, isInjective is reached through legacy passes that pass empty sample columns (RemoveInjectiveFunctionsVisitor / TreeOptimizer), and the arguments.size() <= 1 predicate is true for the empty case, so the wrapper is still eliminated there.

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 SETTINGS optimize_injective_functions_in_group_by = 0 arm — which suggests the old analyzer also runs the elimination through one of the {} legacy passes.

Two options:

  1. Tag the test with -- Tags: no-old-analyzer — matches the fix's actual scope; test only runs in the analyzer configs the fix covers.
  2. Force SET enable_analyzer = 1 at the top of the test — same net effect but explicit.

I'd default to (1). Happy to push whichever you prefer.

cc @groeneai

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

Option 2 (SET enable_analyzer = 1), and agreed that it is deterministic rather than flaky.

The setting under test is analyzer-only by design, so the scope worth stating in the file is the analyzer, not the job: optimizeGroupBy lost its optimize_injective_functions_in_group_by guard deliberately in 8da7b5a ("Remove optimize_injective_functions_in_group_by check in old analyzer"), which is why the old analyzer eliminates the wrapper unconditionally and your fourth assertion returns 10 in that config too.

That same commit is also the in-family precedent for this residual: it left the enable_analyzer=0 arm of 03641_group_by_injective_functoon_bad_arguments.sql as a commented-out line pointing at a tracking issue, and pinned enable_analyzer=1 per query on the arms it kept. None of the existing stateless tests that exercise this setting is tagged no-old-analyzer; the ones whose output depends on the analyzer pin it instead (02969, 03014, 04518, 04805).

One top-of-file SET enable_analyzer = 1; covers all four queries, since the fourth one's SETTINGS clause only overrides the setting it names.

Either option is correct for the residual, so if you still prefer the tag, go ahead.

qoega and others added 2 commits September 1, 2026 19:00
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@qoega

qoega commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

@PedroTadim all green

@PedroTadim

Copy link
Copy Markdown
Member

@qoega did you review the cursor bot's messages?

@qoega

qoega commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

I would prefer to create a followup issue for the cases it highlighted..

Comment thread src/Functions/FunctionsConversion.h Outdated
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@qoega maybe should trim this comment block

Comment thread src/Functions/FunctionsConversion.h Resolved
@PedroTadim

Copy link
Copy Markdown
Member

@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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@PedroTadim

Copy link
Copy Markdown
Member

@qoega should we merge this now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

optimize_injective_functions_in_group_by drops a constant-NULL grouping key on two-argument toString(x, NULL) — silent wrong result

7 participants