Skip to content

Store and ingest Prometheus native histograms in the TimeSeries engine - #115685

Closed
valerypetrov wants to merge 49 commits into
ClickHouse:masterfrom
valerypetrov:promql/native-histograms-storage
Closed

valerypetrov wants to merge 49 commits into
ClickHouse:masterfrom
valerypetrov:promql/native-histograms-storage

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

First slice of Prometheus native-histogram support for the TimeSeries engine (storage + ingestion). Today, timeseries[].histograms[] in a remote-write request is parsed and silently dropped with a 204; a Prometheus sender configured with send_native_histograms: true loses all histogram data. This PR makes that data storable and queryable via SQL:

  • Storage: a new optional HISTOGRAMS target table on the TimeSeries engine (alongside DATA/TAGS/METRICS), enabled with SETTINGS store_native_histograms = 1 or an explicit HISTOGRAMS [db.table | INNER ENGINE ...] clause. One row per histogram sample, mirroring the prompb.Histogram message so a stored histogram reads back exactly as it arrived (an integer-flavor histogram also keeps its counts exactly in count_int, zero_count_int, positive_values_int and negative_values_int, because Float64 is exact only up to 2^53): id, timestamp, flags (is_float / counter-reset hint / stale marker), schema, zero_threshold, count, sum, zero_count, positive/negative spans and bucket values, and custom_values for NHCB (schema −53). Bucket values are stored as absolutes (int-flavor deltas are decoded at ingest). A timeSeriesHistograms(db.table) table function mirrors timeSeriesData for introspection.
  • Ingestion: PrometheusRemoteWriteProtocol reads timeseries[].histograms[] — both the int (delta-encoded) and float flavors — validates span/bucket consistency (rejecting the request with INCORRECT_DATA/HTTP 400 on malformed data), preserves counter-reset hints and stale markers, updates the time range of the series (min_time/max_time) from histogram timestamps, and counts ingested histograms in a new PrometheusRemoteWriteHistograms profile event. The decoding is factored so a future remote-write 2.0 message path can reuse it. The vendored protobuf gains upstream's custom_values = 16 field.
  • Backward compatibility: tables without the HISTOGRAMS target work exactly as before — CREATE, ATTACH, and remote writes are unchanged; histogram samples sent to such a table are dropped with a rate-limited warning and counted in a separate PrometheusRemoteWriteDroppedHistograms profile event, so the loss is at least observable, instead of today's silent drop.

Everything stays behind allow_experimental_time_series_table. PromQL evaluation over histograms (histogram_quantile etc.), the HTTP query API JSON shapes, and remote-read output are explicitly out of scope for this PR and build on this storage layer.

Open design question (called out for reviewers): whether new tables should get the HISTOGRAMS target by default under the experimental flag rather than opt-in.

Tests

  • Stateless: CREATE/SHOW CREATE round-trip with and without the target, external histograms-table validation, timeSeriesHistograms() reads, ATTACH of a pre-histogram definition.
  • Integration (test_prometheus_protocols/test_native_histograms.py): remote-write of int, float, NHCB, and stale-marker histograms with spans, zero bucket and negative buckets, asserting every stored column; mixed float samples + histograms in one request; drop-with-warning on a 3-target table; invalid spans and negative decoded counts → 400.

Changelog category (leave one):

  • New Feature

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

The experimental TimeSeries table engine can now store Prometheus native histograms: a new optional HISTOGRAMS target table (enabled with store_native_histograms = 1), ingestion of native histograms from the Prometheus remote-write protocol, and a timeSeriesHistograms table function for reading them. Previously such samples were silently dropped.


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

valerypetrov and others added 4 commits August 20, 2026 14:54
…e histograms

Adds a fourth, optional target table 'histograms' to the TimeSeries engine,
enabled by the new 'store_native_histograms' setting or an explicit HISTOGRAMS
clause. Its schema stores one row per native histogram sample: id and timestamp
(shared layout with the samples table), flags (float/counter-reset-hint/gauge/
stale-marker bits), schema, zero_threshold, count, sum, zero_count, bucket
spans, absolute bucket values, and custom bucket boundaries (NHCB).

Enabled tables get an additional outer 'histograms' column - an array of
histogram tuples per series - routed to the target by TimeSeriesSink, which
also merges histogram timestamps into min_time/max_time of the tags table.
The stored histograms can be read back with the new timeSeriesHistograms()
table function. Tables without the target keep working unchanged, and their
definitions attach as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
… HISTOGRAMS target

Reads timeseries[].histograms[] from remote-write v1 requests: both the int
flavor (delta-encoded bucket counts, decoded to absolute values on ingestion)
and the float flavor (absolute counts). Span/bucket-array consistency is
validated and invalid data rejects the whole request with INCORRECT_DATA
(HTTP 400). The flags column gets the is-float bit, the counter reset hint,
the gauge bit, and the stale-marker bit (detected by the NaN payload of sum).

Histograms flow through the outer 'histograms' column of the block inserted
into the TimeSeries table, so ids and min_time/max_time are computed by the
same sink path as float samples. A table without the HISTOGRAMS target drops
incoming histograms with a warning instead of failing the write. The decoding
is factored into makeHistogramsColumn() for reuse by a future remote-write
2.0 message path. Adds the PrometheusRemoteWriteHistograms profile event and
the custom_values=16 field (NHCB, upstream prompb parity) to the vendored
protobuf.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Stateless: CREATE/SHOW CREATE round-trips with and without the HISTOGRAMS
target, inner histograms table schema, INSERT through the outer column and
reads via timeSeriesHistograms(), tags min_time/max_time from histogram
timestamps, DETACH/ATTACH of both pre-histogram and histogram-enabled
definitions, and external histograms table validation errors.

Integration (test_prometheus_protocols): remote-write of int, float, NHCB
(schema -53 with custom_values), and stale-marker histograms with every
stored column asserted; mixed samples+histograms; a 3-target table logging
a warning and dropping histograms while the write succeeds; invalid spans
and negative decoded bucket counts rejected with HTTP 400. The pre-generated
prompb pb2 descriptor gains the custom_values field (spliced to keep the
4.25-era gencode compatible with old and new protobuf runtimes).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Calling begin() and end() on two separate temporaries handed the vector
range constructor iterators into different arrays, making CREATE TABLE
... ENGINE = TimeSeries throw std::length_error.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Aug 20, 2026
@clickhouse-gh clickhouse-gh Bot added manual approve Manual approve required to run CI labels Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [da42ebb]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_tsan, 5/6) FAIL
test_replicated_database_active_node_taken/test.py::test_active_node_owned_by_another_server FAIL cidb
Stress test (amd_msan) FAIL
Logical error: GroupingAggregatedTransform pushed bucket A twice (STID: 3994-4c1d) FAIL cidb

AI Review

Summary

This PR adds an optional HISTOGRAMS target to the TimeSeries engine, ingests Prometheus native histograms from remote write, and wires the new data through SQL reads and the timeSeriesHistograms table function. The storage and read plumbing is mostly coherent now, but two correctness gaps remain: the remote-write decoder still accepts malformed custom-bucket histograms, and the new SQL histograms insert surface bypasses the validation entirely.

Findings

❌ Blockers

  • [src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp:266] The code validates only that schema is in range. For schema = -53, Prometheus-native custom buckets have additional invariants: the zero bucket and negative buckets are unused, and custom_values must be finite, strictly increasing custom boundaries. The current path still accepts malformed NHCB payloads and also accepts custom_values on standard schemas, so invalid histograms can be persisted instead of rejected as INCORRECT_DATA.
    Suggested fix: add schema-specific validation. For schema == -53, reject any negative_* buckets, reject a populated zero bucket, and require finite strictly increasing custom_values; for other schemas, reject non-empty custom_values.

⚠️ Majors

  • [src/Storages/TimeSeries/TimeSeriesSink.cpp:236] The new outer histograms column is documented and tested as an INSERT surface, but the sink copies tuple elements into the histograms target verbatim. That means INSERT INTO ts (..., histograms) can persist impossible histogram rows that the remote-write path would reject, so the histogram invariant only holds for one entrypoint.
    Suggested fix: centralize histogram validation and reuse it from both PrometheusRemoteWriteProtocol and TimeSeriesSink, or make the outer histograms column a read-only surface instead of a supported write path.
Tests
  • ⚠️ Add a focused integration case for malformed NHCBs: schema = -53 with negative_* buckets, a populated zero bucket, non-monotonic / non-finite custom_values, and custom_values on a standard schema.
  • ⚠️ If SQL INSERT into the outer histograms column remains supported, add a stateless rejection test for the same malformed shapes there too.
Final Verdict

Status: ⚠️ Request changes

  • Minimum required actions: enforce the missing custom-bucket invariants in the remote-write decoder, and either validate histograms on SQL insert as well or stop exposing that column as a supported write path.

LLVM Coverage Report

Measured on commit da42ebb.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 683/767 (89.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels Aug 20, 2026
@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 20, 2026
valerypetrov and others added 2 commits August 20, 2026 16:29
Address review findings on the native-histogram storage slice:

- Remote write: decide float-ness solely from the `count` oneof (upstream
  `IsFloatHistogram` parity) and reject mixed oneof arms / mismatched bucket
  flavors with `INCORRECT_DATA` instead of silently storing zeroes from the
  unset arm.
- Remote write: guard the int64 delta-decode accumulation against overflow,
  and reject out-of-range counter reset hints (proto3 enums are open) and
  out-of-range bucket schemas.
- Drop the redundant `IsGauge` flag bit (derivable from reset hint == GAUGE);
  reserve 0x08 and document the tuple as append-only.
- `CreateQueryUUIDs`: detect the histograms target only via the materialized
  target (normalizeTimeSeriesDefinition has already run), removing the raw-AST
  settings peek that threw on quoted bool spellings and could mint a phantom
  `HISTOGRAMS INNER UUID` on duplicate settings.
- `TimeSeriesSink`: compare the histogram tuple arity against the declared
  block type, not a compile-time constant, so older shorter tables keep working.
- Rate-limit the dropped-histograms warning to match the documented behavior.
- Add the `timeSeriesHistograms` docs page and integration tests for the new
  rejection paths.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Note for reviewers: the Fast test failure on the first push was a real bug — an iterator-range constructor over two temporaries in normalizeTimeSeriesDefinition produced a garbage vector size on CREATE TABLE ... ENGINE = TimeSeries, which on the CI machine allocated until the server was killed (locally it surfaced as std::length_error). Fixed in 80c07f7, and the stateless suite passes against a local build of the current head. The follow-up pushes are sitting in action_required — could a maintainer approve the pending workflow run so CI reports on the fixed head?

valerypetrov and others added 3 commits August 21, 2026 08:54
clang-tidy: initialize new_running, forward instead of moving the
make_spans_array forwarding references, and drop the no-op move into
ColumnWithTypeAndName's const-reference constructor.

Docs: the timeSeriesHistograms page had been edited by hand inside its
AUTOGENERATED region, so regenerate it from the table function's
description and move the histograms link into that description. Document
the histograms target table and the store_native_histograms setting in
the TimeSeries engine page, which gives the link its anchor, and add the
page to the navigation.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
The previous commit hand-wrote a histograms section into time-series.mdx,
but StorageTimeSeries.cpp already carries that documentation and the page
body is generated from it. Replace the hand-written section with the
generator's own text, so the page matches its source and the
#histograms-table anchor the table function links to exists.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Per review: the int flavor's counts were validated after delta decoding,
but the float flavor's count, zero count and bucket counts were stored
verbatim, so a remote-write request could persist negative bucket state and
still get a 204. Reject them. NaN compares false, so stale markers are
unaffected.

Also add PrometheusRemoteWriteDroppedHistograms, so a table without a
histograms target reports the drops as an event and not only in the log.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
valerypetrov and others added 2 commits August 21, 2026 15:58
count, zero_count and the decoded bucket counts are stored in Float64 columns,
so an integer histogram above 2^53 was silently rounded on ingest even though
the flags bit promises the sample round-trips as an integer. Reject those with
INCORRECT_DATA instead, and state the bound in the engine docs.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 22, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 22, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 22, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 22, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Aug 22, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 10, 2026
The histograms section of the time-series engine page, the
`timeSeriesHistograms` table-function page and its navigation entry are
regenerated reference docs owned by the base PR
ClickHouse#115685, which this branch is
stacked on. The Mintlify "No direct edits to generated or read-only docs"
check compares the AUTOGENERATED regions against the master merge base, so
every engine PR inheriting the base's regenerated regions fails it, and only
a maintainer can set the `pr-autogenerated-docs` label that exempts it.
Remove the three files' changes here so this PR's docs diff is empty; the
pages return when the branch is rebuilt onto master after ClickHouse#115685 merges.
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit da42ebbfdcb8137df6379ea9bf922ed6f370f9de was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

The `histograms` outer column was declared for tables with a "histograms"
target, but makeASTSelectFromTimeSeries() never routed it to that target:
`SELECT histograms FROM ts` fell into the tags-only branch and produced no
such column, which also broke `SELECT *` and `INSERT INTO dst SELECT * FROM src`
for histogram-enabled tables.

The read planner now builds the column from the "histograms" target the same
way `time_series` is built from "samples": a `__histograms` subquery grouped by
`id` collects one `groupArray` per element of the declared outer tuple (the
elements are named after the target's columns, in the order the sink writes
them) and casts the result to the declared named tuple type. The subquery is
joined to "tags" by `id` like the samples one; when both `time_series` and
`histograms` are requested the query anchors on "tags" and LEFT-joins both, so
a series with only one kind of samples is returned with an empty array for the
other kind instead of being dropped.

A new stateless test covers `SELECT histograms`, mixed reads with
`metric_name`/`tags`, `SELECT *`, and the `INSERT ... SELECT *` round-trip into
a second histogram-enabled table, reusing the data of
05024_timeseries_native_histograms.sql.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
valerypetrov and others added 4 commits September 15, 2026 21:32
…grams-storage

Master renamed the METRICS target to METRIC FAMILIES, renamed the outer `time_series`
column to `samples` behind the table version, and split normalizeTimeSeriesDefinition
into a wrapper plus normalizeTimeSeriesDefinitionImpl. The histograms target is carried
over on top of all three.

Resolved: docs/reference/engines/table-engines/integrations/time-series.mdx,
src/Databases/DDLDependencyVisitor.cpp, src/Parsers/CreateQueryUUIDs.cpp,
src/Parsers/ParserCreateQuery.cpp, src/Storages/StorageTimeSeries.{h,cpp},
src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp,
src/Storages/TimeSeries/TimeSeriesColumnNames.h,
src/Storages/TimeSeries/TimeSeriesSink.{h,cpp},
src/Storages/TimeSeries/makeASTSelectFromTimeSeries.{h,cpp},
src/Storages/TimeSeries/normalizeTimeSeriesDefinition.cpp,
src/TableFunctions/TableFunctionTimeSeries.{h,cpp}.

The histograms hunks of normalizeTimeSeriesDefinition.cpp moved into master's new
normalizeTimeSeriesDefinitionImpl.cpp; makeBlock()/makeTimeSeriesBlock() and
generateOuterColumns() keep both sides' new parameters instead of one replacing the
other; buildSelectQueryFromSamplesOnly() gave way to the generic
buildSelectQueryFromDataTableOnly(); the read test now inserts into `samples`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
# Conflicts:
#	docs/_migration/slug-map.csv
#	docs/_site/redirects.json
#	docs/reference/engines/table-engines/integrations/time-series.mdx
#	docs/reference/navigation.json
…tograms-storage

Resolved src/Storages/StorageTimeSeries.cpp: kept the PR's store_native_histograms
and histograms_index_granularity settings rows and took master's version default 5.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 23, 2026
Merging the base branches brought back the histograms section of the
`TimeSeries` engine page and the `timeSeriesHistograms` rows in
`docs/_migration/slug-map.csv` and `docs/_site/redirects.json`, which
belong to the storage PR ClickHouse#115685. The engine page change sits inside an
`AUTOGENERATED` region, so the Docs check "No direct edits to generated or
read-only docs" fails without the `pr-autogenerated-docs` label, and the
slug-map row and redirect point to a `timeSeriesHistograms` page that does
not exist on this branch. Restore the three files to master so this PR's
docs diff is empty, as done before in 4ba61c4.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The docs check rejects any change inside `AUTOGENERATED` regions unless the PR
carries the `pr-autogenerated-docs` label. The `TimeSeries` engine page is one
generated region, so restore it; its histograms text already lives in the
engine documentation in `StorageTimeSeries.cpp` and the docs generator will
pick it up. The new `timeSeriesHistograms` page is kept as a hand-written page
without markers, since adding a new marker pair also counts as a generated
edit; its link no longer points at the `#histograms-table` anchor, which only
appears once the engine page is regenerated.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 23, 2026
Merging the base branches brought back the histograms section of the
`TimeSeries` engine page and the `timeSeriesHistograms` rows in
`docs/_migration/slug-map.csv` and `docs/_site/redirects.json`, which
belong to the storage PR ClickHouse#115685. The engine page change sits inside an
`AUTOGENERATED` region, so the Docs check "No direct edits to generated or
read-only docs" fails without the `pr-autogenerated-docs` label, and the
slug-map row and redirect point to a `timeSeriesHistograms` page that does
not exist on this branch. Restore the three files to master so this PR's
docs diff is empty, as done before in 4ba61c4.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…tograms-storage

Resolve conflicts with master's TimeSeries changes (version 6, `metric_family_name` renamed to
`metric_family`, `scalar_type` renamed to `value_type`, samples read as a cast `groupArray` of tuples):
keep the histograms target alongside the new version-aware metric family column, pass the declared
type of the outer samples column through the PR's shared `makeGroupedByIdTableElement` helper,
and read histograms with one `groupArray` of tuples too, so the elements of a histogram sample
can't be ordered differently by separate `groupArray` calls.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 23, 2026
The merge of the base branches brought back the `timeSeriesHistograms` page and its navigation
entry, which belong to the storage PR ClickHouse#115685. Restore them to master so this PR's docs diff stays
empty, as done before in 4c5e392.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
if (histogram.reset_hint() < prometheus::Histogram::UNKNOWN || histogram.reset_hint() > prometheus::Histogram::GAUGE)
throw Exception(ErrorCodes::INCORRECT_DATA,
"Native histogram has an unknown counter reset hint: {}", static_cast<int>(histogram.reset_hint()));
if (histogram.schema() < -53 || histogram.schema() > 8)

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 only bounds schema numerically, but schema = -53 (custom buckets / NHCB) has stricter structural rules than the standard schemas. This path still accepts payloads with negative_spans / negative_*, a populated zero bucket, or arbitrary custom_values (including non-monotonic or non-finite values), and it also accepts custom_values on non--53 schemas.

That means we can persist malformed native histograms even though this PR otherwise treats malformed remote-write histograms as INCORRECT_DATA. Please add schema-specific validation here: for schema == -53, require negative_* to be empty, the zero bucket to be unused, and custom_values to be finite and strictly increasing; for other schemas, reject non-empty custom_values.

if (num_histograms > 0)
{
out_id_column.insertManyFrom(id_column, id_index, num_histograms);
for (size_t j = 0; j != out_columns.size(); ++j)

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.

The new outer histograms column is now a public INSERT surface, but this path just copies every tuple element into the target table verbatim. That bypasses all of the validation in PrometheusRemoteWriteProtocol, so INSERT INTO ts (..., histograms) can store rows that remote write would reject: malformed schema = -53 custom-bucket histograms, mismatched float / int carrier fields, impossible bucket layouts, and so on.

Because those rows are then exposed through timeSeriesHistograms and the regular histograms read path, the histogram validation needs to be shared here too (or the outer histograms column should stop being treated as a supported write surface).

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 3ac850cde

Suite Baseline Current Delta
Prometheus compliance 96.47% 96.47% +0.00%
Extended support (upstream engine tests) 77.32% 77.32% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 520 -> 520 (+0) 3 -> 3 (+0) 16 -> 16 (+0)
Extended support (upstream engine tests) 566 -> 566 (+0) 141 -> 141 (+0) 25 -> 25 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

valerypetrov and others added 9 commits September 29, 2026 09:40
# Conflicts:
#	src/Storages/StorageTimeSeries.cpp
#	src/Storages/TimeSeries/TimeSeriesSettings.cpp
#	src/Storages/TimeSeries/TimeSeriesSink.cpp
`validateTimeSeriesHistogramSample` now checks every histogram sample for both the Prometheus
remote-write protocol and an `INSERT` into the outer `histograms` column: known flags and schema,
non-negative counts which are NaN only in a stale marker, spans covering exactly the bucket values,
the custom-bucket rules of Prometheus (no negative buckets, an unused zero bucket, finite strictly
increasing bounds covering the bucket indexes), no custom bounds for an exponential schema, and exact
integer counts matching the counts of an integer histogram (empty for a float one).

`TimeSeriesSink` validates and assembles the histograms block before pushing anything to the target
tables, so a rejected `INSERT` leaves no tags or samples behind.

Fix the test rows with a `negative_values_int` carrier for an empty negative side.

PR: ClickHouse#115685

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`timeSeriesHistograms` returned the inner histograms table without checking any grant on
the TimeSeries table, so a user without access to it could read its histograms, see the
structure, and learn whether the table and its histograms target exist.

The function now asks for SHOW COLUMNS on the TimeSeries table before it looks the table
up, and for SELECT (or INSERT) on it before it returns the histograms table. The test
covers DESCRIBE, SELECT and a missing table for each grant level.

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

Master bf041cd made SecretArgumentsSpec a required argument of
TableFunctionFactory::registerFunction, so the timeSeriesHistograms
registration no longer compiled after the merge. It takes no secret
arguments, so it gets an empty spec like the other TimeSeries table functions.

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

Master added the optional "time ranges" target table (ClickHouse#121924), which now
holds min_time and max_time instead of the tags table, and moved the
CREATE-query setting helpers to Parsers/Prometheus/CreateQueryTimeSeriesSettings.

The histograms target becomes the third optional target: it is counted by
countTimeSeriesInnerTables, gets its UUID through the new
isTimeSeriesHistogramsTargetEnabled helper, and a histogram-only time series
now gets a row in the time ranges table, so selectors filtering by time still
find it. The tests read min_time and max_time from timeSeriesTimeRanges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's ClickHouse#120960 changed removeGeneratedInnerEngine: each target now sets engine_is_generated, and a sorting key is dropped only while no primary key is declared. The histograms case kept the old early-return form, so after the merge its generated engine was never stripped and a declared PRIMARY KEY lost its ORDER BY on CREATE TABLE ... AS.

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

Master's TimeSeries version 10 drops external targets, so the external histograms test cases are pinned to version 9.

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

mintlify Bot commented Oct 23, 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 091c26f.

Approve preview

valerypetrov and others added 2 commits October 28, 2026 14:27
…grams-storage

# Conflicts:
#	src/TableFunctions/TableFunctionTimeSeries.cpp
@vitlibar

vitlibar commented Nov 1, 2026

Copy link
Copy Markdown
Member

There is a better implementation of the native histogram support in #122051

@vitlibar vitlibar closed this Nov 1, 2026
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-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... manual approve Manual approve required to run CI pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants