diff --git a/internal/gateway/keepalive_test.go b/internal/gateway/keepalive_test.go index d37963354..4d6bce772 100644 --- a/internal/gateway/keepalive_test.go +++ b/internal/gateway/keepalive_test.go @@ -31,7 +31,7 @@ func keepFast(t *testing.T, gap, every, longest time.Duration) { func TestTranslatedStreamKeepsClientAlive(t *testing.T) { keepFast(t, 10*time.Millisecond, keepaliveEvery, keepaliveLongest) for _, c := range []struct { - name, path, body, done, ping string + name, path, body, done, ping string // done: the reply's last event upChat bool comments bool // the client counts a comment as life }{ @@ -40,7 +40,7 @@ func TestTranslatedStreamKeepsClientAlive(t *testing.T) { {"chat_to_anthropic", "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`, `"type":"message_stop"`, `"type":"ping"`, true, false}, {"responses_to_chat", "/v1/chat/completions", `{"model":"fake/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`, - `"finish_reason":"stop"`, ": keepalive", false, true}, + "data: [DONE]", ": keepalive", false, true}, } { t.Run(c.name, func(t *testing.T) { fresh(t) @@ -112,7 +112,16 @@ func TestTranslatedStreamKeepsClientAlive(t *testing.T) { }() idle := time.NewTimer(150 * time.Millisecond) defer idle.Stop() - timedOut, completed, pings := false, false, 0 + // the client's idle timeout, until it has the whole reply. What + // the gateway does after that before the stream closes (the + // usage ledger, affinity, served) is no wait a client's idle + // timeout counts: Codex hangs up on response.completed, and the + // clients that read on to the close wait minutes, not 150ms. + // Then the stream closes within closeAfterLast, or the test + // fails rather than hangs. + const closeAfterLast = 5 * time.Second + wait := idle.C + timedOut, completed, unclosed, pings := false, false, false, 0 // openai-go v2 (Crush) reads every blank line as an event and // fails on one with no data: "unexpected end of JSON input" data, empty := false, 0 @@ -134,19 +143,22 @@ func TestTranslatedStreamKeepsClientAlive(t *testing.T) { } else if strings.HasPrefix(line, "data:") { data = true } - if strings.Contains(line, c.done) { - completed = true + if strings.Contains(line, c.done) && !completed { + completed, wait = true, time.After(closeAfterLast) } // what the client's idle timeout counts if strings.HasPrefix(line, "data:") || (c.comments && strings.HasPrefix(line, ":")) { idle.Reset(150 * time.Millisecond) } - case <-idle.C: - timedOut = true + case <-wait: + timedOut, unclosed = !completed, completed break read } } cancel() + if unclosed { + t.Fatalf("the stream didn't close within %v of its last event", closeAfterLast) + } t.Logf("upstream_keepalives=%d downstream_keepalives=%d idle_timeout=%v completed=%v", upPings.Load(), pings, timedOut, completed) if timedOut || !completed || pings < 3 { t.Fatal("the client wasn't kept alive while the provider was") diff --git a/internal/gateway/quiet_keepalive_test.go b/internal/gateway/quiet_keepalive_test.go index 891173604..ef274f116 100644 --- a/internal/gateway/quiet_keepalive_test.go +++ b/internal/gateway/quiet_keepalive_test.go @@ -65,6 +65,13 @@ func quietOn(t *testing.T, id, before, after string, heard <-chan struct{}) *ato // closing heard at the first keepalive, and tells how long its headers // took. func askChat(t *testing.T, s *Server, model string, heard chan struct{}) (int, string, time.Duration) { + t.Helper() + return askChatAfter(t, s, model, heard, "") +} + +// askChatAfter is askChat closing heard at the first keepalive after after +// (readQuiet). +func askChatAfter(t *testing.T, s *Server, model string, heard chan struct{}, after string) (int, string, time.Duration) { t.Helper() gw := httptest.NewServer(s.Handler()) t.Cleanup(gw.Close) @@ -76,20 +83,42 @@ func askChat(t *testing.T, s *Server, model string, heard chan struct{}) (int, s } headers := time.Since(began) defer resp.Body.Close() + return resp.StatusCode, readQuiet(resp.Body, heard, after), headers +} + +// readQuiet reads a stream to its end, closing heard at its first +// keepalive once after has come in it. A keepalive may come before the +// vendor's first words as well, the vendor slow to send them, or the try +// slow to read them, with the stream held and nothing of it sent: that is +// the held stream's (TestSilentHeldStreamKeptAlive), and says nothing of a +// quiet after them. +func readQuiet(r io.Reader, heard chan struct{}, after string) string { var once sync.Once var body strings.Builder - rd := bufio.NewReader(resp.Body) + rd := bufio.NewReader(r) for { line, err := rd.ReadString('\n') body.WriteString(line) - if strings.HasPrefix(line, ": keepalive") { + if strings.HasPrefix(line, ": keepalive") && strings.Contains(body.String(), after) { once.Do(func() { close(heard) }) } if err != nil { - break + return body.String() } } - return resp.StatusCode, body.String(), headers +} + +// aliveAfter is where body's first keepalive after after is, or -1. +func aliveAfter(body, after string) int { + i := strings.Index(body, after) + if i < 0 { + return -1 + } + j := strings.Index(body[i:], ": keepalive") + if j < 0 { + return -1 + } + return i + j } // A vendor that sent its 200 and response.created, then nothing while it @@ -116,15 +145,16 @@ func TestSilentHeldStreamKeptAlive(t *testing.T) { // One quiet mid-reply, its first words sent: a translated reply's client // was kept alive only as its vendor sent something, so a vendor that said // nothing at all left it to the proxy's timeout, which reset the stream -// (#947, "INTERNAL_ERROR; received from peer"). +// (#947, "INTERNAL_ERROR; received from peer"). The keepalive this is +// about is the one after them (readQuiet). func TestQuietStreamMidReplyKeptAlive(t *testing.T) { fresh(t) quietFast(t) heard := make(chan struct{}) timedOut := quietOn(t, "fixture", quietCreated+quietDelta("hel"), quietDelta("lo")+quietDone, heard) - code, body, _ := askChat(t, New(), "fixture/gpt-test", heard) - alive := strings.Index(body, ": keepalive") - if timedOut.Load() || code != 200 || alive < 0 || !strings.Contains(body[:alive], "hel") || !strings.Contains(body[alive:], `"lo"`) || !strings.Contains(body, "[DONE]") { + code, body, _ := askChatAfter(t, New(), "fixture/gpt-test", heard, "hel") + alive := aliveAfter(body, "hel") + if timedOut.Load() || code != 200 || alive < 0 || !strings.Contains(body[alive:], `"lo"`) || !strings.Contains(body, "[DONE]") { t.Fatalf("timed out %v: %d %q", timedOut.Load(), code, body) } } @@ -171,8 +201,15 @@ func TestQuietKeptAliveOnlySoLong(t *testing.T) { } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) // the vendor goes on after 3s - if n := strings.Count(string(b), ": keepalive"); n == 0 || n > 8 { - t.Fatalf("%d keepalives in 3s, kept for 200ms: %q", n, b) + // counted from its first words, as readQuiet: the held stream's before + // them are kept for 200ms of their own + body := string(b) + i, j := strings.Index(body, "hel"), strings.Index(body, `"lo"`) + if i < 0 || j < i { + t.Fatalf("%q", body) + } + if n := strings.Count(body[i:j], ": keepalive"); n == 0 || n > 8 { + t.Fatalf("%d keepalives in 3s, kept for 200ms: %q", n, body) } } @@ -211,8 +248,10 @@ func TestQuietStreamsKeptAliveEveryProtocol(t *testing.T) { quietFast(t) heard := make(chan struct{}) before, after := c.start(""), c.text("lo")+c.end("") + said := "" // what the agent has before the quiet if mid { before += c.text("hel") + said = "hel" } var timedOut atomic.Bool up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -249,22 +288,9 @@ func TestQuietStreamsKeptAliveEveryProtocol(t *testing.T) { t.Fatal(err) } defer resp.Body.Close() - var once sync.Once - var body strings.Builder - rd := bufio.NewReader(resp.Body) - for { - line, err := rd.ReadString('\n') - body.WriteString(line) - if strings.HasPrefix(line, ": keepalive") { - once.Do(func() { close(heard) }) - } - if err != nil { - break - } - } - b := body.String() - alive := strings.Index(b, ": keepalive") - if timedOut.Load() || resp.StatusCode != 200 || alive < 0 || !strings.Contains(b[alive:], "lo") || mid && !strings.Contains(b[:alive], "hel") { + b := readQuiet(resp.Body, heard, said) + alive := aliveAfter(b, said) + if timedOut.Load() || resp.StatusCode != 200 || alive < 0 || !strings.Contains(b[alive:], `"lo"`) { t.Fatalf("timed out %v: %d %q", timedOut.Load(), resp.StatusCode, b) } }) diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index feed0a0aa..469444386 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -3,6 +3,12 @@ // built-in's plugin does. const ID = process.env.FAKE_ID || "fakeco" +// born is when the host loaded the plugin. The accounts' windows renew at +// times set from it, as a vendor's are: read again, an account renews when +// it did, so two accounts read either side of an hour aren't an hour apart +// to Smart routing, which weighs renewals to the hour. +const born = Date.now() + // fakeWho is who a team signs in as: team@fake, and a team named name/uid // is name@fake with that uid, as WorkBuddy's plugin keeps one function fakeWho(team) { @@ -165,8 +171,8 @@ export const FakePlugin = async ({ client }) => ({ renew: "auto", resets: full ? { count: 3, byWindow: true, fiveHour: 2, weekly: 1 } : undefined, windows: [ - { name: "5 hours", used: full ? 100 : 25, resetsAt: Date.now() + 3600e3, span: 5 * 3600, models: ["fake-claude"] }, - { name: "Week", used: 10, resetsAt: Math.floor(Date.now() / 1000) + 86400, span: 7 * 86400, amount: 120, limit: 1200, unit: "credits" }, + { name: "5 hours", used: full ? 100 : 25, resetsAt: born + 3600e3, span: 5 * 3600, models: ["fake-claude"] }, + { name: "Week", used: 10, resetsAt: Math.floor(born / 1000) + 86400, span: 7 * 86400, amount: 120, limit: 1200, unit: "credits" }, { name: "Extra", used: 250, display: "$2.50", aside: true }, ], } diff --git a/internal/provider/plugin_usage_test.go b/internal/provider/plugin_usage_test.go index 59953246e..abcc45ffd 100644 --- a/internal/provider/plugin_usage_test.go +++ b/internal/provider/plugin_usage_test.go @@ -47,6 +47,7 @@ func TestPluginUsage(t *testing.T) { t.Fatal(err) } + var first []QuotaWindow // a@fake's, as first read for _, agent := range []string{"fakeco", "plugin:fakeco"} { u := LoginUsage(ctx, agent) if len(u) != 3 { @@ -77,6 +78,9 @@ func TestPluginUsage(t *testing.T) { if e := u["API key"].Error; e != "an API key has no plan" { t.Fatalf("%s: the key's usage error = %q (%v)", agent, e, u) } + if first == nil { + first = q.Windows + } } cards := 0 @@ -92,11 +96,21 @@ func TestPluginUsage(t *testing.T) { t.Fatalf("%d usage cards for the plugin's accounts, want 3", cards) } // one account's card read again from its refresh button (#840): that - // account's alone is asked + // account's alone is asked. Read a moment later (the five hours' renewal + // is told to the millisecond), its windows renew when they did, as a + // vendor's do: TestPluginFailover's routing weighs accounts read at + // different times by when they renew. + time.Sleep(2 * time.Millisecond) again := context.WithValue(context.Background(), cardRefreshKey{}, cardRefresh{"fakeco", "A@fake"}) - if qs := fetchSubscriptionUsage(again); len(qs) != 1 || qs[0].User != "a@fake" || qs[0].Error != "" { + qs := fetchSubscriptionUsage(again) + if len(qs) != 1 || qs[0].User != "a@fake" || qs[0].Error != "" || len(qs[0].Windows) != len(first) { t.Fatalf("a@fake read again: %+v", qs) } + for i, w := range qs[0].Windows { + if a, b := w.ResetsAt, first[i].ResetsAt; (a == nil) != (b == nil) || a != nil && !a.Equal(*b) { + t.Errorf("a@fake's %s renews at %v read again, at %v first", w.Name, a, b) + } + } // a model the plugin says the plan serves at no cost shows as free, // as WorkBuddy's built-in marked its x0.00 models