fix(translate): saturate out-of-range integer fields

Go leaves a float to int64 conversion implementation-defined when the value is out of range, so a huge max_tokens could become a negative number on some architectures. The conversion now saturates to the int64 range and refuses NaN.
This commit is contained in:
2026-11-03 00:27:11 +00:00
parent 1236aa4901
commit 138ced884e
2 changed files with 45 additions and 2 deletions
+11 -2
View File
@@ -3,6 +3,7 @@ package traefikllmgateway
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"unicode/utf8"
@@ -100,12 +101,20 @@ func toFloat64(v any) (float64, bool) {
}
// toInt64 is toFloat64 truncated to an integer, for fields (max_tokens)
// Anthropic's API requires as a JSON integer.
// Anthropic's API requires as a JSON integer. A value outside the int64
// range saturates, because Go leaves that conversion implementation-defined;
// NaN is refused.
func toInt64(v any) (int64, bool) {
f, ok := toFloat64(v)
if !ok {
if !ok || math.IsNaN(f) {
return 0, false
}
switch {
case f >= math.MaxInt64:
return math.MaxInt64, true
case f <= math.MinInt64:
return math.MinInt64, true
}
return int64(f), true
}
+34
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"errors"
"math"
"net/http"
"net/http/httptest"
"os"
@@ -1189,3 +1190,36 @@ func TestAppendJSONStringMatchesMarshal(t *testing.T) {
}
}
}
// TestToInt64_Saturates pins toInt64's defined behaviour for out-of-range
// and non-finite floats, which Go otherwise leaves implementation-defined.
func TestToInt64_Saturates(t *testing.T) {
t.Parallel()
tests := []struct {
in any
name string
want int64
wantOK bool
}{
{name: "fraction truncates toward zero", in: 42.9, want: 42, wantOK: true},
{name: "negative fraction truncates toward zero", in: -3.7, want: -3, wantOK: true},
{name: "zero", in: 0.0, want: 0, wantOK: true},
{name: "int passes through", in: 7, want: 7, wantOK: true},
{name: "huge positive saturates", in: 1e300, want: math.MaxInt64, wantOK: true},
{name: "huge negative saturates", in: -1e300, want: math.MinInt64, wantOK: true},
{name: "just above int64 saturates", in: 9.3e18, want: math.MaxInt64, wantOK: true},
{name: "positive infinity saturates", in: math.Inf(1), want: math.MaxInt64, wantOK: true},
{name: "negative infinity saturates", in: math.Inf(-1), want: math.MinInt64, wantOK: true},
{name: "NaN is refused", in: math.NaN(), want: 0, wantOK: false},
{name: "string is refused", in: "5", want: 0, wantOK: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, ok := toInt64(tt.in)
if got != tt.want || ok != tt.wantOK {
t.Errorf("toInt64(%v) = (%d, %v), want (%d, %v)", tt.in, got, ok, tt.want, tt.wantOK)
}
})
}
}