Skip to content

TimeSeries: enable dynamic remote-write routing via URL table prefix - #93833

Open
niyue wants to merge 73 commits into
ClickHouse:masterfrom
niyue:feature/dynamic-routing-remote-write
Open

niyue wants to merge 73 commits into
ClickHouse:masterfrom
niyue:feature/dynamic-routing-remote-write

Conversation

@niyue

@niyue niyue commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

This PR addresses #93831

Changelog category (leave one):

  • Improvement

Changelog entry

Support dynamic table routing for Prometheus remote-write based on the request URL, allowing a single handler to ingest data into multiple TimeSeries tables while preserving backward compatibility with fixed-table configuration.

Documentation entry for user-facing changes

  • Documentation is written

Motivation

In large-scale observability deployments, users often maintain many TimeSeries tables with similar schemas but different retention or ownership.
The existing Prometheus remote-write integration requires one handler per table, with the table name hard-coded in config.xml, making configuration and operations difficult to scale.

This change allows routing the target TimeSeries table dynamically from the request URL, enabling a single remote-write handler to serve multiple tables while keeping the previous behavior unchanged by default.

Parameters

  • enable_table_name_url_routing (handler option, default: false)
    When enabled, the handler expects URLs in the form /{database}/{table}/... and extracts the target table from the first two path segments.

  • prometheus_remote_write_dynamic_routing_enabled (TimeSeries table setting, default: false)
    Enables dynamic table routing for the specified TimeSeries table.
    Requests targeting tables without this setting enabled will be rejected.

Example usage

<handlers>
      <remote_write>
          <url>regex:^/[^/]+/[^/]+/write$</url>
          <handler>
              <type>remote_write</type>
              <enable_table_name_url_routing>true</enable_table_name_url_routing>
          </handler>
      </remote_write>
  </handlers>

Request example:

POST /{db_name}/{table_name}/write

Enable dynamic routing on the target TimeSeries table:

ALTER TABLE db.ts
MODIFY SETTING prometheus_remote_write_dynamic_routing_enabled = 1;

Note

Medium Risk
Adds request-path-driven table selection to the Prometheus remote_write handler and gates writes with a new per-table setting, so misconfiguration or unexpected URLs could redirect writes or cause new 4xx/5xx failures.

Overview
Enables Prometheus remote_write to dynamically route writes to different TimeSeries tables by extracting {database}/{table} from the request URL when enable_table_name_url_routing is set on the handler.

Dynamic routing is opt-in and additionally gated per target table via new TimeSeries setting prometheus_remote_write_dynamic_routing_enabled (default false); requests to tables without it error out. Docs and integration tests were updated with the required URL regex and validation coverage for both enabled/disabled cases.

Reviewed by Cursor Bugbot for commit d0e4020. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@CLAassistant

CLAassistant commented Jan 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... can be tested Allows running workflows for external contributors labels Jan 9, 2026
@nikitamikhaylov nikitamikhaylov self-assigned this Jan 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c57720]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED

AI Review

Summary

PR #93833 adds opt-in Prometheus remote-write routing through database and table URL segments, with per-table authorization, an alterable opt-in setting, and TimeSeries version 12. Reviewed head 8c57720260ce52be370177eb515321febf175c32, including the current diff, surrounding implementations, and all prior discussion. No unresolved blocker or major findings remain.

Missing context / blind spots
  • ⚠️ Runtime tests were not run locally. Current-head CI runtime jobs were dropped after the clang-tidy failure; rerunning CI after correcting those diagnostics will provide current-head execution evidence. The PR includes focused routing, authorization, encoding, compatibility, and settings-version regression coverage.
Findings

💡 Nits

  • src/Server/PrometheusRequestHandler.cpp:155: The dedicated clang-tidy job already reports performance-string-view-conversions; pass encoded directly to Poco::URI::decode.
  • src/Server/PrometheusRequestHandler.cpp:476: The same job reports modernize-use-nodiscard; mark isTimeSeriesTableNameSetFromRequest with [[nodiscard]]. These diagnostics are already surfaced by CI and do not warrant inline review threads.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jan 9, 2026
@niyue
niyue force-pushed the feature/dynamic-routing-remote-write branch 2 times, most recently from 7223ad8 to e923891 Compare January 10, 2026 13:13
@niyue

niyue commented Jan 10, 2026

Copy link
Copy Markdown
Contributor Author

Hi @nikitamikhaylov,
this PR is ready for review now. Could you please take a look when you have a chance?
Thanks!

@niyue

niyue commented Jan 11, 2026

Copy link
Copy Markdown
Contributor Author

There is one failure reported by CI (UndefinedBehaviorSanitizer: undefined behavior in ProfileEvents::getProfileEvents). It doesn’t appear to be related to this PR, but please let me know if you think I should address anything.

Thanks!

@JTCunning

Copy link
Copy Markdown
Contributor

Hello @niyue!

We appreciate the idea and the contribution.
Referring to an earlier design suggestion here, how would you feel about reversing the order of arguments in the URL, and having the structure be /<database>/<table>/.../write and having the configuration be a suffix instead of a prefix?

I ask because we'd like to adopt this strategy across more than just the remote-write protocol, and eventually introduce it to both the remote-read protocol and the query-api. If the prefix were to be used as it is authored today, it would unfortunately break the query-api protocol, as the majority of query-api clients (Grafana for example) expect a full URL as configuration, and then will issue queries like GET http://localhost:9363/<database>/<table>/api/v1/[query_range|query|etc] and ClickHouse would fail to route to the correct table if the dynamic resolution was looking for db/table suffixes instead of db/table prefixes.

The proposed design is similar to how other multi-tenant time-series databases route to specific tables/partitions/tenants/etc. You can find a similar design in VictoriaMetrics' URL format here.

Please let us know if you're receptive to rewriting your proposed change. Thanks again for authoring it!

@niyue
niyue force-pushed the feature/dynamic-routing-remote-write branch from b35f15e to f75f56c Compare January 14, 2026 06:18
@niyue

niyue commented Jan 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @JTCunning @nikitamikhaylov,

Thanks a lot for the guidance, and that makes perfect sense. I’ve updated the implementation to use the /{database}/ {table}/... URL prefix pattern and adjusted the routing accordingly (remote-write now expects /{db}/{table}/write,
with a boolean toggle enable_table_name_url_routing to enable this behavior). This should align better with query-api clients and leaves room to extend the same convention to remote-read/query-api.

This is my first contribution to ClickHouse, so I’m still learning the conventions, thanks for the patient guidance.

Could you please take another look when you have a chance? Appreciate the feedback!

Resolve trivial include conflict in `PrometheusRequestHandler.cpp`:
keep both `Common/QueryScope.h` (from master) and `Common/StringUtils.h`
(from the PR branch).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@niyue

niyue commented Mar 22, 2026

Copy link
Copy Markdown
Contributor Author

Thanks to @alexey-milovidov for updating the branch to the latest version

@nikitamikhaylov, I’ve addressed the PR comments, could you please take another look and let me know if it’s good to go? Appreciated.

alexey-milovidov and others added 3 commits May 16, 2026 05:33
The master branch already includes `Common/StringUtils.h`; the merge from
the PR branch produced a duplicate include. Drop the duplicate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master to refresh CI. The CI failures on commit 92a71c7 are all unrelated to this PR's changes:

@groeneai, please investigate the failures above and confirm if anything else is needed from this PR. The fix for the stress-test crash is in #104905.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov confirmed — both failures on 92a71c7 are unrelated to this PR. Cross-links + current state:

1. AST fuzzer (amd_debug, targeted) / (amd_debug, targeted, old_compatibility) — STID 4870-4f21

Logical error: AggregateFunctionArray: parameters mismatch ... is the chronic trunk hit in AggregateFunctionCombinatorArray (issue #104459, labels fuzz+testing).

Fix in flight: #104812 by @vitlibar — Resubmit #2: Preserve parameter types in timeseries aggregate functions — OPEN, BLOCKED, last activity 2026-05-17 23:25 UTC. The fix restores the invariant that IAggregateFunction::getParameters() returns exactly the parameters used to create the function, which prevents Array(<wrapped>) from observing a parameter-count mismatch downstream.

This PR touches only PrometheusRequestHandler*, TimeSeriesSettings.cpp, and one Prometheus integration test — none of which exercise the aggregate combinator code path.

2. Stress test (arm_debug) — Cannot start clickhouse-server / Check failed

The crash is the UBSan null deref in StorageTimeSeries::StorageTimeSeries at src/Storages/StorageTimeSeries.cpp:171. Regressing commit: 16e69dfc0f5 (make getInMemoryMetadataPtr aware of context) — tryGetTable returns nullptr during ATTACH at server startup, then the unconditional getInMemoryMetadataPtr deref aborts the server under abort_on_logical_error.yaml.

Fix in flight: #104905 by you — Fix UBSan null deref in StorageTimeSeries constructor — OPEN, BLOCKED, last activity 2026-05-18 01:21 UTC. Skips the LowCardinality validation when tryGetTable returns null.

This PR does not modify StorageTimeSeries.cpp; the only TimeSeries file it touches is TimeSeriesSettings.cpp (adding the new prometheus_remote_write_dynamic_routing_enabled setting).


Nothing additional needed from this PR. Once #104812 and #104905 land, a fresh CI rerun should clear both. SQLancer TLP* failures on the same commit are tracked separately under the chronic SQLancer family (issue #105009 / ~85% master rate over 30 days).

— monitoring under session cron:clickhouse-ci-task-worker:20260518-030000

…ation

`APIv1Impl::getImpl` threw `BAD_ARGUMENTS` for `/read` and `/query` requests on
a handler with `enable_table_name_url_routing` before any authentication, so a
protected handler answered 400 without running `authenticateUserByHTTP`
(and skipped the session audit path). The write-only check now runs in
`ReadImpl` / `QueryImpl` after authentication, and a test checks that wrong
credentials get the normal authentication error.

Addresses review: ClickHouse#93833 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
alexey-milovidov and others added 3 commits October 2, 2026 10:28
…ting-remote-write

Conflicts in `StorageTimeSeries.cpp` and `TimeSeriesSettings.cpp`: keep the new
deduplication cache settings from master and add
`prometheus_remote_write_dynamic_routing_enabled` next to them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Prometheus request URL

`Poco::URI` throws `Poco::URISyntaxException` on an invalid escape such as
`POST /default/%ZZ/write`, which was answered with HTTP 500, so remote-write
senders would retry the bad request forever. Convert it to `BAD_ARGUMENTS`
both where `HTMLForm` parses the request URI and where the routing path
segments are decoded, and add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ication`: expect HTTP 401

A wrong password of the `default` user over HTTP basic authentication is
reported as `REQUIRED_PASSWORD`, which is answered with HTTP 401, not 403.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/93833/54178ddee43fba9428ef73da0162f33c187091f5/pr/result_pr.json
ClickHouse#93833

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93833&sha=54178ddee43fba9428ef73da0162f33c187091f5&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. In Upgrade check (amd_release) the upgraded server cannot attach test_7.t6 (AggregateFunction(countResample(10, 5, 1), UInt64, UInt64), ARGUMENT_OUT_OF_BOUND). That table type is now rejected on purpose, see 05210_empty_serialized_aggregate_state_key. This is the same kind of problem as #121484 (for 05211), which was closed without merging.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

Already fixed by #121590 (merged into 26.9). The failing run on 54178dd (2026-09-23) used v26.9.2.8-stable as the previous release, which predates that fix, so the previous release's tests still left test_7.t6 behind.

v26.9.3.38-stable (2026-09-26) is the first release with the fix. Since then CIDB has 0 countResample is empty rows across 1560 Upgrade check (amd_release) runs, and the check on the current head 1861d9a (previous release v26.9.8.3-stable) is green. Master needs no change: 26.10 already rejects this type at CREATE, so it cannot leave such a table.

alexey-milovidov and others added 2 commits October 10, 2026 07:47
…` by `TimeSeries` version 8

The setting is persisted in the `TimeSeries` table metadata, so a table having it
could not be attached by an older server supporting version 7 (`UNKNOWN_SETTING`
instead of a clean version mismatch). Bump `TimeSeriesVersion::LATEST` to 8, as
it was done for the deduplication caches in version 7: the setting is rejected
by `checkTimeSeriesSettings` (on `CREATE` and `ALTER`) for tables of earlier
versions, and `CREATE TABLE ... AS` drops it when the new table gets an earlier
version.

ClickHouse#93833

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

Copy link
Copy Markdown
Member

🕵 Merged master and addressed the review about TimeSeries versioning: prometheus_remote_write_dynamic_routing_enabled now needs a table of version 8 or later (TimeSeriesVersion::LATEST is now 8). The previous AST fuzzer (amd_release, oracle) segfault (groupConcat over a Variant column after nested EXCEPT) is not related to this PR. It is tracked by #112043, which cites this exact report.

Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
alexey-milovidov and others added 3 commits October 17, 2026 19:30
…ting-remote-write

Master took `TimeSeries` version 8 for the "time ranges" target table and moved
`TimeSeriesVersion.h` to `src/Parsers/Prometheus`, so the
`prometheus_remote_write_dynamic_routing_enabled` setting now requires version 9
(`MIN_WITH_REMOTE_WRITE_DYNAMIC_ROUTING_SETTING = 9`, `LATEST = 9`). The docs, the
setting description, the gtest and the stateless test are updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The latest version is 9 after the merge with master, add version 8 to the list
of supported versions checked by the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 400, report the write-only rejection as Prometheus JSON

A table without `prometheus_remote_write_dynamic_routing_enabled` is a permanent
configuration mistake, but `SUPPORT_IS_DISABLED` was mapped to HTTP 500 which
remote-write senders retry for ever, so use `BAD_ARGUMENTS` (HTTP 400).

The rejection of non-write requests to a routing `prometheus_api_v1` handler is
moved into the `try` block of `QueryImpl` so it is reported in the Prometheus
JSON error envelope.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
Comment thread src/Server/PrometheusRequestHandler.cpp Resolved
alexey-milovidov and others added 2 commits October 26, 2026 06:32
…ting-remote-write

Master took `TimeSeries` versions 9 (UTC partition key of the recent samples table)
and 10 (no external targets or `id_type` / `id_generator` for new tables), so the
`prometheus_remote_write_dynamic_routing_enabled` setting now arrives with version 11:
`MIN_WITH_REMOTE_WRITE_DYNAMIC_ROUTING_SETTING = 11`, `LATEST = 11`. The documentation,
the gtest, `04612_timeseries_version_setting` and
`05355_time_series_remote_write_dynamic_routing_version` are updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th-only routing, column grants

- The `BAD_ARGUMENTS` error for a request target `Poco::URI` can't parse passes the URI through
  `maskSensitiveQueryParametersInURI` and no longer quotes the `Poco::URISyntaxException` message,
  which can contain a part of the query string with credentials.
- `APIv1Impl::getImpl` parses the request target before `handleRequest`, so a malformed escape there
  is now reported as `BAD_ARGUMENTS` (HTTP 400) too, instead of HTTP 500.
- `getRawPath` cuts off the query and the fragment first and recognizes the absolute form only at the
  beginning of the target, so a URL in a query parameter (e.g. `query_id`) can't select the table.
- The `INSERT` privilege is checked before the table lookup only with dynamic routing, and only on the
  columns every remote-write request inserts (`metric_name`, `tags`, `samples`). A handler with a fixed
  table again relies on the column-level check of the `INSERT` itself, so column-scoped grants work.
- The docs mention that the routing setting requires `TimeSeries` version 11 now.

Integration tests cover all four cases.

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

mintlify Bot commented Oct 26, 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 8c57720.

Approve preview

@vitlibar vitlibar self-assigned this Nov 2, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
…ting-remote-write

Master took `TimeSeries` version 11 for the buckets of samples, so the
`prometheus_remote_write_dynamic_routing_enabled` setting now arrives with
version 12 (`MIN_WITH_REMOTE_WRITE_DYNAMIC_ROUTING_SETTING = 12`, `LATEST = 12`).
The docs, the setting description and the tests pinning the latest version
are updated accordingly.

In the query API handler, master moved the table lookup out of the `try`
block; it is skipped when `enable_table_name_url_routing` is set, so such a
request is still rejected by `rejectURLPathRoutingForNonWriteEndpoint` in the
Prometheus JSON error envelope.

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

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflicts. master took TimeSeries version 11 for the buckets of samples, so prometheus_remote_write_dynamic_routing_enabled now requires version 12 (MIN_WITH_REMOTE_WRITE_DYNAMIC_ROUTING_SETTING = 12, TimeSeriesVersion::LATEST = 12). I updated the docs, the setting description, 04612_timeseries_version_setting (adds a version-11 table), 05355_time_series_remote_write_dynamic_routing_version (11 is rejected, 12 accepted), the latest-version line in 05140_time_series_bucketed_samples_table, and the gtest expectations. master also moved the table lookup in the query API handler out of the try block. That lookup is now skipped when enable_table_name_url_routing is set, so these requests are still rejected in the Prometheus JSON error envelope. Built locally: the three stateless tests and the TimeSeries/Prometheus gtests pass.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts). TimeSeriesVersion::LATEST is still 11 on master, so version 12 for prometheus_remote_write_dynamic_routing_enabled remains valid. The changed translation units compile. There are no unresolved review threads.

@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master e84734605

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.03% 93.17% +0.14%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 681 -> 682 (+1) 17 -> 16 (-1) 34 -> 34 (+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

alexey-milovidov and others added 2 commits November 20, 2026 17:35
# Conflicts:
#	tests/queries/0_stateless/05140_time_series_bucketed_samples_table.reference
The documentation of the `TimeSeries` table engine said the latest version is 11,
while this pull request bumps `TimeSeriesVersion::LATEST` to 12.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and resolved the conflict in 05140_time_series_bucketed_samples_table.reference: master changed the default codec and granularity of the samples table (ALP, ZSTD(4), index_granularity_bytes = 262144), and this pull request changes the version shown on the same line, so the line now has the new defaults with version 12. TimeSeriesVersion::LATEST is still 11 on master, so version 12 for prometheus_remote_write_dynamic_routing_enabled remains valid. Also updated the documentation text of the TimeSeries engine, which still said the latest version is 11.

The translation units changed here compile on the merged tree; I did not build a full binary or run the tests locally, so the new CI run is the verification. The previous CH Inc sync failure was a single test unrelated to TimeSeries or Prometheus on the previous head; the sync will re-run on the new head. There are no unresolved review threads.

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-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants