Skip to content

fix(promql): Inherit TimeSeries row policies in the inner tags table. - #127035

Draft
JTCunning wants to merge 11 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/promql-row-policy-propagation
Draft

JTCunning wants to merge 11 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/promql-row-policy-propagation

Conversation

@JTCunning

@JTCunning JTCunning commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

A row policy on a TimeSeries table only filtered plain SELECT queries. PromQL reads (prometheusQuery, prometheusQueryRange, the promql dialect, the Prometheus HTTP API, remote read) read the tags target directly, where no policy applied. A tenant limited to tags['x_org_id'] = 'org-a' could therefore read every tenant's series.

The TimeSeries table now translates its own SELECT row policy into a predicate over the tags target and adds that predicate to every tags-table read it generates. The reads covered are the PromQL functions, the promql dialect, the HTTP query, series, labels, and values endpoints, remote read, federate, and the visible-metric-names subquery of /api/v1/metadata. The predicate uses the dedicated tag columns for __name__ and for tags_to_columns tags, so a series whose stored map omits those tags is filtered as the outer table filters it.

The timeSeriesTags table function fails with ACCESS_DENIED while a row policy applies to the table. Direct reads of the inner tags table are not filtered by the owner's policy. Grant SELECT on that table only to users who may read every series.

A policy that uses a column the tags target lacks, such as samples, still works for plain SELECT. It fails PromQL reads with UNKNOWN_IDENTIFIER rather than returning unfiltered rows.

Changelog category (leave one):

  • Experimental Feature

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

Row policies on a TimeSeries table now apply to PromQL queries, the Prometheus HTTP API, and remote read.


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

@JTCunning JTCunning added can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... labels Oct 20, 2026
A row policy created on a `TimeSeries` table applied only to `SELECT`
queries on that table. PromQL reads (`prometheusQuery`,
`prometheusQueryRange`, the `promql` dialect, the Prometheus HTTP API
and remote read) select time series from the inner tags table directly,
and the planner attaches a row policy only to the storage it scans, so a
tenant restricted to `tags['tenant'] = 'a'` could read every tenant.

The inner tags table now inherits the `SELECT` row policies of its
`TimeSeries` table. `collectRowPolicyFilters` resolves the owner of an
inner tags table with `StorageTimeSeries::tryGetOwnerOfInnerTagsTable`
(by UUID for `.inner_id.tags.<uuid>`, by name for `.inner.tags.<name>`)
and adds the owner's policies to the filter. The inner tags table stores
every tag of every series in its `tags` Map, including `__name__` and
the tags promoted with `tags_to_columns`, so the policy expression
applies to it as written and the generated SQL does not change.

The read of the `TimeSeries` table itself marks its context with
`is_time_series_inner_read_by_owner`, so a plain `SELECT` evaluates the
policy once on the outer read and not again on the inner scan. A policy
over a column the inner tags table lacks, for example `samples`, keeps
working for `SELECT` and fails a PromQL read with `UNKNOWN_IDENTIFIER`.

The `TimeSeries` engine documentation gains a Row policies section.
…policy

The `/api/v1/metadata` endpoint reads the inner metrics table, which has
no tags, so a row policy on the `TimeSeries` table could not filter it
and every metric family was returned.

When the user has an effective `SELECT` row policy on the `TimeSeries`
table, `getMetadata` adds a condition which keeps only the metric
families with at least one metric name (the family plus the suffixes of
its type) among the metric names of the inner tags table. The inner
tags table inherits the policy, so that subquery sees only the visible
series.
…er tags table

The test creates a plain and a promoted `TimeSeries` table, a restricted
user, and a `SELECT` row policy on the `TimeSeries` table. It checks that
the policy filters `SELECT` from the table, `timeSeriesTags`, the inner
tags table itself, `prometheusQuery`, `prometheusQueryRange` and the
`promql` dialect, that `timeSeriesSamples` stays unfiltered, that the
inherited policy is recorded in `used_row_policies`, that a policy on
the inner tags table combines with the inherited one, and that a policy
on a column the inner tags table lacks keeps working for `SELECT` but
fails the PromQL read with `UNKNOWN_IDENTIFIER`.
…s row policy

The stateless server configuration exposes no Prometheus API handlers,
so the HTTP paths need an integration test. With a `SELECT` row policy
on the `TimeSeries` table, the test checks `/api/v1/query`,
`/api/v1/query_range`, `/api/v1/series`, `/api/v1/labels`,
`/api/v1/label/<name>/values`, `/api/v1/metadata` and remote read for a
restricted user and for the default user, and checks that a policy on
the `samples` column fails a PromQL query with a `bad_data` error.

The remote read helpers accept an `auth` argument for that.
@JTCunning
JTCunning force-pushed the jtcunning/promql-row-policy-propagation branch from d03877b to 6b9cbd3 Compare October 20, 2026 21:52
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1945467]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05427_time_series_row_policy_inner_tags FAIL cidb

AI Review

Summary

The PR applies TimeSeries row policies to generated PromQL and Prometheus reads, filters visible metric metadata, and refuses timeSeriesTags under an effective policy. The revised approach addresses the external-target and owner-lookup problems, but policy translation still permits a tags-subcolumn bypass and rejects valid lambda policies. ❌ Block pending both fixes.

Missing context / blind spots
  • ⚠️ Runtime reproductions were not run: this checkout has no ClickHouse binary or build directory. The findings follow concrete source traces; running the focused cases below against the PR binary would complete validation.
Findings

❌ Blockers

  • src/Storages/TimeSeries/makeASTSelectFromTimeSeries.cpp:956: Preserve outer tag semantics for subcolumns. The rewrite handles only the bare tags identifier, so tags.keys and tags.values remain accesses to the stored map; the validator also explicitly skips compound identifiers. Reuse the test's older partial-map row with dedicated tenant = 'b' and stored tags = {'instance': 'b1'}, and apply USING NOT has(tags.keys, 'tenant'). A plain SELECT reconstructs the map, finds tenant, and excludes this row. The generated tags query sees no stored tenant key, accepts the row, and exposes its series through PromQL and the HTTP/remote-read paths. Rewrite subcolumns against the reconstructed outer map, or reject unsupported references before reading. This is the remaining instance of the existing policy-reconstruction finding; keep that thread open without another inline comment.

⚠️ Majors

  • src/Storages/TimeSeries/makeASTSelectFromTimeSeries.cpp:880: Validate actual column references within their scope. USING arrayExists(x -> x = 'a', [tags['tenant']]) is a valid tags-only policy, but the validator treats the lambda declaration and bound uses of x as table columns and throws UNKNOWN_IDENTIFIER. Subquery-local identifiers are checked against the wrong schema too, and rewriting a lambda parameter named tags replaces its binding. Use scope-aware rewriting/validation or resolved column references, preserving rejection of genuinely unavailable outer columns.
Tests
  • ⚠️ Extend the partial-map fixture with NOT has(tags.keys, 'tenant'); compare plain SELECT with prometheusQuery and assert that the excluded series stays hidden.
  • ⚠️ Add a stateless lambda-policy case comparing plain SELECT and prometheusQuery, including a parameter named tags, while keeping the existing free-samples rejection.
Final Verdict

Status: ❌ Block. Preserve policy semantics for map subcolumns and make policy rewriting/validation respect expression scopes, with the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Oct 20, 2026
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
/// table apply to it as they are. The TimeSeries table's own read already evaluated them on its context.
if (!context->isTimeSeriesInnerReadByOwner())
if (auto owner = StorageTimeSeries::tryGetOwnerOfInnerTagsTable(storage_id, context))
collectRowPolicyFilters(*owner, context, result, visited);

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.

❌ Blocker: evaluate the inherited policy against reconstructed tags.

The stored inner tags map does not always have the same contents as the outer column. Existing tables written by older versions omit __name__ and tags promoted with tags_to_columns; makeExpressionForOuterTags deliberately reconstructs them from the dedicated columns. Applying the outer expression directly to the stored map changes its result: for an old row with dedicated tenant = 'b' and no tenant key in tags, tags['tenant'] != 'b' is false on the outer table but true here ('' != 'b'). PromQL and HTTP reads therefore expose a series excluded by the policy.

Reconstruct the outer tag values before evaluating the inherited filter, or translate the filter with equivalent semantics. Add a regression using the older partial-map representation; inserting fresh rows into a promoted table does not exercise it.

Comment thread src/Storages/StorageTimeSeries.cpp Resolved
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1945467c6 with master da9125b5e (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

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

9 object files changed (+60.34 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/makeASTSelectFromTimeSeries.cpp.o 176.32 KiB 208.00 KiB +31.68 KiB (+17.97%)
src/CMakeFiles/dbms.dir/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp.o 293.16 KiB 311.68 KiB +18.52 KiB (+6.32%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×1.07 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.1 s 18.9 s +11.3 s (+149%)
Compile time of recompiled translation units

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

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

Job report

…w-policy-propagation

# Conflicts:
#	src/Interpreters/Context.cpp
#	src/Interpreters/Context.h
#	src/Storages/StorageTimeSeries.cpp
#	src/Storages/TimeSeries/PrometheusHTTPProtocolAPI.cpp
Translate the TimeSeries SELECT row policy onto tags-target columns and
inject it where the storage builds tags-table queries. Remove the pull-side
owner lookup and the Context exemption flag.
Filter /api/v1/metadata by the translated tags predicate, refuse
timeSeriesTags when the owner has an effective row policy, and document
the push-side behavior.
Expect timeSeriesTags to be denied under a policy, keep direct inner tags
reads unfiltered, qualify table-function names for parallel replicas, and
cover version-9 external tags plus partial stored maps.
StorageMetadataHandle deletes operator-> on temporaries, so store the
handle before reading columns.
Validate rewritten policy identifiers against the tags table before
injection so names such as samples raise UNKNOWN_IDENTIFIER instead of
becoming correlated outer references. Update the samples-count expectation
for the version-11 one-row-per-series layout.
Keep the Prometheus HTTP error text aligned with the analyzer wording the
row-policy integration test expects.

if (const auto * identifier = node->as<ASTIdentifier>())
{
if (!identifier->compound() && !tags_columns.has(identifier->shortName()))

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.

⚠️ Major: validate column references within their scope.

A valid tags-only policy such as USING arrayExists(x -> x = 'a', [tags['tenant']]) works for SELECT from the TimeSeries table, but every PromQL read now throws UNKNOWN_IDENTIFIER for x. This traversal visits both the lambda parameter declaration and its uses and requires them to be tags-table columns. It likewise checks identifiers local to a policy's subquery against the wrong table.

Make the validation scope-aware, or validate resolved column references instead of every ASTIdentifier. The rewrite also needs to preserve lambda bindings when a parameter is named tags. Please add a stateless case comparing plain SELECT and prometheusQuery for a lambda policy, while retaining the existing rejection of a free samples reference.

@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master da9125b5e

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

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... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant