hertzbeat: [Question] PromQL comparison operator implementation is inconsistent with the official Prometheus definition
Question
While recently reviewing the official Prometheus documentation, I noticed the behavior of PromQL comparison operators (>, <, ==, >=, <=, !=) and found two main inconsistencies when comparing it with the implementation in Hertzbeat.
-
Comparison Logic for Instant Vector vs. Scalar
According to the official Prometheus documentation, when an instant vector is compared to a scalar, the operation acts as a filter. Specifically, PromQL iterates through each time series in the vector, performs the comparison, and any time series for which the expression is true is kept in the output. Series for which the result is false are removed.
However, I noticed that the behavior demonstrated in the calculate1 test case in hertzbeat.warehouse.service.DataSourceServiceTest does not align with this standard.
void calculate1() { List<Map<String, Object>> prometheusData = List.of( new HashMap<>(Map.of("__value__", 100.0, "timestamp", 1343554, "instance", "node1")), new HashMap<>(Map.of("__value__", 200.0, "timestamp", 1343555, "instance", "node2")) ); QueryExecutor mockExecutor = Mockito.mock(QueryExecutor.class); Mockito.when(mockExecutor.support("promql")).thenReturn(true); Mockito.when(mockExecutor.execute(Mockito.anyString())).thenReturn(prometheusData); dataSourceService.setExecutors(List.of(mockExecutor)); List<Map<String, Object>> result = dataSourceService.calculate("promql", "node_cpu_seconds_total > 150"); assertEquals(2, result.size()); assertNull(result.get(0).get("__value__")); assertEquals(200.0, result.get(1).get("__value__")); }Analysis:
Input: An instant vector containing two time series with values 100.0 and 200.0. Query: node_cpu_seconds_total > 150. Expected PromQL Behavior: Only the series with the value 200.0 satisfies the condition. Therefore, the result should be a new vector containing only that single series, and its size should be 1. Behavior in Hertzbeat Test: The test asserts that result.size() is 2. Instead of filtering out the non-matching series (value of 100.0), it keeps the series in the result set but sets its value to null. Core Question: This “keep and nullify” behavior deviates from PromQL’s standard filtering model. Is this an intentional design choice in Hertzbeat? My main question is whether the plan is to fully align with the Prometheus specification in this regard. If not, it could cause confusion for users familiar with standard PromQL.
-
Support for Comparison Operations on Range Vectors
The Prometheus documentation clearly states that logical and comparison operators are only defined to work between instant vectors. They do not support range vectors.
However, I noticed that DataSourceServiceTest contains test cases involving comparisons between a range vector and a scalar, such as: node_cpu_seconds_total{mode="user"}[4m] <= 100
This is an invalid expression in standard PromQL. This seems to suggest that Hertzbeat is extending PromQL syntax to support comparisons on range vectors.
About this issue
- Original URL
- State: open
- Created a year ago
- Reactions: 2
- Comments: 16 (16 by maintainers)
Real business scenarios are only more complicated than that. 😃
I can provide some contextualization
An example of a real business environment:
Because of the business architecture, there are currently 10+ prometheus nodes like this one, and the rules on each node are also different
A simple metric
As you can see above, if you don’t utilize the
promqlrelated features wisely, you are likely to get into unnecessary trouble.However, despite the many issues that have not been dealt with, it is because of us interesting people that hertzbeat will also explore more endless possibilities in the years to come. 💪
@Cyanty Yes, you’re right, it is indeed a long and complicated process 😃
But thank you very much for your answer, you can follow the movement of the community, so that when we have a follow-up related to the implementation of the same, and also participate in our construction 💪
Everyone,
Thank you for the in-depth discussion. By combining everyone’s viewpoints with my own thoughts, I’d like to propose a more complete solution to help us align our thinking.
My core idea is this: we should not confine ourselves to the goal of “100% PromQL compatibility.” Instead, we should clearly define what we are building: a domain-specific language (DSL) tailored for Hertzbeat’s alerting scenarios. As @MasamiYui pointed out, an alert expression can be clearly broken down into a
Metric Query+Alert Condition. TheMetric Querypart can (and should) use standard PromQL or SQL. For theAlert Conditionpart, however, we can define our own, better-optimized semantics to cater to specific alerting features, such as alert recovery.1. Regarding Comparison Operators
Core Supported Operations:
Instant Vector vs. Scalar: This must be supported as it’s the most common type of threshold alert. This part is already supported.Instant Vector vs. Instant Vector: This should be supported. It’s crucial for scenarios involving dynamic thresholds or comparing two related metrics. This part is not yet supported.Operations That Must Be Prohibited:
Range Vector: This is the most ambiguous and dangerous part of the current implementation. An expression likemetric[5m] > 100has unclear semantics. I strongly recommend following PromQL’s best practice: enforce that users must use aggregation functions (e.g.,avg_over_time,rate,max_over_time) to convert arange vectorinto aninstant vectorbefore any comparison or logical operations can be performed. This will completely eliminate semantic ambiguity and ensure that the alerting behavior is entirely predictable and aligned with user expectations. We need to modify this part to prohibit it.Regarding Retaining and Setting to Null for Alert Recovery:
nullfor alert recovery is a smart and necessary design that serves a core function.value != nullas “Triggered” and those wherevalue == nullas “Normal/Recovered.” The user experience can be made very clear.2. Regarding Logical Operators
Logical operators should be used to connect the results of two or more “alert conditions.” However, we need to carefully consider how to handle null values. We can understand it this way: a non-null value on either the left or right side represents
true, whilenullrepresentsfalse. There’s also the case where the left side has a value, but the corresponding instant vector cannot be found on the right side; we’ll treat the missing one asfalse. The final result merges all instant vectors from both sides. For example:Expression:
(a > 1) and (b > 2)Let’s assume we have the following raw data:
a{instance="A", os="linux"}: 5{instance="B", os="linux"}: 0 (does not satisfy a > 1){instance="C", os="windows"}: 10b{instance="A", os="linux"}: 3{instance="B", os="linux"}: 5{instance="D", os="windows"}: 20 (this is a new instance)Step 1: Calculate the left expression
(a > 1)Based on our previously defined “retain and set to null” logic, the result of this expression is a new instant vector, which we’ll call
Result_A:{instance="A", os="linux"}:5 > 1is true, so the value is retained.__value__: 5{instance="B", os="linux"}:0 > 1is false, so the value is set to null.__value__: null{instance="C", os="windows"}:10 > 1is true, so the value is retained.__value__: 10Step 2: Calculate the right expression
(b > 2)Similarly, we calculate
(b > 2)and get the result vectorResult_B:{instance="A", os="linux"}:3 > 2is true, so the value is retained.__value__: 3{instance="B", os="linux"}:5 > 2is true, so the value is retained.__value__: 5{instance="D", os="windows"}:20 > 2is true, so the value is retained.__value__: 20Step 3: Execute
Result_A AND Result_BNow we come to the most critical step. The
ANDoperator will iterate over all instances that have appeared in eitherResult_AorResult_B(i.e.,A,B,C,D) and then determine the final result based on the following logic:For
instance="A":Result_A, its value is5(non-null, representing True).Result_B, its value is3(non-null, representing True).True AND Trueis True. The final result is non-null. Retain__value__(typically, the value from the left side is kept, which is5).For
instance="B":Result_A, its value isnull(representing False).Result_B, its value is5(non-null, representing True).False AND Trueis False. The final result is__value__: null.For
instance="C":Result_A, its value is10(non-null, representing True).Result_B, it does not exist. A non-existent series in a logical comparison should be treated as False.True AND Falseis False. The final result is__value__: null.For
instance="D":Result_A, it does not exist (representing False).Result_B, its value is20(non-null, representing True).False AND Trueis False. The final result is__value__: null.Final Result
After executing
(a > 1) and (b > 2), the final vector we get is:{instance="A", os="linux"}:__value__: 5<-- The only series that triggers an alert{instance="B", os="linux"}:__value__: null{instance="C", os="windows"}:__value__: null{instance="D", os="windows"}:__value__: nullThis result perfectly aligns with the logical expectation: an alert is triggered only when an instance satisfies both conditions simultaneously.
Understood. Considering that HertzBeat has already integrated various time-series databases, which may have different SQL-like syntaxes, I can imagine the complexity and the chaotic readability of parsing with a single parse tree. As support for more data source syntaxes is added, splitting the logic is indeed necessary. Of course, the work of adapting to multiple parse trees is time and energy consuming, this will likely be a long process. In the future, HertzBeat can achieve a smooth transition in this regard to ensure compatibility for upgrades from older versions. Thank you for your answer.
Okay, that’s fine, go ahead and submit the PR then, if you change that part then I’ll most likely have to add changes to your revisions.
It seems that full PromQL support is necessary, then? If so, the approach of setting the value to
nullwill need to be changed. Perhaps we can take the result of each periodic threshold expression evaluation and compare it against the metrics that are currently in an alerting state. If a metric for an active alert does not appear in the expression evaluation result, we can conclude that it has recovered. This would eliminate the need to usenullfor this determination.@Duansg Additionally, regarding the minor bug mentioned yesterday, I simply modified the PromQL grammar in the .g4 file: I deleted the line
promql binaryOperator promqland then regenerated the corresponding lexer and parser code. If you have already modified this part of the code, we can just use your version. I’ll wait for your next PR.hi, understand you very well.
1, I think it should be judging whether the result is null or not, not judging the value, which breaks the semantics of promql, don’t you think? Between instantaneous vectors and scalars, these operators are applied to the value of each data sample in the vector, and vector elements with a comparison result of
falseare deleted from the result vector, the current logic is to retain the Null value, which is extremely unfriendly to subsequent additions to the preview function.2, the actual threshold judgment of the scene there are many,
range-vectorjust in the implementation of Some functions necessary conditions, rather than only support for queryingrange-vector, but currently can be extended through the promql(xxx), this I think is not the primary focus.3, I don’t think it’s about providing a calibration function, but rather providing a preview, which is often useful when writing complex expressions to determine the correctness and accuracy of the threshold, don’t you think?
To summarize, I think the primary focus is as @bigcyy mentioned, fixing the semantic issues with comparison and providing preview functionality is sufficient, and subsequent issues can be expanded with real usage scenarios in additional.
Hi, sorry just had time to see your reply, first of all thank you for your reply, I have the following thoughts in response to the points you raised:
Or sink down to
QueryExecutor, so that parsing and querying can be executed as a single process. The currentSqlandPromqlparsing rules together affect the ease of maintenance and secondary development, and you often need to worry about whether you are breaking another parsing rule.2.in the scenario of the example, in addition to the operation and maintenance aspects of the scenario, there are even business development to configure a thousand and one expressions, but this does not violate the rules of the promql expression, for example:
vectors and scalars, likescalars and vectors,scalar and scalarwe don’t support it very well. scalar and scalar` we don’t support very well, also compareOp is not handled very well, it’s not compatible with the semantics of Promql at the moment.Even though I’ve fixed that part of the logic, I’ve decided to let this PR go to see if the PR you submitted will open my mind to new ideas. 💪