The test reads the heap once the upstream has written each request's first chunk: got is sent from its handler right after the Flush. The gateway lets the body it sent go when forwardOnce returns (#3383), after the transport has read that reply off the connection and p.Do has returned it, so the heap can be read while a request still holds what it sent, and only the two GCs before the read give it time. A scratch copy of the test, on23cec6c4, counted the requests whose first text had reached their agent when the wait ended: -count=30 at -cpu 1, 2, 4 and 8, it was 8 of 8 in none of the 120 runs (7 in 85, down to 1), and the held ratio ran from 1.74 to 2.87 against the bar of 3. In my full suite at 6b556f5a (go test ./..., internal/gateway 441 s beside the other packages) it went over: streaming_heap_test.go:96: 8 streaming requests of 4 MB hold 121 MB, 3.1 times the body each The test now waits for each request's first text at the agent's end of its pipe (firstText): the gateway streams it from the reply forwardOnce returned, so that request's LetGo has run. What the heap is read for, and the bar, are unchanged. What was run (this commit on 23cec6c4; go1.26.8, -tags nogui): the same count with this wait, -count=30 at -cpu 1, 2, 4 and 8: 8 of 8 in 120 of 120, the ratio 2.09 to 2.19 the answers made to reach forwardOnce late, a 300 ms pause after p.Do (scratch, not in this commit): all 8, -count=10: the old test red 10 of 10, "3.7 times" to "4.0 times the body each"; this one ok the first 3, six runs: the old test red in one, "8 streaming requests of 4 MB hold 122 MB, 3.1 times the body each"; this one ok in six. The first 1 or 2: both ok six times, the old test's ratio up to 2.73 LetGo taken out of forwardOnce, -count=10: red 10 of 10, "8 streaming requests of 4 MB hold 152 MB, 3.9 times the body each" -race -count=20: ok; -cpu 1,2,4 -count=20: ok gofmt -l internal/gateway: nothing; GOOS=linux, darwin, windows go vet -tags nogui ./internal/gateway: exit 0 full suite, go test -tags nogui -count=1 -timeout 45m ./... at this commit: 63 packages ok; internal/gateway ran 445 s, this test ok in it. 7 packages red, each of this machine and named before (#3480's d970371e): #3141's lookup tick (TestInstalledVersion, TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestQoderSettingsFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir, TestZedAppPath); Reasonix's two (a /tmp/.git that isn't this user's); every connection proxied, even to this machine's own non-loopback addresses (TestCallbackGoesPastTheAgentsProxy, TestClaudeToolCallbackOnANonLoopbackAddress, TestGatewayFixQuitsOnlyAMagpie, TestGatewayHeldByAContainer); umask 077 (TestWriteAtomicReadOnlyHardLink, testenv's TestProgram); Bun 1.3.11 (TestBunProxyLoginWithReservedCharacters, #3397) Not tried: macOS, Windows, CI's runners. Landed by yetone in a batch of Coffemon's patches from the issues. What was run, go1.26.8, on origin/maincc81ad4ea, then again at70a0c387c(gofmt, the three vets, the changed tests, umask 077): - mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask 077; agent, provider, library and gateway with an empty .git above TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the changed tests in agent, provider, gateway and gui; the timing tests -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok. TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js 1,312,975 of 1,315,316, no budget raised. - Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink at umask 077 and two Reasonix tests under an empty .git; on Linux (wsl-run) TestProgram at umask 077 with the old program.go. With each fix's code taken back to main's, the Gemini imageConfig tests, TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced, TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto, plugin-github-hooks, plugins-more-discover, plugin-namesake were red. Broken by hand: claudeKeyed always true (both OwnEndpointNeverAsked tests red), claudeAsk a no-op (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder (the three TestGitOnDisk tests red). - GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n, gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on Linux (wsl-run). 11 files had reds (click-scroll, panel-fold, plugin-card-update, plugin-github, plugin-move*, segs-glide, tray-totals, update-*), and run again side by side they fail the same on origin/maind80d75f30(79 pass, 26 fail here; 78 and 27 there). They are click-scroll guards ("the click must not scroll the page"), varying by language from run to run (#4385). copilot-ghe's route-after-close red is #1949, seen on main244d80e23too. In Chromium on mote, Chromium segfaulted partway through files (#4125): context-map, context-scroll-end and context-tune fail the same on origin/main0911a65e7, so the batch's own files (plugin-namesake, update-auto, plugins-more-discover, plugin-github-hooks) ran in Chromium on Linux: 62 of 62. - Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote) at 472a0608f (on70a0c387c): every package ok but internal/gateway, whose five reds were #4362's (Antigravity turned-away and TestCodexSpentGrokFailingIsTold), fixed on main ind80d75f30. After the rebase on244d80e23the five pass, and gofmt, the three vets and the targeted runs above were run again: ok. In Linux the sign-in, copilot, plugin-github*, plugins-more-discover, plugin-namesake, plugin-gateway, update-auto, quota-refresh-order and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe #1949, plugin-github's click scroll, both red on main too). - Rebased again onc7171a256, over its budget fixe94bf7a08: gofmt, vet of gui, gateway, provider and plugin, TestCoreScriptBudget (core 1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini, GitOnDisk and plugin tests, and in Linux both engines i18n-keys, update-mirror, plugin-namesake, plugins-more-discover, plugin-github-hooks and update-auto (138 of 138): ok. Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its Chromium segfaulted, #4125); macOS WebKit; the real app's window.
123 lines
3.9 KiB
Go
123 lines
3.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// streamingHold is a ResponseWriter that passes a reply on as it comes.
|
|
type streamingHold struct {
|
|
h http.Header
|
|
w io.Writer
|
|
}
|
|
|
|
func (s *streamingHold) Header() http.Header { return s.h }
|
|
func (s *streamingHold) Write(b []byte) (int, error) { return s.w.Write(b) }
|
|
func (s *streamingHold) WriteHeader(int) {}
|
|
func (s *streamingHold) Flush() {}
|
|
|
|
// Requests streaming at once each hold what their retries and
|
|
// continuations read, not the body that went upstream: that was held by
|
|
// the transport until the stream ended, and eight Claude Code requests
|
|
// of 4.7 MB translated to Chat held 152 MB mid-stream, 88 MB once it
|
|
// goes when it is answered (#3383). The heap is read once every
|
|
// request's first text has reached its agent: the upstream has written
|
|
// it before the gateway has the answer, and a request not answered yet
|
|
// still holds what it sent.
|
|
func TestStreamingRequestsLetTheirSentBodyGo(t *testing.T) {
|
|
fresh(t)
|
|
const n = 8
|
|
answered := make(chan struct{}, n)
|
|
release := make(chan struct{})
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
io.Copy(io.Discard, r.Body)
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"}}]}`+"\n\n")
|
|
w.(http.Flusher).Flush()
|
|
<-release
|
|
io.WriteString(w, `data: {"id":"c","object":"chat.completion.chunk","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":5}}`+"\n\ndata: [DONE]\n\n")
|
|
}))
|
|
t.Cleanup(up.Close)
|
|
if err := provider.Save(provider.Provider{ID: "up", Name: "Up", Key: "k", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := New()
|
|
var sb strings.Builder
|
|
sb.WriteString(`{"model":"up/m1","max_tokens":100,"stream":true,"messages":[`)
|
|
turn := strings.Repeat("<div>a & b</div> some text here ", 2000)
|
|
for i := 0; i < 80; i++ {
|
|
if i > 0 {
|
|
sb.WriteString(",")
|
|
}
|
|
role := "user"
|
|
if i%2 == 1 {
|
|
role = "assistant"
|
|
}
|
|
fmt.Fprintf(&sb, `{"role":%q,"content":%q}`, role, turn)
|
|
}
|
|
sb.WriteString(`]}`)
|
|
body := sb.String()
|
|
h := s.Handler()
|
|
var ms runtime.MemStats
|
|
runtime.GC()
|
|
runtime.ReadMemStats(&ms)
|
|
before := ms.HeapAlloc
|
|
var wg sync.WaitGroup
|
|
defer wg.Wait()
|
|
once := sync.OnceFunc(func() { close(release) })
|
|
defer once()
|
|
for i := 0; i < n; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
pr, pw := io.Pipe()
|
|
go firstText(t, pr, answered)
|
|
h.ServeHTTP(&streamingHold{h: http.Header{}, w: pw}, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
|
|
pw.Close()
|
|
}()
|
|
}
|
|
for i := 0; i < n; i++ {
|
|
<-answered
|
|
}
|
|
runtime.GC()
|
|
runtime.GC()
|
|
runtime.ReadMemStats(&ms)
|
|
held := int64(ms.HeapAlloc) - int64(before)
|
|
once()
|
|
// the body as it came, for another member, and as read, for a
|
|
// continuation: about twice the body each, the sent one 4 times
|
|
if each := held / n; each > 3*int64(len(body)) {
|
|
t.Errorf("%d streaming requests of %d MB hold %d MB, %.1f times the body each", n, len(body)>>20, held>>20, float64(each)/float64(len(body)))
|
|
}
|
|
}
|
|
|
|
// firstText reads a stream as its agent does and says on answered when
|
|
// the reply's first text has come, the gateway's answer from the
|
|
// upstream with it; then it reads the rest.
|
|
func firstText(t *testing.T, r io.Reader, answered chan<- struct{}) {
|
|
var seen []byte
|
|
buf := make([]byte, 4096)
|
|
for {
|
|
k, err := r.Read(buf)
|
|
seen = append(seen, buf[:k]...)
|
|
if bytes.Contains(seen, []byte(`"text":"hi"`)) {
|
|
break
|
|
}
|
|
if err != nil {
|
|
t.Errorf("the stream ended before its first text: %q", seen)
|
|
break
|
|
}
|
|
}
|
|
answered <- struct{}{}
|
|
io.Copy(io.Discard, r)
|
|
}
|