Skip to content

fix(#9883): PromQL aggregations and math functions refuse an argument of the wrong type - #9923

Merged
robfrank merged 4 commits into
mainfrom
fix/9883-promql-aggregation-scalar-fn-range-vector
Oct 13, 2026
Merged

robfrank merged 4 commits into
mainfrom
fix/9883-promql-aggregation-scalar-fn-range-vector

Conversation

@robfrank

@robfrank robfrank commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #9883

PromQLEvaluator answered silently where Prometheus' type checker refuses: an aggregation over a range vector, a scalar or a string answered an empty vector, a math function (abs, ceil, floor, round) over a range vector returned it unchanged and over a string answered a NaN scalar, and a non-scalar round precision was replaced with 1. Each now raises an IllegalArgumentException in Prometheus' wording, on the evaluated argument like #9723, #9743 and #9788. The same function call path also refused nothing on a wrong argument count (abs() threw NoSuchElementException, abs(m, 1) ignored the extra), and the range-function argument refusal used non-Prometheus wording; both are aligned here.

Finding ledger

# Finding (from the issue) Status
1a sum(m[5m]) answers an empty vector fixed: expected type instant vector in aggregation expression, got range vector
1b sum(1) answers an empty vector fixed: ... got scalar (and got string for sum("a"))
2a abs(m[5m]) returns the range vector fixed: expected type instant vector in call to function "abs", got range vector
2b abs("a") evaluates to a NaN scalar fixed: ... got string
2c non-scalar round precision silently defaults to 1 fixed: expected type scalar in call to function "round", got <type>

Completeness

Invariant: every argument of an aggregation or a function call is evaluated and checked against the type Prometheus requires before it is used; nothing of the wrong type is answered silently.

$ grep -n "return new InstantVector(List.of())\|return argResult\|Double.NaN, evalTimeMs\|instanceof RangeVector" PromQLEvaluator.java   (before the fix)
237: StringLiteral -> NaN scalar             (string source; handled by reading the expression type)
250-313: vector selector, metric/type absent  (legitimate empty result, not a type check)
401: evaluateAggregation non-instant inner -> empty vector   (1a/1b, fixed)
494/497: range function, wrong arg -> "requires a range vector argument"   (wording aligned)
538: evaluateScalarFunction -> return argResult   (2a/2b, fixed)
551: extractSecondParam non-scalar -> 1.0   (2c, fixed)
205/217: evaluateRange keeps only InstantVector/ScalarResult per step   (top-level, filed #9922)
Entry point Status
evaluateAggregation inner expression (sum/avg/min/max/count/topk/bottomk, by/without) fixed here, tested
evaluateScalarFunction first argument (abs/ceil/floor/round) fixed here, tested
extractSecondParam (round precision) fixed here, tested
argument count of math and range functions fixed here, tested
range-function argument type wording fixed here, tested
instant query, range query, SQL promql() all reach evaluate(); tested through evaluateInstant, evaluateRange and RETURN promql(...)
HTTP /prometheus/api/v1/query(_range) same PromQLEvaluator; IllegalArgumentException already maps to a 400 there (as for #9788)
top-level range vector / string in a range query answers an empty matrix filed #9922 (not an argument of an aggregation or function)

Known gaps: #9922 (top-level expression type of a range query), #9924 (math functions still accept a scalar argument).

Deliberately kept: a scalar argument to a math function (abs(-1)) stays accepted. Prometheus refuses it (got scalar), but existing tests (#9723, #9743) and queries rely on abs(-1) being a scalar; tightening it is a behavior change beyond this issue, tracked in #9924.

Test plan

Adversarial pass

Not run as an independent pass: this session had no subagent-spawning tool. An in-session check covered a parenthesized string (abs(("a")), the parser drops the parens, so the expression is still a StringLiteral), a string as an aggregation inner (topk(1, "a"), reported as got string, not got scalar), and the top-level range query (filed as #9922).

Review cycles

Cycle Head Changes Bot outcome
1 5d169d1d02 initial fix + regression test LGTM; suggested removing the unreachable IllegalStateException, a range() test helper, release notes, a follow-up for scalar leniency
2 26cd160149 dropped the unreachable branch (cast after the type check), range() helper; filed #9924 LGTM; suggested a parenthesized-string test, an arity comment, a comment on aggregate(), HTTP 400 confirmation
3 fa54c65bbe ("a") argument tests, arity and helper comments LGTM; optional nits: pin the reported argument when both round() args are wrong, document "matrix", pointer in isRangeFunction
4 318f3ad24b round(m[5m], "a") test, both comments LGTM pending CI, non-blocking suggestions only (below)

Deferred items

  • "Please confirm the HTTP handler maps this to a 400 (bad_data) and not a 500" - confirmed by reading the code, no new IT: GetPromQLQueryHandler (line 113) and GetPromQLQueryRangeHandler (line 119) catch IllegalArgumentException around evaluation and answer 400 bad_data, the same path PromQL: a binary operator with a range-vector operand answers a scalar NaN where Prometheus rejects it #9788's refusals take.
  • "Behavior change ... A line in the release notes or changelog would help" - release notes live outside this PR; owed for 26.11.1: sum(m[5m]), sum(1), abs(m[5m]), abs("a") and a non-scalar round precision now answer 400 instead of an empty or unchanged result.
  • "checkArgumentCount ... could be flattened a little" - skipped, stylistic.
  • "an expensive first argument is evaluated before a bad precision is rejected" - skipped, the reviewer called it negligible; the order matches Prometheus reporting the first mismatched argument.
  • "theSqlFunctionIsRefusedToo ... asserting on the root cause message only may be more robust" - skipped, same assertion shape as PromQL: a binary operator with a range-vector operand answers a scalar NaN where Prometheus rejects it #9788's passing test.
  • Cycle 4 (max cycles reached, not applied): link PromQL: abs/ceil/floor/round accept a scalar argument that Prometheus refuses #9924 from the code comment; a test that every isRangeFunction name refuses 2 arguments; Codecov may flag the unreachable "matrix" branch; confirm the parser rejects sum() / topk(1); round(m, 1, 2) through a range query.

Final state: max-cycles-reached (every bot review was LGTM; only non-blocking suggestions remain).

🤖 Generated with Claude Code

… of the wrong type

sum(m[5m]) and sum(1) answered an empty vector, abs(m[5m]) returned the range vector
unchanged, abs("a") became a NaN scalar and a non-scalar round precision was silently
replaced with 1. Each is now refused with Prometheus' type-check wording, as are a wrong
argument count and a non-range-vector argument to a range function.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@robfrank robfrank added this to the 26.11.1 milestone Oct 13, 2026
@robfrank robfrank added bug timeseries Time series module labels Oct 13, 2026
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 5 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6fbeb855-50e0-49f5-a944-1a532a0d49bd
📥 Commits

Reviewing files that changed from the base of the PR and between d557c8c and 318f3ad.

📒 Files selected for processing (2)
  • engine/src/main/java/com/arcadedb/engine/timeseries/promql/PromQLEvaluator.java
  • engine/src/test/java/com/arcadedb/engine/timeseries/promql/Issue9883PromQLFunctionArgumentTypeTest.java
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@claude

claude Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review

Overall this is a clean, well-scoped fix. The type checks run on the evaluated argument (consistent with #9723/#9743/#9788), the error wording follows Prometheus, and the PR description gives a clear ledger of what was and wasn't changed.

Looks good

  • Aggregation inner-type check runs before the topk/bottomk parameter, matching Prometheus' checker order, and the test pins that order.
  • valueTypeName uses an exhaustive switch over the sealed result type, so a new result type will fail to compile instead of silently falling through.
  • StringLiteral is handled explicitly, since it evaluates to a NaN scalar. Good catch.
  • The tests cover instant, range and SQL entry points, nested refusals, and a "valid arguments still work" case. They follow the CLAUDE.md style (assertThat, final params).

Suggestions / minor points

  1. Argument-count message wording. Prometheus' parser says expected 1 argument(s) in call to "abs", got 0, so that one matches. For variadic functions the Prometheus form is expected at least N argument(s)... / at most. That matches too. Fine.
  2. Behavior change risk in evaluateAggregation. Previously a scalar inner (e.g. sum(1)) returned an empty vector; it now throws. This is intended, but it is a visible behavior change for dashboards that happened to work. A line in the release notes or changelog would help.
  3. Inconsistency kept deliberately. abs(-1) is accepted although Prometheus refuses it. The PR documents this, but the new error message for abs(<scalar-expr>)-like cases in nested contexts (e.g. abs(m9883 > bool 1) is fine, but abs(time())) is also accepted. Consider a follow-up issue so the leniency is tracked rather than just mentioned in the PR body.
  4. Dead branch. The IllegalStateException after the scalar/instant branches is unreachable by construction. Restructuring so the instant-vector case is the final return (cast after the check) would remove the unreachable throw and the duplicated type test.
  5. Evaluation order. In evaluateScalarFunction, the first argument is evaluated before the argument-count check for the second one is complete, and the precision is evaluated only after the first argument is type-checked. That is fine, but it means an expensive first argument is evaluated before a bad precision is rejected. Evaluating nothing until the cheap structural checks pass is a negligible win; not blocking.
  6. Test nit. aRangeQueryIsRefusedToo repeats the evaluator/parse boilerplate; a small range(String) helper like the existing instant(String) would tidy it. Also theSqlFunctionIsRefusedToo asserts IllegalArgumentException through the SQL layer; if the SQL executor ever wraps exceptions this will break, so asserting on the root cause message only may be more robust.
  7. Tags. The class is fast, so no @Tag is needed.

Security / performance

No security concerns. The added checks are instanceof tests on the existing path, so there is no measurable overhead and no new allocations on the hot path (the message strings are only built on failure).

No blocking issues from my side. LGTM once you have considered items 2 and 4.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 11 complexity

Metric Results
Complexity 11

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

…, add a range() test helper

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review

Overall this is a clean, well-scoped fix. The inner type is checked before the topk/bottomk parameter, as Prometheus does. The error wording matches Prometheus. The ledger and completeness table in the description are helpful. The test coverage is thorough: it covers instant, range and SQL entry points, nested expressions, and "valid still works" cases. I didn't build or run the tests.

Observations

  1. Scalar still accepted by math functions (intentional deviation). abs(1) and round(7.3, 0.5) stay valid although Prometheus refuses them. The comment and test document this, which is good. The error text claims "expected type instant vector ... got scalar" is never produced for these, so users get a mix of strict and lenient behavior. Consider a follow-up issue to track tightening it, so the leniency doesn't become permanent by accident.
  2. round precision with an instant-vector first arg. round(1, m9883) is refused (tested), good. Note that Prometheus' precision check is on the parameter type only, so this matches.
  3. Argument-count message wording. expected 1 argument(s) in call to "abs", got 0 is close to Prometheus' text ("expected 1 argument(s) in call to "abs", got 0"), fine. The "at least/at most" variants for round are slightly different from Prometheus' own text, which is "expected at most 2 argument(s)..."; low impact.
  4. checkArgumentCount for range functions is min == max == 1. This is correct today, since isRangeFunction only lists the single-arg functions. If quantile_over_time or predict_linear are added later, the count has to change. A one-line comment at the call site would help the next person.
  5. String detection by expression type. valueTypeName and the aggregation check use instanceof StringLiteral because a string evaluates to a NaN scalar. It works for literals, but it is a workaround for the evaluator having no string result type. A parenthesised string would likely still parse to a StringLiteral; worth a test like sum(("a")) if the parser wraps parens in a node.
  6. Style (CLAUDE.md). valueTypeName's switch is exhaustive over the sealed PromQLResult, which is good. The test class sits well within the conventions (AssertJ, TestHelper). Minor: aggregate() uses String.format with a %s template, which is fine for tests but a little cryptic; a comment would help.

Performance/security: no concerns. The checks are on already-evaluated results, with no extra allocation on the hot path.

Behavior change to note: queries that previously returned empty results for sum(m[5m]) now raise IllegalArgumentException. Please confirm the HTTP handler maps this to a 400 (bad_data) and not a 500; the description mentions the HTTP endpoints, so an HTTP-level test would be a good addition if not already present.

LGTM pending those minor points.

…nge-function arity and the aggregate() helper

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review

Overall this is a solid, well-scoped fix. It reuses the existing isScalarOrInstantVector helper and follows the pattern of #9723, #9743 and #9788. The 12 regression tests cover the ledger well, including nested refusals, range queries and the SQL promql() path. No blocking issues found.

Minor observations

  1. Order of checks in evaluateScalarFunction. The argument count is checked, then the first argument is evaluated, then its type, then the round precision. For round(m[5m], "a") the error is about the first argument, which matches Prometheus (it reports the first mismatched argument). This is fine, but the order isn't pinned down for the case where both are wrong. A test would document it.
  2. valueTypeName and MatrixResult. The exhaustive switch is good. The "matrix" name isn't a Prometheus type name. It's only reachable if a MatrixResult ever comes out of evaluate(), so consider a comment or checking that it can't reach these paths.
  3. checkArgumentCount wording. expected 1 argument(s) matches Prometheus' format, so that's fine. The min == max branch and the two else if branches could be flattened a little for readability, but this is purely stylistic.
  4. Range-function count comment. The comment says "quantile_over_time or predict_linear would not" take one argument. If someone adds those to isRangeFunction later, the shared checkArgumentCount(..., 1, 1) will silently reject them. A short pointer in isRangeFunction would help.
  5. Tests. The tests construct PromQLEvaluator per call and look good. AGGREGATIONS mixes plain names and %s templates, which is slightly clever. A tiny comment already explains aggregate(), so that's acceptable.
  6. Behavior note. Scalar arguments to math functions are deliberately still accepted, and this is documented. It would be worth a follow-up issue so the leniency doesn't get forgotten.

CLAUDE.md conventions

  • Uses final, imports and AssertJ style correctly. There are no System.out calls and no new dependencies.
  • No wall-clock assertions. No fixed ports.

LGTM, with the optional nits above.

… are wrong, document the range-function arity and the matrix type name

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review of #9923

Overall this is a clean, well-scoped fix. I read the diff only and did not build or run the tests.

What looks good

Suggestions (non-blocking)

  1. abs(-1) and the other math functions on a scalar are still accepted, though Prometheus refuses them. The comment and test document this as deliberate. Please file a follow-up issue and link it from the comment, so the divergence is tracked.
  2. The isRangeFunction comment says quantile_over_time and predict_linear need their own count. A cheap guard against someone adding them to the switch without updating the count is a small test that asserts every name in isRangeFunction rejects 2 arguments.
  3. The case MatrixResult ignored -> "matrix" branch is unreachable per the comment. That is fine for exhaustiveness, but it cannot be covered by a test, so it may show up as an uncovered line in Codecov.
  4. sum() or topk(1) with a missing inner expression is a parser concern. Please confirm the parser rejects these, since the evaluator no longer needs to guard them.
  5. The "argument(s)" wording matches Prometheus. Consider also testing round(m, 1, 2) through a range query, though one path is probably enough.

There are no performance or security concerns. The added checks are instanceof tests on the existing path.

LGTM, pending CI.

@robfrank
robfrank merged commit 1e13a69 into main Oct 13, 2026
robfrank added a commit that referenced this pull request Oct 21, 2026
… of the wrong type (#9923)

* fix(#9883): PromQL aggregations and math functions refuse an argument of the wrong type

sum(m[5m]) and sum(1) answered an empty vector, abs(m[5m]) returned the range vector
unchanged, abs("a") became a NaN scalar and a non-scalar round precision was silently
replaced with 1. Each is now refused with Prometheus' type-check wording, as are a wrong
argument count and a non-range-vector argument to a range function.

(cherry picked from commit 1e13a69)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug timeseries Time series module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PromQL: an aggregation or a scalar function over a range vector answers silently instead of refusing it

1 participant