-
Notifications
You must be signed in to change notification settings - Fork 26.2k
Add PrometheusSeriesPlanBuilder for series endpoint #144493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
felixbarny
merged 10 commits into
elastic:main
from
felixbarny:prometheus-series-plan-builder
Mar 30, 2026
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1ae4ecb
Add esql and esql-core compile dependencies to prometheus plugin
felixbarny 528cfab
Add PrometheusSeriesPlanBuilder and extend TranslatePromqlToEsqlPlan
felixbarny 386ca50
Extract PrometheusPlanBuilderUtils from PrometheusSeriesPlanBuilder
felixbarny 2bc5e05
Remove section dividers from PrometheusSeriesPlanBuilderTests
felixbarny dd17572
Tighten assertion on aggregation-expression rejection message
felixbarny 969a1c7
Merge branch 'main' into prometheus-series-plan-builder
felixbarny dad7e9b
Resolve merge conflict with PrometheusPlanBuilderUtils.java from main
felixbarny 37b4a69
Fix limit=0 handling in Prometheus series API plan builder
felixbarny 5026fa8
Replace ASCII-art tree characters with \_ in PrometheusSeriesPlanBuil…
felixbarny e599701
Merge remote-tracking branch 'origin/main' into prometheus-series-pla…
felixbarny File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
155 changes: 155 additions & 0 deletions
155
...eus/src/main/java/org/elasticsearch/xpack/prometheus/rest/PrometheusPlanBuilderUtils.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.prometheus.rest; | ||
|
|
||
| import org.elasticsearch.xpack.esql.core.expression.Expression; | ||
| import org.elasticsearch.xpack.esql.core.expression.Literal; | ||
| import org.elasticsearch.xpack.esql.core.expression.UnresolvedAttribute; | ||
| import org.elasticsearch.xpack.esql.core.expression.UnresolvedTimestamp; | ||
| import org.elasticsearch.xpack.esql.core.tree.Source; | ||
| import org.elasticsearch.xpack.esql.expression.predicate.nulls.IsNotNull; | ||
| import org.elasticsearch.xpack.esql.expression.predicate.operator.comparison.GreaterThanOrEqual; | ||
| import org.elasticsearch.xpack.esql.expression.predicate.operator.comparison.LessThanOrEqual; | ||
| import org.elasticsearch.xpack.esql.optimizer.rules.logical.promql.TranslatePromqlToEsqlPlan; | ||
| import org.elasticsearch.xpack.esql.parser.ParsingException; | ||
| import org.elasticsearch.xpack.esql.parser.PromqlParser; | ||
| import org.elasticsearch.xpack.esql.plan.IndexPattern; | ||
| import org.elasticsearch.xpack.esql.plan.logical.LogicalPlan; | ||
| import org.elasticsearch.xpack.esql.plan.logical.SourceCommand; | ||
| import org.elasticsearch.xpack.esql.plan.logical.UnresolvedRelation; | ||
| import org.elasticsearch.xpack.esql.plan.logical.promql.selector.InstantSelector; | ||
| import org.elasticsearch.xpack.esql.plan.logical.promql.selector.LabelMatcher; | ||
|
|
||
| import java.time.Instant; | ||
| import java.time.ZoneOffset; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| import static org.elasticsearch.xpack.esql.expression.predicate.Predicates.combineAnd; | ||
| import static org.elasticsearch.xpack.esql.expression.predicate.Predicates.combineOr; | ||
|
|
||
| /** | ||
| * Shared plan-building utilities for Prometheus REST handlers. | ||
| */ | ||
| final class PrometheusPlanBuilderUtils { | ||
|
|
||
| /** Column produced by {@link org.elasticsearch.xpack.esql.plan.logical.TsInfo} that lists the dimension field names. */ | ||
| static final String DIMENSION_FIELDS = "dimension_fields"; | ||
|
|
||
| private PrometheusPlanBuilderUtils() {} | ||
|
|
||
| /** | ||
| * Returns an {@link UnresolvedRelation} for the given index pattern using the {@code TS} source command. | ||
| */ | ||
| static UnresolvedRelation tsSource(String index) { | ||
| IndexPattern pattern = new IndexPattern(Source.EMPTY, index); | ||
| return new UnresolvedRelation(Source.EMPTY, pattern, false, List.of(), null, SourceCommand.TS); | ||
| } | ||
|
|
||
| /** | ||
| * Builds a filter expression combining a time-range condition with optional selector conditions. | ||
| * | ||
| * @param matchSelectors PromQL instant vector selectors (may be empty) | ||
| * @param start start of the time range (inclusive) | ||
| * @param end end of the time range (inclusive) | ||
| * @return a single {@link Expression} suitable for use in a {@link org.elasticsearch.xpack.esql.plan.logical.Filter} node | ||
| */ | ||
| static Expression filterExpression(List<String> matchSelectors, Instant start, Instant end) { | ||
| List<Expression> allParts = new ArrayList<>(); | ||
| allParts.add(buildTimeCondition(start, end)); | ||
| List<Expression> selectorConditions = parseSelectorConditions(matchSelectors); | ||
| if (selectorConditions.isEmpty() == false) { | ||
| allParts.add(combineOr(selectorConditions)); | ||
| } | ||
| return allParts.size() == 1 ? allParts.get(0) : combineAnd(allParts); | ||
| } | ||
|
|
||
| /** | ||
| * Parses each {@code match[]} selector string into an ESQL {@link Expression} condition, | ||
| * delegating per-selector translation to {@link #buildSelectorCondition(InstantSelector)}. | ||
| * | ||
| * @param matchSelectors PromQL selector strings (may be empty) | ||
| * @return list of per-selector conditions; empty if {@code matchSelectors} is empty | ||
| * @throws IllegalArgumentException if a selector is syntactically invalid or not an instant vector selector | ||
| */ | ||
| static List<Expression> parseSelectorConditions(List<String> matchSelectors) { | ||
| List<Expression> selectorConditions = new ArrayList<>(); | ||
| PromqlParser parser = new PromqlParser(); | ||
| for (String selector : matchSelectors) { | ||
| LogicalPlan parsed; | ||
| try { | ||
| parsed = parser.createStatement(selector); | ||
| } catch (ParsingException e) { | ||
| throw new IllegalArgumentException("Invalid match[] selector [" + selector + "]: " + e.getMessage(), e); | ||
| } | ||
| if (parsed instanceof InstantSelector instantSelector) { | ||
| Expression cond = buildSelectorCondition(instantSelector); | ||
| if (cond != null) { | ||
| selectorConditions.add(cond); | ||
| } | ||
| } else { | ||
| throw new IllegalArgumentException("match[] selector must be an instant vector selector, got: [" + selector + "]"); | ||
| } | ||
| } | ||
| return selectorConditions; | ||
| } | ||
|
|
||
| /** | ||
| * Converts an InstantSelector's LabelMatchers into a single AND expression. | ||
| * Returns {@code null} if all matchers match everything (e.g. bare metric name with no labels). | ||
| * | ||
| * <p>Special handling for {@code __name__}: | ||
| * <ul> | ||
| * <li>EQ (e.g. {@code {__name__="up"}}): emits {@code IsNotNull(series)} — checks the metric | ||
| * field itself exists, which works for both Prometheus (labels.__name__ present) and OTel | ||
| * (field named "up" exists). The parser always provides a non-null {@code series()} for EQ.</li> | ||
| * <li>NEQ / REG / NREG whose automaton does not match all strings: falls back to filtering on | ||
| * {@code __name__}. OTel metrics that lack this label will be excluded — unavoidable, | ||
| * as we have no way to enumerate all field names by regex or negation.</li> | ||
| * <li>NEQ / REG / NREG whose automaton matches all strings (e.g. {@code =~".*"}): no constraint | ||
| * is emitted, matching all series including OTel.</li> | ||
| * </ul> | ||
| */ | ||
| static Expression buildSelectorCondition(InstantSelector selector) { | ||
| List<Expression> conditions = new ArrayList<>(); | ||
| for (LabelMatcher matcher : selector.labelMatchers().matchers()) { | ||
| if (LabelMatcher.NAME.equals(matcher.name())) { | ||
| if (matcher.matcher() == LabelMatcher.Matcher.EQ) { | ||
| // Parser contract: EQ __name__ always carries a non-null series expression | ||
| assert selector.series() != null : "EQ __name__ matcher should always have a non-null series"; | ||
| conditions.add(new IsNotNull(Source.EMPTY, selector.series())); | ||
| } else if (matcher.matchesAll() == false) { | ||
| // NEQ / REG / NREG: use __name__ for filtering. | ||
| // OTel metrics that lack this label will be excluded — unavoidable, as we have no | ||
| // way to enumerate all field names by regex or negation. | ||
| Expression nameField = new UnresolvedAttribute(Source.EMPTY, "__name__"); | ||
| Expression matcherCond = TranslatePromqlToEsqlPlan.translateLabelMatcher(Source.EMPTY, nameField, matcher); | ||
| conditions.add(combineAnd(List.of(new IsNotNull(Source.EMPTY, nameField), matcherCond))); | ||
| } | ||
| // matchesAll() == true: universal automaton — no constraint on metric name | ||
| } else { | ||
| Expression field = new UnresolvedAttribute(Source.EMPTY, matcher.name()); | ||
| Expression cond = TranslatePromqlToEsqlPlan.translateLabelMatcher(Source.EMPTY, field, matcher); | ||
| if (cond != null) { | ||
| conditions.add(cond); | ||
| } | ||
| } | ||
| } | ||
| return conditions.isEmpty() ? null : combineAnd(conditions); | ||
| } | ||
|
|
||
| /** | ||
| * Builds {@code @timestamp >= start AND @timestamp <= end}. | ||
| */ | ||
| static Expression buildTimeCondition(Instant start, Instant end) { | ||
| Expression ts = new UnresolvedTimestamp(Source.EMPTY); | ||
| Expression ge = new GreaterThanOrEqual(Source.EMPTY, ts, Literal.dateTime(Source.EMPTY, start), ZoneOffset.UTC); | ||
| Expression le = new LessThanOrEqual(Source.EMPTY, ts, Literal.dateTime(Source.EMPTY, end), ZoneOffset.UTC); | ||
| return combineAnd(List.of(ge, le)); | ||
| } | ||
| } |
55 changes: 55 additions & 0 deletions
55
...us/src/main/java/org/elasticsearch/xpack/prometheus/rest/PrometheusSeriesPlanBuilder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.prometheus.rest; | ||
|
|
||
| import org.elasticsearch.xpack.esql.core.expression.Literal; | ||
| import org.elasticsearch.xpack.esql.core.tree.Source; | ||
| import org.elasticsearch.xpack.esql.plan.logical.Filter; | ||
| import org.elasticsearch.xpack.esql.plan.logical.Limit; | ||
| import org.elasticsearch.xpack.esql.plan.logical.LogicalPlan; | ||
| import org.elasticsearch.xpack.esql.plan.logical.TsInfo; | ||
|
|
||
| import java.time.Instant; | ||
| import java.util.List; | ||
|
|
||
| /** | ||
| * Builds the {@link LogicalPlan} for a Prometheus {@code /api/v1/series} request. | ||
| * | ||
| * <p>The resulting plan has the shape: | ||
| * <pre> | ||
| * [Limit(n)] | ||
| * └── TsInfo | ||
| * └── Filter(timeCond AND OR(selectorConds...)) | ||
| * └── UnresolvedRelation(index, TS) | ||
| * </pre> | ||
| */ | ||
| final class PrometheusSeriesPlanBuilder { | ||
|
|
||
| private PrometheusSeriesPlanBuilder() {} | ||
|
|
||
| /** | ||
| * Builds the logical plan for a series request. | ||
| * | ||
| * @param index index pattern, e.g. {@code "*"} or a concrete name | ||
| * @param matchSelectors list of {@code match[]} selector strings (at least one required) | ||
| * @param start start of the time range (inclusive) | ||
| * @param end end of the time range (inclusive) | ||
| * @param limit maximum number of series to return (must be positive) | ||
| * @return the logical plan | ||
| * @throws IllegalArgumentException if a selector is not a valid instant vector selector | ||
| */ | ||
| static LogicalPlan buildPlan(String index, List<String> matchSelectors, Instant start, Instant end, int limit) { | ||
| LogicalPlan plan = PrometheusPlanBuilderUtils.tsSource(index); | ||
| plan = new Filter(Source.EMPTY, plan, PrometheusPlanBuilderUtils.filterExpression(matchSelectors, start, end)); | ||
| plan = new TsInfo(Source.EMPTY, plan); | ||
| if (limit > 0) { | ||
|
felixbarny marked this conversation as resolved.
Outdated
|
||
| plan = new Limit(Source.EMPTY, Literal.integer(Source.EMPTY, limit), plan); | ||
| } | ||
| return plan; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.