Skip to content

Support PromQL absent functions - #104493

Closed
BadLiveware wants to merge 48 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-absent-functions
Closed

BadLiveware wants to merge 48 commits into
ClickHouse:masterfrom
BadLiveware:split/promql-absent-functions

Conversation

@BadLiveware

@BadLiveware BadLiveware commented May 9, 2026 •

Copy link
Copy Markdown

Adds native lowering for PromQL absence functions over ClickHouse TimeSeries data.

The implementation supports absent and absent_over_time, including synthetic output label construction from unambiguous equality matchers and per-step presence probing for range inputs.

Split out from the integration draft #104271; shared base #104484.

Changelog category (leave one):

  • Experimental Feature

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

Added native PromQL-to-SQL lowering for absent and absent_over_time over ClickHouse TimeSeries data.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

BadLiveware added 13 commits May 9, 2026 13:52
Add the common PromQL compliance reporting and developer notes used by the follow-up TimeSeries PromQL lowering slices. Keep the parser compliance corpus expectation explicit for selectors Prometheus rejects.
Add focused Prometheus protocol tests for user-facing native lowering errors: unsupported-but-parseable functions and invalid date-function arity. These are semantic guardrails for clear errors, not broad coverage padding.
Implement native TimeSeries lowering for PromQL absent and absent_over_time using the existing SQLQueryPiece and AST builder pipeline. The lowering produces the synthetic single-series result only when inputs are absent, derives output labels from equality matchers, and keeps regex/negative matchers out of the synthetic labels.

Add differential and compliance coverage for present and missing inputs, equality-derived labels, regex and negative matcher behavior, range-query output, and aggregation over absent.

Validation: git diff --check; Python py_compile for updated PromQL tests; Dockerized Build (amd_debug) passed; test_prometheus_protocols/test_evaluation.py passed; test_promql_compliance passed.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Avoid fork-local wording in the PromQL review base. These are ClickHouse PromQL regression cases and evidence requirements, not fork-specific artifacts.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove the standalone native histogram discovery Markdown note from the PromQL split branches.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Remove downstream promshim-specific evidence and non-goal language from the native PromQL lowering README so the note stays focused on ClickHouse review guidance.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Rewrite the native PromQL lowering notes around external SQL-transpiler measurements. Document measured and mixed SQL patterns with target PromQL shapes, pseudocode, and the ClickHouse-side validation expected for in-tree changes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
Replace external corpus row names with concrete PromQL expressions and query-range context in the native PromQL lowering notes.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f1ffc31]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
02915_move_partition_inactive_replica FAIL cidb
01164_alter_memory_database FAIL cidb
03916_system_table FAIL cidb
01231_distributed_aggregation_memory_efficient_mix_levels FAIL cidb
01152_cross_replication FAIL cidb
02346_additional_filters_distr FAIL cidb
02916_another_move_partition_inactive_replica FAIL cidb
03702_not_existing_role_on_cluster FAIL cidb
01615_random_one_shard_insertion FAIL cidb
Some queries hung FAIL cidb
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED
Build (arm_msan) DROPPED

AI Review

Summary

This PR adds native PromQL lowering for absent and absent_over_time, plus parser validation/tests around PromQL selector semantics. The main shape is reasonable, but two correctness gaps remain in the new absence lowering: stale markers are counted as presence for absent, and absent_over_time(... @ ts) is evaluated on the outer range grid instead of the fixed argument time in range queries.

Findings

❌ Blockers

  • [src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionAbsent.cpp:135] absent must decide presence after instant-selector stale-marker filtering, but countForEach(values) counts the Prometheus stale NaN as a non-null value. A selector whose latest sample is the stale marker is empty in PromQL, so absent(selector) should emit 1; this branch suppresses it before finalizeInstantVectorAsSQL can apply the stale-marker predicate. Map stale-marker values to NULL with the same check used by finalization before counting.
  • [src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunctionAbsent.cpp:336] absent_over_time must preserve @ fixed-time semantics for raw range-selector arguments. In a range query such as absent_over_time(test[45s] @ 210), the selector is read from the fixed window ending at 210, but this code probes those raw samples using the outer steps' windows, so it can emit absence even when the fixed argument range is non-empty. Mirror applyFunctionOverRange: aggregate the raw Offset argument using the wrapped expression's fixed range, then repeat the resulting presence vector across the outer grid.
Tests
  • ⚠️ Add a regression where a stale marker is the latest instant-selector sample: absent should treat it as absent, while an ordinary NaN sample should still count as present.
  • ⚠️ Add a range-query regression for absent_over_time(metric[window] @ fixed_ts) where the fixed window has samples but the outer query timestamps do not overlap that window.
Final Verdict

Status: ❌ Block

Minimum required actions: fix the stale-marker presence check, fix fixed-time @ handling for absent_over_time range queries, and add the focused regressions above.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label May 10, 2026
Match Prometheus parser behavior by requiring vector selectors to contain at
least one matcher that cannot match an empty label value. This prevents broad
selectors like `{job=~".*"}` or `{__name__=~".*"}` from silently selecting every
metric when the user likely intended an explicit non-empty constraint.

Users who intentionally want all real metrics can still use `{__name__=~".+"}`,
and empty-matching label matchers remain valid when combined with that explicit
metric-name matcher.
Deduplicate expanded compliance cases by query text before checking the
`should_fail` expectation. A query listed once as expected success and once as
expected failure is now reported as conflicting metadata instead of slipping
through as two separate cases.
Only propagate labels from absent functions when a label has exactly one matcher
and that matcher is an equality matcher. This avoids synthesizing output labels
from selector forms where another matcher for the same label should make the
label ambiguous, regardless of matcher order.
Mirror the upstream PromQL compliance corpus for label transformation invalid
label-name cases. These cases should remain should-fail entries so ClickHouse
acceptance of invalid destination labels stays visible as a rejection mismatch
rather than being counted as expected coverage.
The focused regression covers ClickHouse's deterministic label synthesis for
ambiguous duplicate matchers. The Prometheus reference keeps compatibility
behavior for this exact mixed matcher shape, so do not require both reference
servers to match the ClickHouse-only invariant.
Do not stop selector validation after finding the first matcher that cannot match an empty label value. Later regex matchers still need syntax validation so equivalent selector reorderings cannot change parse validity.

Add parser regressions for invalid regex matchers after an implicit metric-name matcher and after explicit non-empty matchers.
Prometheus builds output labels for `absent` and `absent_over_time` by walking direct selector matchers in order. A first exact equality matcher contributes a label, while later duplicate or mixed matchers delete it; `__name__` is always skipped.

Mirror that historical rule instead of treating any duplicate matcher as globally ambiguous, and add focused coverage for empty vectors, selector/non-selector arguments, sparse range output, and regular `NaN` samples counting as present.

Validation:

- `python -m ci.praktika run "integration" --test tests/integration/test_prometheus_protocols/test_evaluation.py::test_absent_functions > build_debug/test_prometheus_absent_functions_rerun4.log 2>&1`

- `python -m ci.praktika run "integration" --test tests/integration/test_prometheus_protocols/test_compliance.py::test_promql_compliance > build_debug/test_promql_compliance_absent.log 2>&1`
Ignore string literals and selector matchers when routing compliance failures by query shape. This keeps report categories from treating label values or exponent signs as binary operators, and recognizes bare '<' and '>' comparisons.
Unwrap PromQL offset and @ modifier nodes before collecting selector matchers for absent functions. Prometheus still derives synthetic labels from the underlying selector when timing modifiers are present.
Use the existing eps parameter when checking live Prometheus HTTP results against expected JSON, and compare ClickHouse HTTP output against the live Prometheus result. This keeps numeric drift bounded to eps while preserving exact shape, label, and timestamp checks.
Matcher validation intentionally turns malformed label regexes into PromQL parse errors. Construct RE2 with log_errors disabled so rejected selectors do not also emit internal RE2 error log lines on every parse attempt.
@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 84.19% (261/310) · Uncovered code

Full report · Diff report

Keep the PromQL parser, modifier, and selector fixes from the local matrix pass, but move the high-value regression coverage into the existing protocol and compliance suites instead of adding the standalone matrix harness to the PR branch.\n\nThis keeps fixed-time range evaluation covered through the existing evaluation tests and records the parser, matcher, timestamp-modifier, and sparse range cases in the shared compliance corpus.
Build (arm_tidy) flagged the vector-grid finalization predicate because one call cloned an AST pointer while another argument moved the same pointer. C++ argument evaluation order can make that a use-after-move.\n\nCreate separate AST nodes for the null and stale-marker checks so the generated predicate stays the same without relying on argument evaluation order.
Parse `@ start()` and `@ end()` as timestamp modifier variants instead of
rewriting the raw query text before parsing. This keeps label values and
regular expressions untouched while resolving symbolic bounds in the query
range planner.

Propagate symbolic `@` modifiers through the PromQL tree and SQL lowering so
instant selectors and range-vector functions bind to the query start or end
consistently with Prometheus.
The selector-matcher validation branch should not also introduce symbolic
`@ start()` and `@ end()` modifier parsing. Remove that parser/evaluation
feature from the base branch so the behavior can be reviewed independently.

Move the symbolic timestamp-modifier compliance cases out with the feature.
Keep the offset-only case here because it exercises existing modifier behavior.
Symbolic `@ start()` and `@ end()` modifiers need parser-level handling so
selectors, string literals, and regular expressions are not rewritten as raw
text. Remove the temporary text-substitution path from the base branch; the
symbolic modifier implementation belongs with the dedicated parser change.
…tions

# Conflicts:
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunction.cpp

ASTPtr makeAbsentValuesFromCountsAST(const NodeEvaluationRange & node_range, ConverterContext & context)
{
auto counts = makeASTFunction("countForEach", make_intrusive<ASTIdentifier>(ColumnNames::Values));

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.

absent needs to test presence after instant-selector staleness filtering, but this counts stale markers as present.

Concrete trace: for absent(up) at an evaluation time where the latest up sample is the Prometheus stale NaN, fromSelector intentionally reads the stale marker (filter_stale_markers = false) and timeSeriesLastToGrid returns it as a non-null grid value. countForEach(values) then produces a non-zero count, so this branch maps the step to NULL and the absent sample is suppressed. A plain selector only gets the correct empty-vector behavior later in finalizeInstantVectorAsSQL, but absent bypasses that final stale-marker predicate when it does its own presence probe.

Please map values with the same stale-marker check used by finalizeInstantVectorAsSQL to NULL before calling countForEach, and add a regression with a stale sample so regular NaN still counts as present while the stale marker does not.

case StoreMethod::RAW_DATA:
{
chassert(isAbsentOverTime(function_name));
argument = buildPresenceGridForRangeArgument(std::move(argument), node_range, context);

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.

absent_over_time needs to preserve the fixed argument evaluation time from @ before probing presence, but this uses the outer query grid for raw range-selector arguments.

For prometheusQueryRange(..., 'absent_over_time(test[45s] @ 210)', 110, 130, 10), NodeEvaluationRangeGetter plans the range selector itself at the fixed window ending at 210, and fromSelector reads samples from that fixed window. Here we then aggregate those raw samples with the outer node_range ending at 110, 120, and 130, so none of the fixed-window samples can count as present and the function emits 1s even when test[45s] @ 210 is non-empty. Prometheus evaluates the argument at 210 and repeats that same empty/non-empty result for every outer step.

Please mirror the fixed-argument handling in applyFunctionOverRange: aggregate a raw Offset argument with the wrapped expression's fixed range first, then resize/repeat the resulting presence value across the outer absent_over_time grid.

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 3, 2026
@nikitamikhaylov

Copy link
Copy Markdown
Member

'absent' added here: #112795

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.

4 participants