Skip to content

Optimize cramersV, cramersVBiasCorrected, theilsU, and contingency when used with window functions - #93384

Merged
nihalzp merged 83 commits into
ClickHouse:masterfrom
nihalzp:optimize-crosstab-functions
Apr 23, 2026
Merged

nihalzp merged 83 commits into
ClickHouse:masterfrom
nihalzp:optimize-crosstab-functions

Conversation

@nihalzp

@nihalzp nihalzp commented Jan 4, 2026 •

Copy link
Copy Markdown
Member
SELECT cramersV(number, number) OVER (ORDER BY number) FROM numbers(20000) FORMAT NULL;

Master: 4.198 sec
PR: 0.014 sec

These functions were running in quadratic time complexity when used in window context. This PR adds window variants of these aggregate functions. When a query uses these aggregates in a window context, resolveFunction chooses the window variants creators.

We do not use these Window versions for non-window context such as GROUP BY because they will be slower. Window versions are optimized for incremental updates so that getResult is O(1).

image

Changelog category (leave one):

  • Performance Improvement

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

Optimize cramersV, cramersVBiasCorrected, theilsU, and contingency when used with window functions. Closes #83521.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.27

@nihalzp
nihalzp requested a review from Copilot January 4, 2026 20:33
@clickhouse-gh

clickhouse-gh Bot commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [31743b5]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) FAIL
03008_uniq_exact_equal_ranges FAIL cidb, issue ISSUE CREATED
Integration tests (amd_binary_excluded_from_llvm) FAIL
test_trace_log_memory_context/test.py::test_memory_context_in_trace_log FAIL cidb IGNORED

AI Review

Summary

This PR adds Window state variants for cross-tab aggregate functions and wires variant-aware resolution/merging so window execution avoids quadratic behavior. Verdict: ⚠️ request changes due to two unresolved correctness-edge issues in CrossTab window state bookkeeping that can produce incorrect behavior after extreme-but-valid state growth/merge counts.

Findings

⚠️ Majors

  • [src/AggregateFunctions/CrossTab.h:324,395,450] ab_edges.size() is cast to UInt32 and uses UInt32(-1) as INVALID_EDGE_IDX. If size reaches 2^32 - 1, a real edge index collides with sentinel semantics, breaking skip logic and adjacency handling.
    Suggested fix: replace chassert-only guards with explicit Exception(ErrorCodes::CORRUPTED_DATA, ...) before index assignment.
  • [src/AggregateFunctions/CrossTab.h:642-645,731-739] epoch intentionally wraps without reset, while 0 is also the “unmarked” value in a_epoch_mark; after wrap, merge bookkeeping can skip edges incorrectly.
    Suggested fix: on wrap (++epoch == 0), clear a_epoch_mark to zero and set epoch = 1.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ✅
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Add hard runtime bounds checks (with exception) for edge-index capacity instead of chassert-only protection.
  2. Make epoch wraparound safe by resetting marks and restarting epoch from 1.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 4, 2026

Copilot AI 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.

Pull request overview

This PR optimizes four statistical aggregate functions (cramersV, cramersVBiasCorrected, theilsU, and contingency) when used with window functions by introducing specialized *Window variants. The optimization achieves ~600x performance improvement (8.575s → 0.014s) by replacing O(n) getResult() complexity with O(1) or O(log n) alternatives, making them suitable for window contexts where getResult() is called frequently. The rewrite from standard to window variants happens automatically via rewriteAggregateFunctionNameForWindowIfNeeded in the query resolver.

Key Changes

  • Added CrossTabWindowPhiSquaredData base class that maintains an incrementally-updated phi_term_sum using adjacency lists for efficient updates
  • Implemented specialized window variants: TheilsUWindowData, CramersVWindowData, CramersVBiasCorrectedWindowData, and ContingencyWindowData
  • Added automatic function rewriting logic in both analyzer and expression analyzer paths

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/AggregateFunctions/CrossTab.h Adds CrossTabWindowPhiSquaredData class with incremental phi-squared calculation; optimizes phi calculation in CrossTabData
src/AggregateFunctions/AggregateFunctionTheilsU.cpp Implements TheilsUWindowData with cached entropy sums for O(1) results; fixes documentation range description
src/AggregateFunctions/AggregateFunctionCramersV.cpp Adds CramersVWindowData variant and updates test examples
src/AggregateFunctions/AggregateFunctionCramersVBiasCorrected.cpp Adds CramersVBiasCorrectedWindowData variant with consistent computation logic
src/AggregateFunctions/AggregateFunctionContingencyCoefficient.cpp Adds ContingencyWindowData variant
src/Analyzer/Resolve/resolveFunction.cpp Implements rewriteAggregateFunctionNameForWindowIfNeeded to automatically select window variants
src/Interpreters/ExpressionAnalyzer.cpp Adds same rewriting logic for non-analyzer code path
tests/performance/contingency_functions.xml Adds performance benchmarks covering window and non-window cases
tests/queries/0_stateless/03781_contingency_functions_resolve.sql Tests that resolver correctly rewrites to window variants
tests/queries/0_stateless/03782_contingency_window_functions_state_serialize_deserialize.sql Tests state serialization/deserialization roundtrips
tests/queries/0_stateless/03783_contingency_window_functions_distributed.sql Tests window variants work correctly in distributed mode

Comment thread src/AggregateFunctions/CrossTab.h Resolved
Comment thread src/AggregateFunctions/CrossTab.h Resolved
@UnamedRus

Copy link
Copy Markdown
Contributor

Slightly different direction, but for that particular window

SELECT cramersV(number, number) OVER () FROM numbers(20000);

It actually does not change aggregated state between calling of getResult ( as window is the same for all rows)

Could we have flag and cached result value in function.
So, if we call getResult, it will set flag to true and save result in cache. and if add/merge function is called, it would just reset flag to false and clear cache.

But, it wouldn't work for windows if it's rolling or adding.

@nihalzp

nihalzp commented Jan 5, 2026

Copy link
Copy Markdown
Member Author

Yes, you are right. For this format:

SELECT cramersV(number, number) OVER () FROM numbers(20000);

we can definitely use your idea; but that is a different problem and require changes in various other places.

The PR also optimizes any window functions like rolling or partition. For example:

SELECT cramersV(number, number) OVER (ORDER BY number) FROM numbers(20000);

@@ -1,3 +1,22 @@
SELECT 'Sanity Check to ensure window variant is choosen. Non-window variant would take too long';

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.

Typo: choosen → chosen.

</query>

<query>
-- Worst-case performance test for `CrossTabWindowPhiSquaredData` inherited aggregate functions

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.

Typo in class name: CrossTabWindowPhiSquaredData should be CrossTabPhiSquaredWindowData.

@azat azat left a comment

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.

I have not looked at the implementation of optimized version for window states (there was already approve before), everything else looks good, also PTAL at some minor comments

Comment thread src/AggregateFunctions/CrossTab.h Resolved
Comment thread src/AggregateFunctions/CrossTab.h Resolved
Comment thread src/AggregateFunctions/CrossTab.h Resolved
Comment thread src/AggregateFunctions/CrossTab.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 95.63% (940/983) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Apr 23, 2026
Merged via the queue into ClickHouse:master with commit 6f79d40 Apr 23, 2026
158 of 161 checks passed
@nihalzp
nihalzp deleted the optimize-crosstab-functions branch April 23, 2026 04:47
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 23, 2026
@groeneai groeneai mentioned this pull request Jun 4, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

7 participants