Skip to content

evalengine: return an error when float arithmetic overflows - #22105

Open
BahaaMattar wants to merge 2 commits into
vitessio:mainfrom
BahaaMattar:evalengine-float-arith-overflow
Open

BahaaMattar wants to merge 2 commits into
vitessio:mainfrom
BahaaMattar:evalengine-float-arith-overflow

Conversation

@BahaaMattar

@BahaaMattar BahaaMattar commented Nov 20, 2026 •

Copy link
Copy Markdown

Description

+, - and * on DOUBLE values returned +Inf or -Inf when the result does not fit in a DOUBLE. MySQL fails the statement with ERROR 1690 (22003): DOUBLE value is out of range instead (Item_func_plus, Item_func_minus and Item_func_mul end in check_float_overflow), and evalengine already does the same for / (mathDiv_ff0).

  • arithmetic.go: new mathAdd_ff0, mathSub_ff0 and mathMul_ff0, shaped like mathDiv_ff0. They return dataOutOfRangeError(..., "DOUBLE", op) when the result is not finite. mathAdd_ff, mathSub_ff and mathMul_ff now return that error to their callers.
  • compiler_asm.go: the compiled Add_ff, Sub_ff and Mul_ff use the same helpers, so the interpreter and the compiled program agree.
  • A constant expression such as 1e308 * 10 is now reported when it is translated, like the existing 1e308 / 0.1.

Results that still fit in a DOUBLE are unchanged, with one exception found in review: evalengine evaluates every argument of CASE (and so IF and IFNULL) and of COALESCE, so an overflow in an argument that is not returned now fails the whole expression, while MySQL returns the chosen value. See the review discussion. This is a bug fix; I don't think it needs a backport.

Motivation

How do you use Vitess? (pick one)

  • In production
  • In staging or development
  • Evaluating it
  • I don't use Vitess

Did you run this change against a real Vitess deployment? No. I found this by reading the float helpers in arithmetic.go next to the division one, which already returns this error. I reproduced it with a unit test on main: TestFloatArithmeticOverflow fails there (interpreter returned FLOAT64(+Inf), want an error containing "DOUBLE value is out of range", and the same for the compiler) and passes with this change. I did not have a MySQL server; the MySQL behaviour is taken from the MySQL 8.4 source (Item_func_plus::real_op, Item_func_minus::real_op, Item_func_mul::real_op).

Related Issue(s)

Fixes #22104

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI? (they pass locally; CI pending)
  • Documentation was added or is not required

Deployment Notes

None. A query whose DOUBLE +, - or * overflows inside vtgate now fails with the MySQL error instead of returning +Inf/-Inf.

AI Disclosure

Developed with AI assistance; I reviewed and tested every change.

Adding, subtracting or multiplying DOUBLE values returned +Inf or -Inf when the
result did not fit in a DOUBLE. MySQL fails the statement with ERROR 1690
(22003) "DOUBLE value is out of range" instead, and evalengine already does so
for division.

Make +, - and * return the same error, in the AST interpreter and in the
compiled program.

Fixes vitessio#22104

Signed-off-by: Bahaa Mattar <bahaa.kmattar@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 20, 2026 00:33
@github-actions github-actions Bot added this to the v25.0.0 milestone Nov 20, 2026
@vitess-bot vitess-bot Bot added NeedsWebsiteDocsUpdate What it says NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Nov 20, 2026
@vitess-bot

vitess-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

@github-actions github-actions Bot added Component: Evalengine changes to the evaluation engine Component: VTGate labels Nov 20, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues block the change to return out-of-range errors for DOUBLE arithmetic overflow.

No open issues 🎉

What changed in this PR

This PR aligns evalengine’s DOUBLE addition, subtraction, and multiplication with MySQL by returning an out-of-range error instead of infinity when arithmetic overflows, addressing #22104.

Changes:

  • Add shared overflow-checking helpers and propagate errors through interpreted and compiled evaluation.
  • Add regression tests for overflow, mixed numeric operands, finite results, and constant folding.
File Description
go/​vt/​vtgate/​evalengine/​compiler_asm.go Use checked float helpers in compiled arithmetic instructions.
go/​vt/​vtgate/​evalengine/​arithmetic.go Detect non-finite arithmetic results and return DOUBLE range errors.
go/​vt/​vtgate/​evalengine/​arithmetic_float_test.go Test interpreter/compiler behavior and translation-time constant overflow.

Review effort: Balanced

@mattlord mattlord left a comment

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.

Thanks for this!

  1. Blocking: I think that we should make the new error come only from the argument that a conditional returns. evalengine evaluates every argument of CASE before choosing one, both in the interpreter (go/vt/vtgate/evalengine/expr_logical.go:587) and in the compiled CmpCase (go/vt/vtgate/evalengine/compiler_asm.go:539). IF is rewritten into a CASE (go/vt/vtgate/evalengine/translate_builtin.go:1203), and IFNULL and COALESCE also evaluate every argument. Until now, an overflowing argument that wasn't chosen became +Inf and was thrown away. With this change, its error fails the whole expression. On this head, with column0 = 10 and column1 = 1.7976931348623157e308, IF(column1 < 1e300, column1 * column0, column1), CASE WHEN column1 < 1e300 THEN column1 * 1e10 ELSE column1 END and IFNULL(column0, column1 * 10) all fail with DOUBLE value is out of range, in both the interpreter and the compiled program, while main returns the chosen value. MySQL 8.0.46 and 8.4.9 also return the chosen value. Over DOUBLE columns, IF(v < 1e300, v * w, v) returns 1.7976931348623157e308, IFNULL(w, v * 10) returns 10, and IF(1, 0, 1e308 * 10) returns 0. This reaches real queries wherever VTGate evaluates the expression itself. For example, select if(sum(col) > 1e300, null, sum(col) * 10) from user on a sharded keyspace plans a VTGate Projection over the merged SUM. If col is a DOUBLE and the total is near the limit, the query now fails instead of returning NULL. That also contradicts "Results that still fit in a DOUBLE are unchanged" in the description. BIGINT overflow and float division already fail this way on main: CASE WHEN i < 100 THEN i * 2 ELSE i END with i = 9223372036854775807 errors, while MySQL returns i. So the root cause is the eager evaluation, and this PR extends it to +, - and * on floats, which are far more common. I think that we should make CASE, IFNULL and COALESCE evaluate only the argument that they return, either here or in a PR that lands first, and add the guarded forms above as test cases. What do you think?

  2. I think that we should also add some of these cases to the MySQL comparison corpus in go/vt/vtgate/evalengine/testcases/cases.go, such as overflowing +, - and * on DOUBLE inputs and the guarded IF, CASE and IFNULL forms. TestCompilerReference checks that the interpreter and the compiled program agree on every case there, and the evalengine unit test job compares each case against a real MySQL. The guarded forms would then be checked against MySQL itself, not against expectations taken from its source. The integration harness tolerates a MySQL value is out of range error when evalengine returns a value (go/vt/vtgate/evalengine/integration/fuzz_test.go:95), so TestFloatArithmeticOverflow would still be what checks that the error is raised.

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.37%. Comparing base (70c7a72) to head (da2fcd9).
⚠️ Report is 844 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main   #22105       +/-   ##
===========================================
+ Coverage   69.67%   79.37%    +9.70%     
===========================================
  Files        1614      502     -1112     
  Lines      216793    91149   -125644     
===========================================
- Hits       151044    72347    -78697     
+ Misses      65749    18802    -46947     
Flag Coverage Δ
partial 79.37% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

TestSelectTupleWithNonLiteralMembers built its +Inf member from 1e308*10.
Float arithmetic that overflows is an out of range error now, so the
constant no longer folds and the query goes to the shard instead of being
evaluated by vtgate.

Pass +Inf as a bind variable instead. The case still checks that a tuple
with a non-finite float member is returned rather than panicked on, and it
does not depend on which functions return +Inf: COT(0) and DEGREES(1e308)
still do, but MySQL fails on both.

Signed-off-by: Bahaa Mattar <bahaa.kmattar@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 15:47
@BahaaMattar

Copy link
Copy Markdown
Author

Thanks for the detailed review, and for checking it against MySQL 8.0 and 8.4. You are right: CASE (and so IF and IFNULL) and COALESCE evaluate every argument, so with this PR an overflow in an argument that is not returned fails the whole expression, and my "results that still fit in a DOUBLE are unchanged" line was wrong for that case. I corrected the description.

The unit test failures came from TestSelectTupleWithNonLiteralMembers, which built its +Inf tuple member from 1e308*10. That constant no longer folds, so da2fcd9 passes +Inf as a bind variable instead. The case still panics if evalTuple.ToRawBytes goes back to NewValue.

On the root cause, I agree it should be fixed before this lands. One thing I noticed: the compiler already aggregates the CASE result type statically, but the interpreter aggregates it from the runtime type of every branch (translate_test.go pins case when null then 2 when 12 = 4 then 'ohnoes' else 42 end as '42'), so the interpreter still needs the types of the branches it does not return, just not their errors. My suggestion is a separate PR that lands first, starting with CASE (which covers IF, IFNULL and NULLIF), then COALESCE, which has other open work (#22156). After that I would add the overflowing +, - and * cases and the guarded IF, CASE and IFNULL forms to testcases/cases.go here. Does that order work for you?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

l := env.vm.stack[env.vm.sp-2].(*evalFloat)
r := env.vm.stack[env.vm.sp-1].(*evalFloat)
l.f += r.f
l.f, env.vm.err = mathAdd_ff0(l.f, r.f)
return newEvalFloat(v1 + v2)
func mathAdd_ff(v1, v2 float64) (*evalFloat, error) {
result, err := mathAdd_ff0(v1, v2)
return newEvalFloat(result), err
})
require.NoError(t, err)

env := evalengine.NewExpressionEnv(t.Context(), nil, evalengine.NewEmptyVCursor(venv, time.UTC))

@mattlord mattlord left a comment

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.

Thanks for the update and for fixing the test. With the bind variable, TestSelectTupleWithNonLiteralMembers still panics if evalTuple.ToRawBytes goes back to NewValue. I checked that.

Yes, that order works for me. This head doesn't change the production code, so the earlier Blocking point still applies until the CASE change lands. Two thoughts on that PR. First, it can be tested on its own with forms that already fail on main, such as CASE WHEN i < 100 THEN i * 2 ELSE i END with i = 9223372036854775807, which MySQL evaluates to i. Second, a branch that isn't returned and fails has no runtime type for the interpreter to aggregate. I wonder if the interpreter could use the same static aggregation that CaseExpr.compile already does (go/vt/vtgate/evalengine/expr_logical.go:676), so that the two paths can't drift apart. What do you think?

@BahaaMattar

Copy link
Copy Markdown
Author

Thanks for checking the bind-variable case.

Agreed on both. The BIGINT form already fails on main, so the CASE change can be tested on its own, without this PR.

On the types, one constraint I found: the interpreter is what UntypedExpr.eval runs (translate.go:669), and there the column and bind-variable types are only known at runtime. UntypedExpr.typeof gets them through loadTypedExpression and compiles with them, so CaseExpr.compile already aggregates the static types for those runtime types. IR nodes have no typeof of their own, though, so CaseExpr.eval can't call that aggregation directly. The result type would have to come from the compiled form for the current types, or the aggregation would need a typing pass over the IR that compile also uses. Either way the result type no longer depends on evaluating branches that aren't returned, which also fixes the case where such a branch fails.

@mattlord mattlord left a comment

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.

Thanks, that matches what I see. IR has no typeof (go/vt/vtgate/evalengine/expr.go:35), only typedIR does, and UntypedExpr.typeof gets its type by compiling for the current runtime types. Either option sounds fine to me. I'd lean toward the one that leaves CASE with a single type aggregation for the interpreter and the compiler to share, so they can't drift apart. One small thing for that PR: the comment in CaseExpr.eval (go/vt/vtgate/evalengine/expr_logical.go:594) says that MySQL evaluates every branch of a CASE. That doesn't match MySQL 8.0 and 8.4, which return the chosen value when a branch that isn't returned overflows. So I think that comment should change along with the code.

CI is green at this head apart from the labels check. Until the CASE change lands, the earlier Blocking point still applies here.

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

Component: Evalengine changes to the evaluation engine Component: VTGate NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says Type: Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: evalengine returns +Inf instead of a "DOUBLE value is out of range" error when +, - or * overflow

3 participants