Skip to content

Implement PromQL functions sort_by_label() and sort_by_label_desc() - #113173

Open
valerypetrov wants to merge 60 commits into
ClickHouse:masterfrom
valerypetrov:promql/sort-by-label
Open

valerypetrov wants to merge 60 commits into
ClickHouse:masterfrom
valerypetrov:promql/sort-by-label

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Experimental Feature

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

Support the PromQL functions sort(), sort_desc(), sort_by_label() and sort_by_label_desc() in the experimental PromQL dialect for TimeSeries tables.

Documentation entry for user-facing changes:

sort_by_label(v instant-vector, label string, ...) and sort_by_label_desc(v instant-vector, label string, ...) sort the elements of an instant vector by the natural sort order of the given label values, in ascending and descending order respectively. Several label names may be provided; earlier labels take precedence and later ones break ties. A missing label is treated as an empty string (matching Prometheus).

Description

This adds the PromQL sorting-by-label functions to the experimental PromQL-to-SQL converter:

  • sort_by_label(v, label, ...) — sort ascending by the given label values.
  • sort_by_label_desc(v, label, ...) — sort descending by the given label values.

Unlike sort() / sort_desc() (which order by sample value), these order by the natural sort order of the requested label values, so numeric segments compare numerically (e.g. host1, host2, host10, host20). Multiple labels are supported: earlier labels take precedence, later labels break ties, and the full label set is appended as a deterministic final tiebreaker. A missing label is treated as an empty string.

Implementation notes:

  • Lowering: applySortFunction orders the vector at the call site (in PromQL these are ordinary vector functions, so outer transforms must keep the order they produce): it materializes the argument grid and builds a rank map sort_group → sort_rank fixing each series' position. The map is carried through series-preserving transforms, joined through the source series of each row by group-changing ones (metric-name dropping, label_replace()/label_join()), joined through vector/vector binary operators (left order, right order for group_right) and or (left rows, then right rows), discarded by aggregations, and finalizeSQL joins it and emits ORDER BY sort_rank.
  • Errors: the vector argument is required, and every label argument must be a string.

Testing:

  • Parser unit tests in gtest_PromQLParser.cpp.
  • Stateless test 04556_promql_sort_by_label covering single-label natural ordering, descending order, multi-label ordering with the missing-label/tiebreak behaviour, and the argument-count / argument-type errors.
  • Nested regressions in the stateless tests (abs(sort(...)), -sort(...), label_replace(sort_desc(...), ...), abs(sort_by_label(...))) checking that outer functions keep the order produced by an inner sort* call.
  • sort*/sort_by_label* checks in tests/integration/test_prometheus_protocols/test_evaluation.py comparing against real Prometheus, and re-enabled the tests that were disabled as nondeterministic without sort_by_label().

Note

Per review, this PR supersedes #112826: it contains both the sort() / sort_desc() commit and the sort_by_label() / sort_by_label_desc() work, and is intended to be merged instead of that PR.


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

valerypetrov and others added 2 commits July 31, 2026 15:18
Adds two PromQL functions that sort instant vector output by sample value:
- `sort(v)` — ascending
- `sort_desc(v)` — descending

Implementation uses a pass-through converter that sets a sort_direction flag
on the SQLQueryPiece, which finalizeInstantVectorAsSQL reads to append
ORDER BY value ASC/DESC to the final SQL. Matches Prometheus semantics
where sort only affects instant query output ordering.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
These functions sort the elements of an instant vector by the natural sort
order of the given label values (ascending for `sort_by_label`, descending
for `sort_by_label_desc`), rather than by sample value like `sort()` /
`sort_desc()`. Multiple label names can be given; earlier labels take
precedence and later ones break ties. A missing label is treated as an empty
string, matching Prometheus. The full label set is appended as a deterministic
final tiebreaker.

The ordering is lowered to SQL using `naturalSortKey()` over the requested
label values, so numeric segments sort numerically (e.g. host1, host2, host10,
host20).

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e7f655]


AI Review

Summary

Reviewed #113173 at PR head 6e7f6555fe29d21bdf1493c18efb4ca7cfff95ee, including the current implementation and all prior discussion. The change adds sort, sort_desc, sort_by_label, and sort_by_label_desc to experimental PromQL, preserves ordering through vector transformations, and clears it when aggregation or range conversion invalidates it. Earlier findings are addressed; no new actionable findings remain. The Praktika reports report 15,427 passed tests, zero failures, and 4,587 skipped tests. Validation relied on those reports and source inspection; no local tests were run.

Final Verdict

Status: ✅ Approve

@valerypetrov valerypetrov reopened this Aug 3, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 3, 2026
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

I accidentally closed this PR. Will continue working on this one. Can you please remove the manual approve tag? I suppose it was added when I closed and opened this PR.

@nikitamikhaylov nikitamikhaylov added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Aug 3, 2026
@vitlibar vitlibar self-assigned this Aug 4, 2026
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR. labels Aug 4, 2026

@vitlibar vitlibar Aug 4, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this PR's approach is better than the approach of #112826

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vitlibar , I can mimic this PR's approach in #112826

valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Aug 4, 2026
…y_label()

sort() and sort_desc() are supposed to replace the ordering mode entirely,
but they only overwrote `sort_direction` and left any `sort_by_labels`
set by an earlier sort_by_label() / sort_by_label_desc() intact. As a
result, a query like sort_desc(sort_by_label(up, "instance")) still took
the label-sorting path in finalizeSQL and returned `instance` DESC order
instead of sample-value DESC order.

Clear `sort_by_labels` in applySortFunction() when the plain sort() /
sort_desc() variants override the ordering mode, and add a regression
test for nested sort_desc(sort_by_label()) to
tests/queries/0_stateless/04550_promql_sort_sort_desc.sh.

Addresses review comment from clickhouse-gh on PR ClickHouse#113173.
@CLAassistant

CLAassistant commented Aug 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

…y_label()

sort() and sort_desc() are supposed to replace the ordering mode entirely,
but they only overwrote `sort_direction` and left any `sort_by_labels`
set by an earlier sort_by_label() / sort_by_label_desc() intact. As a
result, a query like sort_desc(sort_by_label(up, "instance")) still took
the label-sorting path in finalizeSQL and returned `instance` DESC order
instead of sample-value DESC order.

Clear `sort_by_labels` in applySortFunction() when the plain sort() /
sort_desc() variants override the ordering mode, and add a regression
test for nested sort_desc(sort_by_label()) to
tests/queries/0_stateless/04550_promql_sort_sort_desc.sh.

Addresses review comment from clickhouse-gh on PR ClickHouse#113173.
@valerypetrov
valerypetrov force-pushed the promql/sort-by-label branch from 2f093dc to 575eca6 Compare August 4, 2026 18:28
valerypetrov and others added 4 commits August 4, 2026 16:35
The file was tracked as mode 100644, so CI's stateless test runner hit
"Permission denied" (return code 126) trying to execute it directly,
failing every stateless-test shard that runs it (and, since it's
new/changed in this PR's diff, every "flaky check" job too, which
specifically re-runs new/changed tests).
# Conflicts:
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLLexer.cpp
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLLexer.interp
…ort-by-label

# Conflicts:
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyFunction.cpp
if (result.sort_by_labels.empty())
{
/// sort() / sort_desc(): order by sample value.
builder.order_by.push_back(make_intrusive<ASTIdentifier>(ColumnNames::Value));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this PR already implements most of what's needed for sort/sort_desc functions as well. Let's finish and merge this PR and not #112826

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done - sort and sort_desc are implemented in this PR (04550_promql_sort_sort_desc covers them), and the ordering is applied at the sort* call site so it composes with outer functions. #112826 stays closed in favor of this PR.

@@ -0,0 +1,21 @@
-- sort(up): ascending by value (10, 20, 30)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Usually we check new promql functions in test_evaluation.py. Also there are already some tests with disabled checks containing sort functions, with this PR we can try enable them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_sort_functions to test_evaluation.py comparing against real Prometheus, including the nested cases (abs(sort(-http_errors)), label_replace(sort_desc(...), ...)), and several comparisons that needed deterministic ordering now go through sort_by_label.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. test_sort_functions() (test_evaluation.py:2531) runs sort, sort_desc, sort_by_label and sort_by_label_desc through do_query_test, which executes every query against real Prometheus and asserts ClickHouse matches (test_evaluation.py:469-491) — including nested composition, abs(sort(-http_errors)) at 2576 and label_replace(sort_desc(...)) at 2587. The FIXME-disabled tests are enabled: sort_by_label(rate(...)) at 2498, and the existing comparisons now route through sort_by_label for deterministic order at 2857, 2913, 3919, 4003, 4200 and 4300.

valerypetrov and others added 5 commits October 24, 2026 15:13
Prometheus's natural-order comparator calls each of two equal numbers
written with different leading zeros (host1, host01) the smaller one, so
the result of sort_by_label() depends on the order of its input. `or`
gives its left rows first, then its right ones, but without an inner
sort*() it had no rank map and the sort started from the tag order, so
sort_by_label(lz{instance="host1"} or lz{instance="host01"}, "instance")
returned host1, host01 where Prometheus 3.5.0 returns host01, host1 (and
the reverse for sort_by_label_desc()).

Now `or` keeps its left-then-right rank map when it is evaluated at one
step inside sort_by_label() or sort_by_label_desc(); other queries are
not changed. Both orders are checked against a Prometheus 3.5.0 server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
naturalLess is ported from github.com/facette/natsort and GoSort from
Go's slices package, both under the BSD-3-Clause license, which asks to
keep the copyright notice, the conditions and the disclaimer in the
source. Copy both upstream LICENSE files verbatim next to the existing
note, as src/Common/isValidUTF8.cpp does for its MIT-licensed code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check rejects lines indented by one to three spaces, and the BSD license block added to
`timeSeriesSortGroupsByTags.cpp` in the previous commit had five such continuation lines.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113173&sha=749f0b7f6917731932594eee702c7a59123d7041&name_0=PR&name_1=Style%20check
PR: ClickHouse#113173

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Go sort and facette/natsort code ported into timeSeriesSortGroupsByTags.cpp is BSD-3-Clause, which
asks binary distributions to carry the notices too. system.licenses is how ClickHouse ships the licenses of
the code it includes, so list-licenses.sh now also reads utils/list-licenses/ported/<project>/LICENSE,
which hold the upstream LICENSE files verbatim.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits October 31, 2026 17:43
…y_label

Without an inner sort*() call there was no rank map, so an outer sort_by_label()
rebuilt its input order from the tags changed by label_replace()/label_join(),
which differs from Prometheus where the vector keeps the selector's order.
Record the order by the original tags as the rank map before the labels change.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…MetricName and vector binary operators

Capture the storage-order rank before the metric name is dropped or labels are projected, and re-key it through the existing source-rank path, as done for label_replace().

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Dear @vitlibar, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@vitlibar vitlibar self-assigned this Nov 2, 2026
All label-sort fixtures had at most ten series, so only the insertion-sort
path of the Go pdqsort port was compared with Prometheus. The new series use
leading zeros and digit runs past Int64, which make Prometheus's comparator
non-transitive, so the expected order holds only if the partition and pivot
paths match Go's. The expected orders are the PR's output; CI's Prometheus
checks them.

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

clickhouse-gh Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master d55bffe3a

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 94.67% +1.50%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 693 (+11) 16 -> 16 (+0) 34 -> 23 (-11)

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 3 commits November 6, 2026 22:14
Prometheus gives in-memory series to sort_by_label in arrival order and stored blocks in label order.
Its comparator is not transitive for these hosts, so the result depends on that input order.
ClickHouse uses the label order, and CI's Prometheus got the series in index order, so the
20-series case failed. With the series sent in label order, local Prometheus 3.5.0 returns the
expected order for all four cases, both from memory and from a stored block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A side of `or` without its own rank map gave all its rows one rank, so they
tied by tags. After a later tag change (abs(), label_replace(), a binary
operator) the tie used the new tags, not the order the rows had before, so
sort_by_label(abs(s or s), "instance") differed from sort_by_label(abs(s),
"instance"). At one step each unranked side now gets its order by tags as a
rank map before the side prefix is added.

The same order was also lost before the `or`: in `sort(pc) or abs(s)` the
right rows came out by their tags after abs(), while Prometheus 3.5 keeps the
selector order. An operand of `or` whose other operand has a sort function now
records its order before tags change, like an operand of sort_by_label().

The new 04556 cases match a Prometheus 3.5.0 server on the same data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov and others added 2 commits November 21, 2026 21:37
…discard]]

clang-tidy's modernize-use-nodiscard check is now an error on master.
It flags GoSort::less and the const overrides of
FunctionTimeSeriesSortGroupsByTags, which this file adds without the
attribute. The attribute changes no behaviour.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
valerypetrov and others added 2 commits November 23, 2026 18:39
The sanitizer builds now report unsigned integer overflow and abort on it.
`offsets[row - 1]` and `rank_offsets[first + i - 1]` wrapped a `size_t` at
index 0 before reaching the padded element at -1; they now use a signed
index like the other array functions. The two heap sort loops of `GoSort`
decremented their counter below zero on exit; they now stop at zero and
use `i - 1` in the body, which visits the same indexes in the same order.

The function is new in 26.12, so `introduced_in` says so.

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

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-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants