Skip to content

Fix NDV and column width propagation through expressions - #114755

Open
XuJia0210 wants to merge 44 commits into
ClickHouse:masterfrom
XuJia0210:agent/ndv-constant-arguments
Open

XuJia0210 wants to merge 44 commits into
ClickHouse:masterfrom
XuJia0210:agent/ndv-constant-arguments

Conversation

@XuJia0210

@XuJia0210 XuJia0210 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Propagate NDV bounds through deterministic functions with exactly one non-constant argument, regardless of its position, such as dateTrunc('month', d). Previously, these expressions lost their input NDV, so aggregation cardinality estimates could fall back to the input row count.

Only reuse the input column's average byte width when it remains applicable. For example, concat(materialize(repeat('x', 1000)), s) must discard the width of s even though the result is also String. Value-preserving wrappers such as identity(s) retain the input width. This prevents invalid width estimates from affecting optimizer costs.

SQL regression coverage:

  • 04926_ndv_constant_arguments: NDV propagation with literals, shared non-folded constants, and scalar-subquery constants.
  • 05175_string_function_width: shuffle placement when concat discards the input width and identity preserves it.

Closes ClickHouse/clickhouse-private#68097

Changelog category (leave one):

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

Changelog entry:

Fix inaccurate cardinality estimates for deterministic functions with constant arguments and incorrect propagation of string width estimates, which can affect query plan selection.


Workflow [PR]
Sync PR [sync-upstream/pr/114755]

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa29f10]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
03836_tpch_join_order_plans FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) DROPPED

@XuJia0210
XuJia0210 marked this pull request as ready for review August 14, 2026 05:14
@XuJia0210 XuJia0210 added the can be tested Allows running workflows for external contributors label Aug 14, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cea4a9683 with master 62b7ea5c5 (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@XuJia0210
XuJia0210 force-pushed the agent/ndv-constant-arguments branch from 160fbca to 7c63f39 Compare August 18, 2026 03:21
@XuJia0210

Copy link
Copy Markdown
Contributor Author

Robert: it will be good to include a SQL test that demonstrates that the problem is resolved)

@cv4g cv4g self-assigned this Aug 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
Remove the four `auto_statistics_types` overrides from `04001`. Its existing reference matches with `use_statistics` enabled and disabled.

Correct TSV quote escaping in the `04926` expression labels using actual output. Both tests pass with statistics enabled; `04001` also passes with statistics disabled.

Related: ClickHouse#114755 (comment)
Related: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=114755&sha=46d1efc2092b6fa194e30902f29009d9468dcea5&name_0=PR&name_1=Fast%20test
Related: ClickHouse#114755
Use `plus(plus(materialize(1), materialize(1)), n)` in the existing NDV SQL case to cover shared constant arguments. Remove the corresponding gtest and retain the SQL NDV assertion.

Related: ClickHouse#114755 (comment)
Related: ClickHouse#114755
Check NDV bounds for `concat`, `substring`, `materialize`, and `identity`. Verify preserved and default string widths through shuffle placement with fixed statistics, following the existing width-plan SQL test.

Restore `gtest_column_stats_derivation.cpp` to the PR base. The new SQL and `04926` pass; the new test also passes five runs with randomized query and MergeTree settings.

Related: ClickHouse#114755 (comment)
Related: ClickHouse#114755 (comment)
Related: ClickHouse#114755
Keep `concat` NDV and width-reset coverage, and the `identity` width regression check. Update comments and expected output.

Related: ClickHouse#114755
Describe the string length change in `concat` and unchanged values in `identity` alongside the expected width behavior.

Related: ClickHouse#114755
Remove the duplicate NDV check and its setup. Rename the test to `05175_string_function_width` and retain the `concat` width reset and `identity` width preservation checks.

Related: ClickHouse#114755
Replace Boolean checks with the estimated `ShuffleExchange` rows. Explain the tested width behavior, expected row count and why the optimizer chooses it for `concat` and `identity`.

Related: ClickHouse#114755
@XuJia0210 XuJia0210 changed the title Propagate NDV through functions with constant arguments Fix NDV and column width propagation through expressions Sep 11, 2026
Use explicit traversal frames and cache both constant and non-constant
results. Exclude unfurled server-constant functions from constness inference.

Disable randomized settings in the fixed-plan join-order test and add
regressions for deep constant subtrees and distributed server constants.

Related: ClickHouse#114755
/// NDV counts only non-null values. A hop turning a Nullable first argument into a
/// NDV counts only non-null values. A hop turning a Nullable source argument into a
/// non-Nullable result can map NULL to one additional counted value.
const bool collapses_null

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.

assumeNotNull is still going through the generic collapses_null ? 1 : 0 NDV model just above, but that model is not sound for this function. FunctionAssumeNotNull::executeImpl returns ColumnNullable::getNestedColumnPtr() verbatim (src/Functions/assumeNotNull.cpp:70-79), and the nullable framework explicitly allows arbitrary hidden nested values under NULL rows (src/Functions/IFunction.cpp:241-246).

So assumeNotNull(nullable_expr) can expose far more than NDV(child) + 1 distinct values once the null map is stripped. That false bound then feeds straight into join / aggregation costing. Please keep the width preservation, but handle NDV separately here: either drop lineage for nullable assumeNotNull, or only keep it when the child is proven null-free, and add a regression with a nullable expression whose hidden nested values vary across NULL rows.

Keep the v2 format used by the existing read_rows reference. Randomized v1
with wide parts reports zero rows for the second DELETE instead of eight,
while both formats produce the correct deleted-row result.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@cv4g cv4g self-assigned this Oct 8, 2026
Check that `plus(length(queryID()), n)` does not inherit `NDV(n)` and
keeps the `aggregated[no_stats~100]` estimate.

ClickHouse#114755 (comment)
Reuse `allColumnFunctions` to check lambda bodies and captured lambdas before treating a precomputed column as constant. Extend the SQL regression with deterministic, non-deterministic, constant-subtree, and nested lambda cases.

Review: ClickHouse#114755 (comment)
Keep both `FunctionHelpers.h` from master and `FunctionsMiscellaneous.h` required for the folded lambda determinism check.
Propagate `isServerConstant` through lambda bodies using the existing recursive helpers. Reject server-specific functions in both constant-column checks and lineage hops, including lambdas with non-constant captures.

Extend the SQL regression with folded, nested, captured, and direct `addressToSymbol` cases.

Review: ClickHouse#114755 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Dear @cv4g, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh clickhouse-gh Bot unassigned cv4g Nov 9, 2026
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp
@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants