Files
magpie/internal/gateway/codex_compact_late_test.go
T
yetone 9a51d644d6 gateway: a compaction's summary late past 4 minutes is magpie's own, sent before Codex gives up (#5275)
hayden4608 on Discord (#5275, asked as urgent): Codex Desktop compacting a
~108k-token conversation on volcengine/deepseek-v4.1-flash. The ~3.1MB
summary request was still being written to Ark at 299s (TryNet Send
~299s, no first byte), Codex gave up at 300s (499), and only then did
magpie log "the reply ended before it was complete; compacting locally".
That local summary went to a request nobody was reading, and
compactFails.done cleared the conversation's count as if it had worked.
Codex sent the same history again, three times, 300s each, and the
conversation never got shorter.

- codexCompact gives the summary compactWithin (4 minutes, a minute
  short of Codex's 300s stream idle timeout, as agentQuietMost). Past it
  the vendor is no longer waited on (the ask's context ends with a
  sideTimedOut cause, so the usage log says "magpie stopped waiting: its
  compaction summary had no answer in 4m0s", not the agent canceling),
  and magpie's own summary (localSummary, saying "no summary came in
  4m0s") goes to Codex while it still waits. Checked after the first
  ask, the ask as plain text, and the as-text ask after tool calls, so
  a late first ask is never followed by another ask of the same body.
- A compaction Codex left before it was answered is counted a failure
  (499, "Codex left before the summary reached it") and nothing is
  written; done() is no longer called for it. After compactFailsMost in
  a row, the next is held with a 400 at once instead of another 300s.

Why the upload was slow: not shown to be magpie's. From here a 3.1MB
whitespace-padded chat request to ark.cn-beijing.volces.com/api/v3 was
read whole in ~1.5s by curl over HTTP/2 and HTTP/1.1, and Go's client
with vendorTransport's settings (HTTP/2, ping health) wrote it in 0.89s
(HTTP/1.1 0.17s) from mote. The reporter's ~10KB/s, and their own 4MiB
control not finishing in 40s by any route, point at the uplink or the
Shadowrocket TUN in their path. Not tried through a TUN.

Run (mote): TestCodexCompactLateSummaryCompactsLocallyInTime and
TestCodexCompactLeftBeforeAnsweredStillCounts green with the fix;
both red on the old code (the first: no answer before the client's 10s; the
second: a completed compaction written to a Codex that left, and the next
not held). go test -run Compact ./internal/gateway ok; go vet of
internal/gateway for darwin, linux and windows ok; gofmt clean.
Full suite: run after the push (go test -timeout 45m ./... on mote, log
teed), result on #5275.

Not tried: a real Codex Desktop session against a slow uplink; a
reporter-side stream_idle_timeout_ms shorter than 4 minutes (then Codex
still leaves first, and the count holds the conversation after 3).
2026-11-05 01:26:12 +08:00

130 lines
4.5 KiB
Go

package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// #5275 (hayden4608): Codex Desktop compacting on a Volcengine model, its
// ~3MB history still going up a slow uplink when Codex gave up at 300s.
// magpie made its own summary only after that, for nobody, and counted
// the compaction a success; Codex sent the same history again, another
// 300s, and the conversation never got shorter.
// silentUpstream is a provider whose vendor never answers: each request
// is held until it is given up on, as one whose body is still going up.
func silentUpstream(t *testing.T) (asked chan struct{}) {
t.Helper()
noRests()
t.Cleanup(noRests)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
asked = make(chan struct{}, 16)
release := make(chan struct{})
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
asked <- struct{}{}
select {
case <-r.Context().Done():
case <-release:
}
}))
t.Cleanup(func() {
close(release)
up.Close()
})
p := provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.URL + "/v1"}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
return asked
}
func withCompactWithin(t *testing.T, d time.Duration) {
t.Helper()
was := compactWithin
compactWithin = d
t.Cleanup(func() { compactWithin = was })
}
// A summary that hasn't come by compactWithin is magpie's own, sent while
// Codex still waits: the compaction completes, saying why, and the vendor
// is no longer waited on.
func TestCodexCompactLateSummaryCompactsLocallyInTime(t *testing.T) {
asked := silentUpstream(t)
withCompactWithin(t, 300*time.Millisecond)
// Codex's patience, far past compactWithin here as 300s is past 4m
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-late"))).WithContext(ctx)
req.Header.Set("Authorization", "Bearer chatgpt-token")
began := time.Now()
New().Handler().ServeHTTP(rec, req)
if ctx.Err() != nil {
t.Fatalf("Codex gave up first, after %s: %d %s", time.Since(began), rec.Code, rec.Body)
}
select {
case <-asked:
default:
t.Fatal("the vendor was never asked")
}
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
sum := compactedText(t, rec.Body.String())
for _, want := range []string{"no summary came in 300ms", "fix the login bug", "now add a test"} {
if !strings.Contains(sum, want) {
t.Errorf("summary %q, want it to say %q", sum, want)
}
}
}
// A compaction Codex left before it was answered is no success: what was
// made reached nobody, so the conversation's failures still count and its
// compaction is held after compactFailsMost of them, rather than cleared
// for the next to wait as long again.
func TestCodexCompactLeftBeforeAnsweredStillCounts(t *testing.T) {
asked := silentUpstream(t)
withCompactWithin(t, time.Minute)
s := New()
key := compactKey([]byte(codexCompactOf("fake/m1", "thread-left")))
for range compactFailsMost - 1 {
s.compactFails.failed(key, 502, "the reply ended before it was complete")
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-asked
cancel() // Codex gives up while the vendor says nothing
}()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-left"))).WithContext(ctx)
req.Header.Set("Authorization", "Bearer chatgpt-token")
s.Handler().ServeHTTP(rec, req)
if strings.Contains(rec.Body.String(), "response.completed") {
t.Errorf("a compaction written to a Codex that left: %s", rec.Body)
}
// held, it is answered at once; asked, the vendor would hold it
actx, acancel := context.WithTimeout(context.Background(), 5*time.Second)
defer acancel()
again := httptest.NewRecorder()
areq := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(codexCompactOf("fake/m1", "thread-left"))).WithContext(actx)
areq.Header.Set("Authorization", "Bearer chatgpt-token")
s.Handler().ServeHTTP(again, areq)
if again.Code != 400 || !strings.Contains(again.Body.String(), "times in a row") {
t.Fatalf("after Codex left a third time: %d %s", again.Code, again.Body)
}
select {
case <-asked:
t.Error("the vendor was asked again while the conversation is held")
default:
}
}