diff --git a/internal/gateway/otel_test.go b/internal/gateway/otel_test.go index 369ac0a22..02c538d9b 100644 --- a/internal/gateway/otel_test.go +++ b/internal/gateway/otel_test.go @@ -19,6 +19,15 @@ import ( "github.com/yetone/magpie/internal/usage" ) +// fastOTel has the exporter read the agents' transcripts and send what it +// holds within a fraction of a second, not every 2s and 5s, so a test that +// waits for an export doesn't wait seconds (#1654). +func fastOTel(t *testing.T) { + every, sessionsEvery := usage.OTelEvery, usage.OTelSessionsEvery + usage.OTelEvery, usage.OTelSessionsEvery = 200*time.Millisecond, 50*time.Millisecond + t.Cleanup(func() { usage.OTelEvery, usage.OTelSessionsEvery = every, sessionsEvery }) +} + func TestOTelSessionDedupOnlyUnkeyedLoopback(t *testing.T) { f := &fake{ctype: "application/json", reply: `{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5}}`} setup(t, provider.Chat, f) @@ -54,6 +63,7 @@ func TestOTelSessionDedupOnlyUnkeyedLoopback(t *testing.T) { t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_SESSIONS", "true") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) // Header-only first request: no user event or completed observation exists. @@ -193,6 +203,7 @@ func TestOTelSessionDiscoveredDuringFirstRequest(t *testing.T) { t.Setenv("MAGPIE_OTEL_ENDPOINT", "http://127.0.0.1:1") t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_SESSIONS", "true") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) req := httptest.NewRequest("POST", "/v1/chat/completions", nil) @@ -264,6 +275,7 @@ func TestOTelFastRequestTranscriptDiscovery(t *testing.T) { t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_SESSIONS", "true") t.Setenv("MAGPIE_OTEL_METRICS", "false") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"m1","messages":[{"role":"user","content":"hello"}]}`)) @@ -306,6 +318,7 @@ func TestOTelExportsGatewayUsageWithoutContent(t *testing.T) { t.Setenv("MAGPIE_OTEL_ENDPOINT", collector.URL) t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_METRICS", "false") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) code, body := post(t, "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"PRIVATE-PROMPT"}]}`) @@ -352,6 +365,7 @@ func TestOTelExportsBodiesWhenOn(t *testing.T) { t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_BODIES", c.bodies) + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) secret := "sk-ant-api03-" + strings.Repeat("Q7x", 30) @@ -425,6 +439,7 @@ func TestOTelWaterfallIncludesUnbilledFallback(t *testing.T) { t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_METRICS", "true") t.Setenv("MAGPIE_OTEL_BODIES", "false") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq)) @@ -533,6 +548,7 @@ func TestOTelWaterfallFailureAndCancellation(t *testing.T) { t.Setenv("MAGPIE_OTEL_HEADERS", "") t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_BODIES", "false") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"m1","messages":[{"role":"user","content":"hi"}]}`)).WithContext(ctx) @@ -591,6 +607,7 @@ func TestOTelExportsWholeBodiesWhenOn(t *testing.T) { t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_BODIES", "true") t.Setenv("MAGPIE_OTEL_BODIES_WHOLE", fmt.Sprintf("%t", c.whole)) + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) s := New() @@ -679,6 +696,7 @@ func TestOTelWholeWaterfallFallback(t *testing.T) { t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_BODIES", "true") t.Setenv("MAGPIE_OTEL_BODIES_WHOLE", "true") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) request := `{"model":"plan/m1","messages":[{"role":"user","content":"` + big + `"}],"metadata":{"api_key":"` + secret + `"}}` @@ -783,6 +801,7 @@ func TestOTelClaudeMainAndChildDedupRetainsHelper(t *testing.T) { t.Setenv("MAGPIE_OTEL_SESSIONS", "true") t.Setenv("MAGPIE_OTEL_METRICS", "false") t.Setenv("MAGPIE_OTEL_BODIES", "false") + fastOTel(t) stop := usage.StartOTel() t.Cleanup(stop) root := filepath.Join(os.Getenv("CLAUDE_CONFIG_DIR"), "projects", "p") diff --git a/internal/gateway/queue_keepalive_test.go b/internal/gateway/queue_keepalive_test.go index 02c7a228c..6b4412d4c 100644 --- a/internal/gateway/queue_keepalive_test.go +++ b/internal/gateway/queue_keepalive_test.go @@ -279,25 +279,26 @@ func TestQueuedStreamKeptAliveForTheMinute(t *testing.T) { // begun before the vendor was asked, wrote nothing until keepHeldAfter // after it began. The check is on the gateway's own writes, in order, // not on gaps a client measures, which stretch under load (3f4287e6). +// The request waits for a slot (MaxConcurrency), freed once its agent has +// heard a keepalive, so it is kept alive before the handoff however late +// it runs; a wait for room in the minute is kept alive and handed over +// the same way (keepQueued, then watch), but needed a minute sized for a +// loaded machine (#1654). func TestQueuedStreamKeptAliveOnceSentToItsVendor(t *testing.T) { for _, a := range queueAsks { t.Run(a.name, func(t *testing.T) { - // what is left of the minute when the queued request arrives, - // late under load, stays over keepHeldAfter, so it is kept - // alive before the handoff - shortMinute(t, 4*time.Second, time.Minute) - v := &streamVendor{later: time.Second} - gw := queueGateway(t, v, func(p *provider.Provider) { p.MaxRPM = 1 }) + one := 1 + v := &streamVendor{block: make(chan struct{}), later: time.Second} + gw := queueGateway(t, v, func(p *provider.Provider) { p.MaxConcurrency = &one }) keepFast(t, keepaliveGap, 100*time.Millisecond, keepaliveLongest) keepHeldAfter = 1500 * time.Millisecond // put back by queueGateway's cleanup - if code, body, _, err := askHeard(gw, a.path, a.body, nil); err != nil || code != 200 { - t.Fatalf("first: %d %v %s", code, err, body) - } + first := holdSlot(t, gw, v, a.path, a.body) req, _ := http.NewRequest("POST", gw+a.path, strings.NewReader(a.body)) req.Header.Set("Content-Type", "application/json") var from string req = req.WithContext(httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{ - GotConn: func(i httptrace.GotConnInfo) { from = i.Conn.LocalAddr().String() }, + GotConn: func(i httptrace.GotConnInfo) { from = i.Conn.LocalAddr().String() }, + GotFirstResponseByte: first.free, })) res, err := (&http.Client{Transport: &http.Transport{DisableKeepAlives: true}, Timeout: 30 * time.Second}).Do(req) if err != nil { @@ -308,6 +309,7 @@ func TestQueuedStreamKeptAliveOnceSentToItsVendor(t *testing.T) { if err != nil || res.StatusCode != 200 || !strings.Contains(string(b), ": keepalive") || !strings.Contains(string(b), "queued ok") { t.Fatalf("queued = %d %v %q, want 200, keepalives, then the reply", res.StatusCode, err, b) } + first.done(t) l, ok := writes.Load(from) if !ok { t.Fatal("no writes recorded for the agent's connection") @@ -326,6 +328,41 @@ func TestQueuedStreamKeptAliveOnceSentToItsVendor(t *testing.T) { } } +// heldSlot is a request holding a provider's one slot (MaxConcurrency 1) +// at a vendor whose first request waits on its block. +type heldSlot struct { + once sync.Once + v *streamVendor + err chan error +} + +// free lets the holder's vendor answer, which frees the slot; once. +func (h *heldSlot) free() { h.once.Do(func() { close(h.v.block) }) } + +// done waits for the holder's own reply. +func (h *heldSlot) done(t *testing.T) { + t.Helper() + if err := <-h.err; err != nil { + t.Fatal(err) + } +} + +// holdSlot sends a request that takes the slot and keeps it until free; it +// is freed after 5s if nothing frees it, so a queued agent that hears +// nothing fails its test rather than hanging it. +func holdSlot(t *testing.T, gw string, v *streamVendor, path, body string) *heldSlot { + t.Helper() + h := &heldSlot{v: v, err: make(chan error, 1)} + go func() { + _, _, _, err := askHeard(gw, path, body, nil) + h.err <- err + }() + waitSeen(t, v, 1) // the first has the slot + stop := time.AfterFunc(5*time.Second, h.free) + t.Cleanup(func() { stop.Stop(); h.free() }) + return h +} + // A slot of MaxConcurrency waited for is kept alive the same way. func TestQueuedStreamKeptAliveForASlot(t *testing.T) { one := 1 @@ -357,7 +394,11 @@ func TestQueuedStreamKeptAliveForASlot(t *testing.T) { // Once a queued request's agent has the stream's 200, the vendor failing // after it reaches the agent as its stream's error event, in its // protocol's own shape, not as a status the agent can no longer be told, -// nor a JSON error body inside the stream. +// nor a JSON error body inside the stream. The request waits for a slot +// (MaxConcurrency), freed once its agent has heard a keepalive: a wait for +// room in the minute goes through the same keepQueued and handoff, but +// there each of the vendor's retries waited a minute more, nine seconds a +// protocol (#1654). func TestQueuedStreamFailureIsTheStreamsError(t *testing.T) { wants := map[string][]string{ "chat": {`"error"`, "the vendor is overloaded"}, @@ -366,15 +407,18 @@ func TestQueuedStreamFailureIsTheStreamsError(t *testing.T) { } for _, a := range queueAsks { t.Run(a.name, func(t *testing.T) { - shortMinute(t, queueMinute, time.Minute) - gw := queueGateway(t, &streamVendor{fail: 10}, func(p *provider.Provider) { p.MaxRPM = 1 }) - if code, body, _, err := askHeard(gw, a.path, a.body, nil); err != nil || code != 200 { - t.Fatalf("first: %d %v %s", code, err, body) - } - code, body, _, err := askHeard(gw, a.path, a.body, nil) + one := 1 + v := &streamVendor{fail: 10, block: make(chan struct{})} + gw := queueGateway(t, v, func(p *provider.Provider) { p.MaxConcurrency = &one }) + first := holdSlot(t, gw, v, a.path, a.body) + code, body, _, err := askHeard(gw, a.path, a.body, first.free) if err != nil || code != 200 || !strings.Contains(body, ": keepalive") { t.Fatalf("queued = %d %v %q, want the stream's 200 and keepalives", code, err, body) } + first.done(t) + if _, ok := v.arrived(1); !ok { + t.Fatal("the queued request never reached the vendor") + } for _, w := range wants[a.name] { if !strings.Contains(body, w) { t.Fatalf("stream %q doesn't say %s", body, w) diff --git a/internal/usage/otel.go b/internal/usage/otel.go index e9e19e29d..c962ded1d 100644 --- a/internal/usage/otel.go +++ b/internal/usage/otel.go @@ -54,6 +54,12 @@ type otelExporter struct { identities sessions.TraceSessionIndex } +// OTelEvery is how often the exporter sends what it holds, and +// OTelSessionsEvery how often it reads the agents' transcripts for +// sessions. Read once when StartOTel starts an exporter; tests shorten them +// so a test that waits for an export doesn't wait seconds. +var OTelEvery, OTelSessionsEvery = 5 * time.Second, 2 * time.Second + // StartOTel runs only in the process serving the gateway. Stopping drains // accepted metadata for at most three seconds, after in-flight calls finish. func StartOTel() func() { @@ -63,8 +69,8 @@ func StartOTel() func() { log.Printf("otel: %s", err) } watchCtx, stopWatch := context.WithCancel(e.ctx) - go e.watchSessions(watchCtx, time.Now()) - go e.run() + go e.watchSessions(watchCtx, time.Now(), OTelSessionsEvery) + go e.run(OTelEvery) var once sync.Once return func() { once.Do(func() { @@ -179,11 +185,11 @@ func (e *otelExporter) offer(item otelItem) { } } -func (e *otelExporter) run() { +func (e *otelExporter) run(every time.Duration) { defer close(e.done) defer e.cancel() defer e.client.CloseIdleConnections() - ticker := time.NewTicker(5 * time.Second) + ticker := time.NewTicker(every) defer ticker.Stop() batch := make([]otelItem, 0, otelBatchSize) flush := func() { diff --git a/internal/usage/otel_sessions.go b/internal/usage/otel_sessions.go index a951d3e87..cb0b61447 100644 --- a/internal/usage/otel_sessions.go +++ b/internal/usage/otel_sessions.go @@ -106,8 +106,8 @@ func (e *otelExporter) offerSession(s sessions.TraceSpan, config settings.OTel) } } -func (e *otelExporter) watchSessions(ctx context.Context, started time.Time) { - ticker := time.NewTicker(2 * time.Second) +func (e *otelExporter) watchSessions(ctx context.Context, started time.Time, every time.Duration) { + ticker := time.NewTicker(every) defer ticker.Stop() var reader *sessions.TraceReader var prior settings.OTel