Merge branch 'fix/l4'

This commit is contained in:
2026-11-03 00:12:09 +00:00
10 changed files with 230 additions and 10 deletions
+3
View File
@@ -95,6 +95,9 @@ func (c *concurrencyLearner) observe(provider string, resp *http.Response, err e
if next < 1 {
next = 1
}
if next > learnedCeiling-1 {
next = learnedCeiling - 1
}
if s.learned == 0 || next < s.learned {
s.learned = next
}
+36
View File
@@ -0,0 +1,36 @@
package traefikllmgateway
import (
"net/http"
"testing"
)
// TestConcurrencyLearner_OverloadStaysBelowCeiling pins that an overload
// observation on an unknown limit never learns a value at or above the
// ceiling, however many requests were in flight.
func TestConcurrencyLearner_OverloadStaysBelowCeiling(t *testing.T) {
t.Parallel()
tests := []struct {
name string
inFlight int
}{
{name: "one in flight", inFlight: 1},
{name: "typical load", inFlight: 8},
{name: "exactly at ceiling", inFlight: 2 * learnedCeiling},
{name: "far above ceiling", inFlight: 1000},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newConcurrencyLearner(0)
for range tt.inFlight {
_ = c.begin("p")
}
c.observe("p", &http.Response{StatusCode: http.StatusTooManyRequests}, nil)
got := c.limit("p")
if got < 1 || got > learnedCeiling-1 {
t.Errorf("limit = %d, want in [1, %d]", got, learnedCeiling-1)
}
})
}
}
+8 -1
View File
@@ -231,7 +231,14 @@ func newAdapterHTTPClient(timeout time.Duration) *http.Client {
}
tr.MaxIdleConnsPerHost = adapterIdleConnsPerHost
tr.ResponseHeaderTimeout = timeout
return &http.Client{Transport: tr}
// Redirects are not followed: the client re-sends provider API key
// headers, and a hijacked redirect target would receive them.
return &http.Client{
Transport: tr,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// attemptRecorder is invoked once per upstream HTTP attempt a shared
+49
View File
@@ -6,8 +6,11 @@ import (
"errors"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"testing/iotest"
"time"
)
// TestProviderPassthroughEnabled is the security+performance audit
@@ -210,3 +213,49 @@ func TestReadAllLimited_PropagatesNonEOFError(t *testing.T) {
t.Errorf("readAllLimited err = %v, want errors.Is match for %v", gotErr, injected)
}
}
// TestAdapterHTTPClient_RedirectHandling pins that the adapter client
// never follows a redirect, so provider API key headers are not re-sent
// to a redirect target.
func TestAdapterHTTPClient_RedirectHandling(t *testing.T) {
t.Parallel()
tests := []struct {
name string
wantStatus int
wantFollowed bool
}{
{name: "redirect returned to caller, target not contacted", wantStatus: http.StatusFound, wantFollowed: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var followed atomic.Bool
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
followed.Store(true)
}))
t.Cleanup(target.Close)
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusFound)
}))
t.Cleanup(redirector.Close)
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, redirector.URL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext: %v", err)
}
req.Header.Set("x-api-key", "test-key")
resp, err := newAdapterHTTPClient(time.Second).Do(req)
if err != nil {
t.Fatalf("Do: %v", err)
}
t.Cleanup(func() { _ = resp.Body.Close() })
if resp.StatusCode != tt.wantStatus {
t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus)
}
if got := followed.Load(); got != tt.wantFollowed {
t.Errorf("redirect target contacted = %v, want %v", got, tt.wantFollowed)
}
})
}
}
+8 -1
View File
@@ -171,7 +171,7 @@ func defaultWaitFn(ctx context.Context, d time.Duration) bool {
// tries total); the maximum, maxRetryAttempts, is 3 retries (four tries
// total). A value outside 1..maxRetryAttempts is a config error.
// rc.Backoff defaults to defaultRetryBackoff when left empty, and must
// parse via time.ParseDuration either way.
// parse via time.ParseDuration to a positive duration either way.
func newRetryPolicy(rc RetryConfig) (*retryPolicy, error) {
if !rc.Enabled {
return &retryPolicy{enabled: false, waitFn: defaultWaitFn}, nil
@@ -193,6 +193,9 @@ func newRetryPolicy(rc RetryConfig) (*retryPolicy, error) {
if err != nil {
return nil, fmt.Errorf("llmgateway: retry.backoff: %w", err)
}
if backoff <= 0 {
return nil, fmt.Errorf("llmgateway: retry.backoff must be positive, got %q", backoffStr)
}
return &retryPolicy{enabled: true, attempts: attempts, backoff: backoff, waitFn: defaultWaitFn}, nil
}
@@ -263,6 +266,10 @@ func (p *retryPolicy) waitBefore(attempt int, resp *http.Response) (wait time.Du
}
}
// Compare before multiplying: a backoff at or above the cap must not overflow the shift.
if p.backoff >= maxRetryWait {
return maxRetryWait, false
}
wait = p.backoff * time.Duration(int64(1)<<uint(attempt-1))
if wait > maxRetryWait {
wait = maxRetryWait
+49
View File
@@ -1087,3 +1087,52 @@ func TestRetryPolicy_Do_NoAttemptRecorderInContext_NoPanic(t *testing.T) {
t.Errorf("resp.StatusCode = %d, want 200", resp.StatusCode)
}
}
// TestNewRetryPolicy_RejectsNonPositiveBackoff pins that a zero or
// negative backoff is a config error, not a silent no-wait retry.
func TestNewRetryPolicy_RejectsNonPositiveBackoff(t *testing.T) {
t.Parallel()
tests := []struct {
name string
backoff string
wantErr bool
}{
{name: "zero", backoff: "0s", wantErr: true},
{name: "negative", backoff: "-1s", wantErr: true},
{name: "positive", backoff: "1ms", wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
_, err := newRetryPolicy(RetryConfig{Enabled: true, Backoff: tt.backoff})
if (err != nil) != tt.wantErr {
t.Errorf("newRetryPolicy(Backoff:%q) err = %v, wantErr %v", tt.backoff, err, tt.wantErr)
}
})
}
}
// TestRetryPolicy_WaitBeforeLargeBackoffCapped pins that a backoff at or
// above the cap returns the cap for every attempt, without overflowing.
func TestRetryPolicy_WaitBeforeLargeBackoffCapped(t *testing.T) {
t.Parallel()
tests := []struct {
name string
backoff time.Duration
}{
{name: "equal to cap", backoff: maxRetryWait},
{name: "int64 overflow range", backoff: time.Duration(1) << 62},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
p := &retryPolicy{enabled: true, attempts: maxRetryAttempts, backoff: tt.backoff, waitFn: defaultWaitFn}
for attempt := 1; attempt <= maxRetryAttempts; attempt++ {
got, fromRetryAfter := p.waitBefore(attempt, nil)
if got != maxRetryWait || fromRetryAfter {
t.Errorf("attempt %d: waitBefore = (%v, %v), want (%v, false)", attempt, got, fromRetryAfter, maxRetryWait)
}
}
})
}
}
+8 -4
View File
@@ -442,11 +442,15 @@ func newTeeBudget(limit int64) *teeBudget { return &teeBudget{limit: limit} }
// reserve claims n bytes and reports whether the budget had room.
func (b *teeBudget) reserve(n int64) bool {
if atomic.AddInt64(&b.used, n) > b.limit {
atomic.AddInt64(&b.used, -n)
return false
for {
cur := atomic.LoadInt64(&b.used)
if cur+n > b.limit {
return false
}
if atomic.CompareAndSwapInt64(&b.used, cur, cur+n) {
return true
}
}
return true
}
func (b *teeBudget) free(n int64) { atomic.AddInt64(&b.used, -n) }
+32
View File
@@ -351,3 +351,35 @@ func TestLogSafe(t *testing.T) {
assert.Equal(t, `a\nllmgw[x] ERROR forged`, logSafe("a\nllmgw[x] ERROR forged"))
assert.Equal(t, `a\r\nb`, logSafe("a\r\nb"))
}
// TestTeeBudget_ReserveNeverExceedsLimit pins that concurrent reserves
// grant exactly the budget: used never passes limit, and no reserve is
// denied while room remains.
func TestTeeBudget_ReserveNeverExceedsLimit(t *testing.T) {
t.Parallel()
const (
limit = 100
chunk = 10
workers = 50
)
b := newTeeBudget(limit)
var granted atomic.Int64
var overshoot atomic.Bool
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
if b.reserve(chunk) {
granted.Add(chunk)
}
if atomic.LoadInt64(&b.used) > limit {
overshoot.Store(true)
}
}()
}
wg.Wait()
assert.False(t, overshoot.Load(), "used must never exceed limit")
assert.EqualValues(t, limit, granted.Load(), "exactly the budget is granted")
assert.EqualValues(t, limit, atomic.LoadInt64(&b.used))
}
+10 -4
View File
@@ -39,6 +39,11 @@ const sseScannerMaxLineSize = 4 * 1024 * 1024
// tuning knob.
const sseMaxEventBytes = 8 * 1024 * 1024
// sseDataLineOverhead is the per-"data:" line cost counted against
// sseMaxEventBytes: 1 byte for the joined "\n" plus the 16-byte string
// header the dataLines slice retains for the line.
const sseDataLineOverhead = 1 + 16
// errSSEEventTooLarge is returned by readSSE when one event's accumulated
// "data:" payload exceeds sseMaxEventBytes. It mirrors how the per-line
// cap surfaces (bufio.ErrTooLong is returned as-is): the caller's stream
@@ -195,10 +200,11 @@ func readSSE(r io.Reader, fn func(sseEvent) error) error {
case "event":
event = value
case "data":
// +1 for the "\n" this line will contribute to the joined
// payload. Checked BEFORE appending, so the cap bounds what is
// actually held rather than catching it one line late.
dataBytes += len(value) + 1
// Each line costs its payload plus the "\n" it adds to the
// joined payload plus the string header dataLines retains, so
// many empty lines cannot amplify past the cap. Checked BEFORE
// appending, so the cap bounds what is actually held.
dataBytes += len(value) + sseDataLineOverhead
if dataBytes > sseMaxEventBytes {
return errSSEEventTooLarge
}
+27
View File
@@ -571,3 +571,30 @@ func TestNewFlushWriter_AssertsFlusherOnce(t *testing.T) {
}
})
}
// TestReadSSE_EmptyDataLinesCountTheirRetainedCost pins that an event of
// many empty "data:" lines hits the size cap on retained cost, not just
// payload bytes.
func TestReadSSE_EmptyDataLinesCountTheirRetainedCost(t *testing.T) {
t.Parallel()
maxLines := sseMaxEventBytes / sseDataLineOverhead
tests := []struct {
wantErr error
name string
lines int
}{
{name: "few lines", lines: 10, wantErr: nil},
{name: "just under the cap", lines: maxLines - 10, wantErr: nil},
{name: "past the cap", lines: maxLines + 10, wantErr: errSSEEventTooLarge},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
input := strings.Repeat("data:\n", tt.lines) + "\n"
err := readSSE(strings.NewReader(input), func(sseEvent) error { return nil })
if !errors.Is(err, tt.wantErr) {
t.Errorf("readSSE err = %v, want %v", err, tt.wantErr)
}
})
}
}