From d603780560a4cfe33be837da7dc88c546e9c8083 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Wed, 25 Nov 2026 13:43:46 +0000 Subject: [PATCH] fix(router): keep decision calls out of upstream accounting --- smart_router_decision.go | 9 ++++++++- smart_router_decision_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/smart_router_decision.go b/smart_router_decision.go index a9da220..85a1c8c 100644 --- a/smart_router_decision.go +++ b/smart_router_decision.go @@ -366,7 +366,7 @@ func (g *Gateway) callDecisionModel(ctx context.Context, rt *smartRouter, state if body == nil { return 0, 0, decisionError } - callCtx, cancel := context.WithTimeout(ctx, cfg.timeout) + callCtx, cancel := context.WithTimeout(withoutUpstreamAccounting(ctx), cfg.timeout) defer cancel() probe := &http.Request{Header: http.Header{}} oa.injectAuth(probe) @@ -399,3 +399,10 @@ func decisionFailure(parent, call context.Context) string { } return decisionError } + +// withoutUpstreamAccounting hides the request's recorders so the decision call is not billed to the user's request. +func withoutUpstreamAccounting(ctx context.Context) context.Context { + ctx = context.WithValue(ctx, attemptRecorderCtxKey{}, nil) + ctx = context.WithValue(ctx, latencyRecorderCtxKey{}, nil) + return context.WithValue(ctx, firstByteCtxKey{}, nil) +} diff --git a/smart_router_decision_test.go b/smart_router_decision_test.go index 4d14cd6..588f605 100644 --- a/smart_router_decision_test.go +++ b/smart_router_decision_test.go @@ -446,3 +446,36 @@ func TestRouterDecisionOutcomeNames(t *testing.T) { t.Fatalf("got %d outcomes", len(seen)) } } + +func TestRouterDecisionIgnoresRequestRecorders(t *testing.T) { + f := newDecisionFixture(t, 3, "", okHandler) + var attempts, latencies int64 + ctx := withAttemptRecorder(context.Background(), func(*http.Response, error) { atomic.AddInt64(&attempts, 1) }) + ctx = withLatencyRecorder(ctx, func(latencySample) { atomic.AddInt64(&latencies, 1) }) + if a := f.g.askDecisionModel(ctx, f.rt, "s"); a.outcome != "" { + t.Fatalf("outcome %q", a.outcome) + } + if n := atomic.LoadInt64(&attempts); n != 0 { + t.Fatalf("attempt recorder called %d times", n) + } + if n := atomic.LoadInt64(&latencies); n != 0 { + t.Fatalf("latency recorder called %d times", n) + } +} + +func TestRouterDecisionNonOpenAIProviderIsError(t *testing.T) { + f := newDecisionFixture(t, 3, "", okHandler) + f.g.adapters["gx10"] = &fakeAdapter{} + if a := f.g.askDecisionModel(context.Background(), f.rt, "s"); a.outcome != decisionError { + t.Fatalf("outcome %q", a.outcome) + } +} + +func TestRouterDecisionParentCancelIsError(t *testing.T) { + f := newDecisionFixture(t, 3, "", okHandler) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if a := f.g.askDecisionModel(ctx, f.rt, "s"); a.outcome != decisionError { + t.Fatalf("outcome %q", a.outcome) + } +}