Skip to content

Extract reusable ActionsDAG lineage computation into actionsDAGUtils - #114824

Merged
cv4g merged 8 commits into
masterfrom
extract-actionsdag-lineage
Aug 28, 2026
Merged

cv4g merged 8 commits into
masterfrom
extract-actionsdag-lineage

Conversation

@cv4g

@cv4g cv4g commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

The new traceActionsDAGLineage computes lineage for every ActionsDAG output using iterative traversal with memoization shared across all output roots. Each output is traced to at most one input through supported hops. Hops are classified as:

  • Identity
  • ValuePreserving
  • DistinctValuesBound, meaning output NDV is bounded by input NDV plus ndv_delta

Inputs and outputs are identified by position rather than column name, so the reusable lineage result remains unambiguous when names are duplicated.

remapColumnStats in the join-order optimizer now uses this API instead of its local describeValueHop/ backTrackColumnsInDag traversal.

This changes the call site as follows:

  • Lineage is computed once per ActionsDAG, with memoization shared across all outputs, instead of running an independent DFS for every statistics entry.
  • Statistics names that do not match a DAG input no longer trigger additional per-name traversals. A nonempty statistics map causes at most one lineage computation.
  • An explicit mapped.empty() guard preserves the common case where absent statistics require no lineage traversal.
  • Remapping becomes a direct loop over output lineage results, using the traced input position and ndv_delta.

The lineage-related complexity changes from approximately O(#stats × DAG) to O(DAG + #outputs), with the remaining statistics-map handling linear in the number of entries.

For outputs that can be represented unambiguously by the name-keyed statistics map, the computed statistics remain unchanged. The supported-hop and ndv_delta rules are equivalent to the previous implementation: nullable-to-non-nullable hops may add one distinct value, and the existing overflow guard remains in place. remapColumnStats does not currently distinguish between lineage kinds; it only uses traceability, input_position, and ndv_delta.

The reusable API handles duplicate names positionally. remapColumnStats itself remains keyed by column name and therefore cannot represent separate statistics for conflicting duplicate output names.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • Not for changelog

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

Version info

  • Merged into: 26.9.1.257 (included in 26.9 and later)

Add a reusable lineage computation to actionsDAGUtils that traces every
`ActionsDAG` output to at most one input via iterative, memoized
traversal. Each hop is classified as `Identity`, `ValuePreserving`, or
the weaker `DistinctValuesBound` (output NDV bounded by input NDV plus
`ndv_delta`), and results are keyed by input/output positions, so they
stay unambiguous under duplicated column names.

Rewire `remapColumnStats` in the join-order optimizer onto the new API,
replacing its hand-rolled `propagatesNdv`/`backTrackColumnsInDag` walk.
Skip the lineage walk entirely when there are no column stats to remap,
since statistics are usually absent.
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9463d80]

Summary: ✅


AI Review

Summary

This PR extracts reusable ActionsDAG lineage tracing out of remapColumnStats and adds focused coverage for duplicate-name and null-collapsing cases. The refactor is mostly straightforward, but one previously raised lineage-contract hole is still present in the current code, so I do not think the new helper is safe to treat as a general reusable proof yet.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Extract reusable ActionsDAG lineage computation into actionsDAGUtils #114824#discussion_r3796706856] [src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp:569] The generic deterministic-unary branch still classifies assumeNotNull as DistinctValuesBound, even though assumeNotNull explicitly allows arbitrary results for NULL rows and simply returns the nested column. That breaks the helper's advertised contract that DistinctValuesBound proves output_ndv <= input_ndv + ndv_delta: a nullable input with NDV = 0 can still expose multiple distinct nested values through assumeNotNull. Exclude assumeNotNull (and any equivalent nullable-stripping wrappers) from the generic branch, or model it as an unsupported hop, and add a focused regression test.
Final Verdict

Changes requested: the reusable lineage API still overclaims DistinctValuesBound for assumeNotNull, so it is not yet safe as a general contract.

LLVM Coverage Report

Measured on commit 9463d80.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9463d805a with master 90144f901 (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
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.27 MiB -3.06 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

4 object files changed (-14.09 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeJoin.cpp.o 690.04 KiB 650.86 KiB -39.19 KiB (-5.68%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp.o 165.07 KiB 190.17 KiB +25.09 KiB (+15.20%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +6.9 s (+6%) in total before that adjustment.

Job report

else if (node.children.size() == 1 && node.function_base->isDeterministic())
kind = ActionsDAGLineageKind::DistinctValuesBound;
else
return {};

@cv4g cv4g Aug 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

remapColumnStats previously used equivalent logic to determine whether an NDV bound propagates through a hop. The new lineage kinds retain stronger semantic information by distinguishing Identity, ValuePreserving, and DistinctValuesBound. remapColumnStats currently treats ValuePreserving and DistinctValuesBound equivalently because it only consumes input_position and ndv_delta.

|| child->kind == ActionsDAGLineageKind::ValuePreserving)
kind = ActionsDAGLineageKind::ValuePreserving;
result = ActionsDAGInputLineage{child->input_position, kind, child->ndv_delta + hop->ndv_delta};
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

remapColumnStats previously followed only children[0], so this preserves existing behavior. As a follow-up, add a child position to ActionsDAGLineageHop for multi-argument functions with one value-bearing child.
Supporting genuinely multi-source functions requires more than a set of child positions: the lineage result must represent multiple inputs and the hop must specify how their NDV bounds are composed. The composition logic currently around line 622 could then be extracted into a dedicated helper.

@cv4g cv4g changed the title Extract reusable ActionsDAG lineage Extract reusable ActionsDAG lineage computation into actionsDAGUtils Aug 17, 2026
@diegomestre2 diegomestre2 self-assigned this Aug 17, 2026
@@ -294,6 +295,59 @@ TEST(ColumnStatsDerivation, DeepChainOfFunctionsResolves)
/// The bound propagates through a chain of deterministic single-argument functions: no link can
/// increase the distinct count, so the final output is still bounded by the source column. A
/// multi-argument link anywhere in the chain breaks the propagation.

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.

I think this description is related to the test that was already in the file, maybe move it to the right place and add a specific description for this new test case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh, that one indeed belongs to ChainOfFunctionsPropagatesBound. Moved the comment back to it's front: e757ead

@diegomestre2 diegomestre2 left a comment

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.

Hi @cv4g , great work! The code is clean and straight to the point. I really like the trick with memoization. I left a few questions and comments, feel free to implement what you think makes sense. Once you are ready I can take a final look.

@cv4g
cv4g requested a review from diegomestre2 August 17, 2026 12:55
kind = ActionsDAGLineageKind::ValuePreserving;
else if (function_name == "_CAST" || function_name == "CAST")
kind = ActionsDAGLineageKind::DistinctValuesBound;
else if (node.children.size() == 1 && node.function_base->isDeterministic())

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 generic isDeterministic() bucket is too broad for the new reusable API. assumeNotNull is unary and deterministic, but its contract is explicitly weaker than "NDV <= input_ndv + 1": the docs say a NULL input may yield an arbitrary result, and FunctionAssumeNotNull::executeImpl just returns the nested column (src/Functions/assumeNotNull.cpp), so different NULL rows can surface different underlying values. That means traceActionsDAGLineage can now report a false DistinctValuesBound for nullable inputs, even though the exported type/comment presents it as a real proof for future callers. I think assumeNotNull (and any similar nullable-stripping wrappers with arbitrary null semantics) needs to be excluded from this generic branch or handled separately, with a focused regression test here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Let's address this in a follow-up PR. This PR prepares for re-use but should preserve the current behavior in order to make sure that remapColumnStats does not change too much. Having the re-usable API surface, we can then start opening pull requests to introduce additional call sites and follow up improvements concurrently.

@diegomestre2 diegomestre2 left a comment

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.

Thanks for addressing the comments and for the replies. Everything looks clear now. Feel free to merge it once CI is ready! Great work! It was fun to review it!

@cv4g

cv4g commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Pushed another merge commit. No conflicts but want to be sure no other issues arised due to changes merged in the meantime

@cv4g
cv4g added this pull request to the merge queue Aug 28, 2026
Merged via the queue into master with commit 50e9026 Aug 28, 2026
180 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants