Repository navigation
Implement PromQL functions sort_by_label() and sort_by_label_desc() - #113173
valerypetrov wants to merge 60 commits into
Conversation
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>
|
Workflow [PR], commit [6e7f655] AI ReviewSummaryReviewed #113173 at PR head Final VerdictStatus: ✅ Approve |
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
|
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. |
There was a problem hiding this comment.
I think this PR's approach is better than the approach of #112826
…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.
…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.
2f093dc to
575eca6
Compare
… namespace unwind
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)); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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) | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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]>
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]>
…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]>
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]>
|
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. |
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]>
PromQL Compliance ReportBaseline: S3 master
Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream Note: Prometheus compliance score is unchanged vs baseline. |
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]>
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]>
…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]>
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]>
Changelog category (leave one):
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()andsort_by_label_desc()in the experimental PromQL dialect forTimeSeriestables.Documentation entry for user-facing changes:
sort_by_label(v instant-vector, label string, ...)andsort_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:
applySortFunctionorders 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 mapsort_group→sort_rankfixing 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 forgroup_right) andor(left rows, then right rows), discarded by aggregations, andfinalizeSQLjoins it and emitsORDER BY sort_rank.Testing:
gtest_PromQLParser.cpp.04556_promql_sort_by_labelcovering single-label natural ordering, descending order, multi-label ordering with the missing-label/tiebreak behaviour, and the argument-count / argument-type errors.abs(sort(...)),-sort(...),label_replace(sort_desc(...), ...),abs(sort_by_label(...))) checking that outer functions keep the order produced by an inner sort* call.tests/integration/test_prometheus_protocols/test_evaluation.pycomparing against real Prometheus, and re-enabled the tests that were disabled as nondeterministic withoutsort_by_label().Note
Per review, this PR supersedes #112826: it contains both the
sort()/sort_desc()commit and thesort_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]