Skip to content

Add histogramExplicit and histogramExplicitOpenClosed aggregate functions - #118823

Open
apidtykan wants to merge 3 commits into
ClickHouse:masterfrom
apidtykan:add-histogram-count
Open

apidtykan wants to merge 3 commits into
ClickHouse:masterfrom
apidtykan:add-histogram-count

Conversation

@apidtykan

@apidtykan apidtykan commented Sep 8, 2026 •

Copy link
Copy Markdown

Changelog category (leave one):

  • New Feature

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

Add histogramExplicit and histogramExplicitOpenClosed aggregate functions for histograms with user-defined bucket boundaries and optional counters for NULL, NaN, and zero values.


Introducing histogramExplicit and histogramExplicitOpenClosed Aggregate Functions

Summary

This PR introduces the histogramExplicit and histogramExplicitOpenClosed aggregate functions for building histograms with fixed, user-defined bucket boundaries.

Unlike dynamic histogram functions, where bucket boundaries are derived from the input data, these functions keep the same boundaries across different datasets, time periods, or partitions. This makes them particularly useful for comparing distributions over time, including Data Drift Detection and metrics such as PSI, KL-divergence, and JS-divergence.


Features

Explicit bucket boundaries

Users provide the bucket boundaries directly:

SELECT histogramExplicit([0, 50, 100, 500, 1000])(order_amount)
FROM orders;

Boundary normalization

  • Up to 250 boundaries are supported.
  • Boundaries are sorted and deduplicated before constructing the histogram.
  • The histogram always includes unbounded first and last buckets, so values outside the explicitly specified range are still counted. Unbounded endpoints are represented as NULL in the result.

Special value tracking

Optional flags allow NULL, NaN, and zero values to be tracked separately from the regular histogram buckets:

SELECT histogramExplicit([0, 50, 100], 'null', 'zero')(order_amount)
FROM orders;

The result contains the histogram buckets followed by counters for the requested special values.

-- Result format: ([(lower, upper, count), ...],  [nan_count], [null_count], [zero_count])
([(NULL, 0, 1), (0, 50, 12), (50, 100, 5), (100, NULL, 2)], 0, 3)
  • Open/Closed interval control: histogramExplicitOpenClosed provides alternative boundary inclusion semantics for precise control over edge cases.

Use Cases

  • Data & Feature Drift Monitoring — consistent buckets for PSI, JS/KL divergence, and other distribution-comparison metrics.

  • SLA & Latency Percentile Tracking — predefined thresholds such as 50ms, 100ms, 500ms, and 1000ms.

  • Telemetry — consistent metric distributions across services, environments, or time periods.


Testing

Covered by C++ unit tests and stateless SQL tests:

Test File Coverage
04700_histogramExplicit Basic functionality, boundary sorting/deduplication, unbounded buckets, special value tracking ('null', 'nan', 'zero'), and state merging across execution threads
04701_histogramExplicit_data_types Type-aware boundary handling across Float, Decimal, 64/128/256-bit Integer types, fractional rounding, and precision limits
04702_histogramExplicit_errors Error handling and edge cases (e.g., empty boundary arrays, exceeding 250 boundaries limit, invalid special value parameters)

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

@CLAassistant

CLAassistant commented Sep 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ed97981]

Summary: ✅


AI Review

Summary

Adds histogramExplicit and histogramExplicitOpenClosed with explicit bucket boundaries, special-value counters, and supporting combinator changes. No actionable findings remain after reviewing the current code and all prior discussion. Validation against a CI binary whose source tree matches PR head reproduced all 120 reference-output lines and all 15 expected exceptions in the supplied stateless tests; focused checks also covered sparse grouping, nullable selector keys, and wrapped state compatibility.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 8, 2026
@apidtykan
apidtykan force-pushed the add-histogram-count branch 7 times, most recently from 9f970cc to 089a07c Compare September 10, 2026 04:09
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@apidtykan
apidtykan force-pushed the add-histogram-count branch 2 times, most recently from 9244d04 to d236827 Compare September 12, 2026 20:36
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ed9798106 with master 2f1968a33 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d2364ed14; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

5 object files changed (+2.41 MiB total), 1 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionHistogramExpl… new 2.39 MiB +2.39 MiB

719 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

10 translation units recompiled, 24 s compile time in total, 9 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/AggregateFunctions/AggregateFunctionHistogramExplicit.cpp: 12.5 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::IAggregateFunction* DB::createWithNumericType<DB::(anonymous namespace)::AggregateFunctionHisto… new 64.26 KiB +64.26 KiB

Job report

@apidtykan
apidtykan force-pushed the add-histogram-count branch 3 times, most recently from 0ac7db9 to ca20ce7 Compare September 21, 2026 12:29
@apidtykan

Copy link
Copy Markdown
Author

@nikitamikhaylov

  1. -If with a Nullable(UInt8) condition throws ILLEGAL_TYPE_OF_ARGUMENT

Solution: Leave unchanged. is_window_function = true is required for correct NULL counting. Relaxing the strict isUInt8 check in AggregateFunctionCombinatorIf::transformArguments() would affect all aggregate functions, so this remains outside the scope of this change.

  1. -OrNull treats entirely ignored input as data (NULL/NaN)
    AggregateFunctionOrFill::add() sets its flag unconditionally, and OrFill cannot check function-specific ignored values generically.

Solution: Add an opt-in virtual hook to IAggregateFunction (default: true), consulted in AggregateFunctionOrFill::insertResultIntoImpl(). When the hook reports no data, -OrNull returns NULL instead of delegating. This keeps the change additive and preserves existing behavior for other functions.

  1. State canonicalization through -OrNull / -OrDefault

Solution: Override getNormalizedStateType() directly in AggregateFunctionOrFill.h. It requests the nested function's normalized state and wraps it back in AggregateFunctionOrFill, ensuring the state layout and type name match correctly.

What do you think about this approach?

@apidtykan
apidtykan force-pushed the add-histogram-count branch 2 times, most recently from a9f0103 to fc5486c Compare September 29, 2026 15:54
@apidtykan
apidtykan force-pushed the add-histogram-count branch from fc5486c to 3872351 Compare October 18, 2026 13:59
@apidtykan

Copy link
Copy Markdown
Author

@clickhouse-bot add-label pr-autogenerated-docs

@mintlify

mintlify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit ed97981.

Approve preview

@apidtykan

Copy link
Copy Markdown
Author

@nikitamikhaylov
I added the .mdx stubs as requested, but I cannot edit the PR labels because the Labels field is disabled for me. Could you please add pr-autogenerated-docs ?

@apidtykan
apidtykan force-pushed the add-histogram-count branch 2 times, most recently from 8c5f6f8 to d2938e6 Compare October 23, 2026 07:17
@rschu1ze rschu1ze added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Nov 4, 2026
Add docs and patch CombinatorsArgMinArgMax

patch Decimal

patch ArgMinArgMax and OrFill

fixt style

fix orFill

fix UInt128/256

fix numbers

patch numeric type and add tests

patch roundMagnitudeToDouble

fix arm_tidy

fix double
@apidtykan
apidtykan force-pushed the add-histogram-count branch from fe21569 to 2379cf3 Compare November 5, 2026 16:08
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Nov 24, 2026
…ted job

ClickHouse#122111 made the targeted stateless and integration jobs SKIP instead of
ERROR when a test-selection CIDB request times out on every attempt
(`CIDBTimeoutError`). The first selection read, the strict previously-failed
lookup in `Targeting.get_previously_failed_tests_with_info`, re-wrapped any
exception as a plain `RuntimeError`, so a timeout there lost its class
before reaching either `except CIDBTimeoutError` handler and the shard
still ERRORed ("Failed to load test selection" in the stateless job, an
uncaught exception in the integration job). On a `pr-bugfix` PR that drops
`Bugfix validation` and fails `Finish Workflow / Post Hooks`.

Re-raise `CIDBTimeoutError` unchanged in strict mode. Every other failure
(a refused connection, an answered non-OK response) stays wrapped and keeps
failing the job, as ClickHouse#114730 intends. Best-effort mode is unchanged.

CIDB shows 3 such errors, all on 2026-09-24/25 during the CIDB overload
ClickHouse#122111 targets (PRs ClickHouse#118823, ClickHouse#117436, ClickHouse#114865).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants