gateway: a held request's report says where the request itself stood
wilsonxuuuu on X (0.1.4178, Codex to cloud/auto/gpt-6.1-sol, a remote magpie's auto group): requests held 30s "in no wait magpie knows of" and stopped with 504 all day. The report he pasted was cut before its goroutine dump, so nothing said which step held the request. watchUnrouted now keeps the handler's goroutine id (about 10us a request at a 40-frame stack). On give-up, heldOwn finds that goroutine in a dump of every goroutine and strips the argument words and pc offsets. The report then puts "stood at: <first of magpie's own functions> (<what it waited in>)" next to the known waits. It also puts the request's own stack under "where this request stood", ahead of every goroutine's. The log line says it as "standing at". Not found: the block itself. A fake remote that hangs or answers slowly, 49 cloud/ requests in flight, and 400 Codex requests with 200KB bodies against concurrent settings and provider writes all routed. The local magpie asks the remote nothing before routing a cloud/ model. The next report will name the step. Run: - TestHeldReportSaysWhereItStood (a fake slow remote magpie, Codex /backend-api/codex/responses for cloud/auto/gpt-6.1-sol, a lock that routing needs held) is red on the old code: `stood at: ""`. - TestHeldOfFindsItsGoroutine checks that heldOf finds the goroutine by its id and strips the values. - gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows ./... ok (mote). - Full suite `go test -count=1 -timeout 45m ./...` on mote at 7c405dac7 (this change oncd030691a): internal/gateway ok (1023s); every package ok except two reds already on main, outside this change: - TestNoEagerPackageRegexps: chatpage.go, #6689. - TestEveryRouteHasACommandOrIsNamed: providers/delete, fixed in4c86b0ab4, which this commit is now rebased onto.
This commit is contained in:
@@ -536,14 +536,22 @@ recorded as a prediction failure (`noPrediction`).
|
||||
the newest `heldKept` (5) kept. It has the time, version and system,
|
||||
method and path, the model and agent, how long it was held, each kind
|
||||
of known wait and its time ("(under way)" for the one it was in), the
|
||||
body room's state, the requests in flight and every goroutine's stack
|
||||
(function names and lines, no values; 128 KB at most, one dump for a
|
||||
burst within 10s). Never the body or headers. Its file name is
|
||||
body room's state, the requests in flight, where the request itself
|
||||
stood (`stood at:`, the first of magpie's own functions on its
|
||||
handler's stack and what it waited in, and that stack in full under
|
||||
"where this request stood", ahead of the rest: `watchUnrouted` keeps
|
||||
the handler's goroutine id, `heldOwn` finds it in a dump of every
|
||||
goroutine and strips the argument words and pc offsets; the log line
|
||||
says it as "standing at", wilsonxuuuu on X: a report pasted cut before
|
||||
the stacks said 30s in no known wait and nothing more) and every
|
||||
goroutine's stack (function names and lines, no values; 128 KB at
|
||||
most, one dump for a burst within 10s). Never the body or headers. Its file name is
|
||||
`Route.Held`; the Routing page's story of that request has Copy Report
|
||||
(`GET /api/gateway/held/{name}`, only a report's own name is read) and,
|
||||
in the app, Open Folder (`POST /api/gateway/held/reveal`). The 504 and
|
||||
the log line say where it is. `TestUnroutedHeldReportSaved`,
|
||||
`TestHeldReportsKeptAndNamed`, `routing-held-report.test.cjs`.
|
||||
`TestHeldReportsKeptAndNamed`, `TestHeldReportSaysWhereItStood`,
|
||||
`TestHeldOfFindsItsGoroutine`, `routing-held-report.test.cjs`.
|
||||
`TestUnroutedRequestShownThenAnswered`, `TestUnroutedShownGivesWayToItsRoute`,
|
||||
`TestUnroutedUnknownHoldAnsweredSooner`, `TestUnroutedSlowBodyNotCutOff`,
|
||||
`TestUnroutedMaskingNotCutOff`, `TestUnroutedSlotWaitNotCutOff`,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// wilsonxuuuu on X: Codex's requests for a remote magpie's auto group
|
||||
// (cloud/auto/gpt-6.1-sol, the remote on 0.1.3295) were held 30s "in no
|
||||
// wait magpie knows of" and stopped, and the report pasted in the tweet
|
||||
// was cut before its goroutines. A request held in a step that is no
|
||||
// named wait (here a lock routing needs, held and never let go) has a
|
||||
// report that says by name where the request itself stood, in its first
|
||||
// lines, with its own stack ahead of every goroutine's, and no values.
|
||||
func TestHeldReportSaysWhereItStood(t *testing.T) {
|
||||
fresh(t)
|
||||
unroutedLimits(t, 20*time.Millisecond, time.Hour)
|
||||
unknownLimit(t, 300*time.Millisecond)
|
||||
// the remote magpie answers slowly, as an old one far off would
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
select {
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
io.WriteString(w, `{"object":"list","data":[{"id":"auto/gpt-6.1-sol","object":"model"}]}`)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"status\":\"completed\",\"output\":[]}}\n\n")
|
||||
}))
|
||||
t.Cleanup(remote.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "cloud", Name: "Remote magpie", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-x",
|
||||
Chat: remote.URL + "/v1", Models: []string{"auto/gpt-6.1-sol"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
srv := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(srv.Close)
|
||||
sticks.Lock()
|
||||
var once sync.Once
|
||||
unlock := func() { once.Do(sticks.Unlock) }
|
||||
t.Cleanup(unlock)
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+CodexPath+"/responses", strings.NewReader(
|
||||
`{"model":"cloud/auto/gpt-6.1-sol","stream":true,"instructions":"be","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("originator", "codex_cli_rs")
|
||||
req.Header.Set("User-Agent", "codex_cli_rs/0.200.0")
|
||||
req.Header.Set("session_id", "sess-held")
|
||||
resp, err := (&http.Client{Timeout: 20 * time.Second}).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
unlock()
|
||||
if resp.StatusCode != http.StatusGatewayTimeout {
|
||||
t.Fatalf("held request answered %d %s", resp.StatusCode, b)
|
||||
}
|
||||
var held string
|
||||
for deadline := time.Now().Add(10 * time.Second); held == ""; time.Sleep(10 * time.Millisecond) {
|
||||
for _, r := range routesOf(s, "cloud/auto/gpt-6.1-sol") {
|
||||
held = cmpOr(held, r.Held)
|
||||
}
|
||||
if held == "" && time.Now().After(deadline) {
|
||||
t.Fatalf("the held request's report was never saved: %+v", routesOf(s, "cloud/auto/gpt-6.1-sol"))
|
||||
}
|
||||
}
|
||||
text, err := HeldReport(held)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head, _, _ := strings.Cut(text, "\nwhere every goroutine stood:")
|
||||
at := ""
|
||||
for _, l := range strings.Split(head, "\n") {
|
||||
if v, ok := strings.CutPrefix(l, "stood at: "); ok {
|
||||
at = v
|
||||
}
|
||||
}
|
||||
// the lock's taker, in the affinity code, and what it waited in
|
||||
if !strings.HasPrefix(at, "gateway.") || !strings.Contains(at, "Mutex") {
|
||||
t.Fatalf("the report doesn't name where the request stood: %q\n%s", at, head)
|
||||
}
|
||||
own, ok := strings.CutPrefix(head[strings.Index(head, "\nwhere this request stood:")+1:], "where this request stood:\n")
|
||||
if !ok || !strings.Contains(own, "internal/gateway/affinity.go:") || !strings.Contains(own, "serveCodexBackend") && !strings.Contains(own, "codexBackend") {
|
||||
t.Fatalf("the report's own stack doesn't show the request's path:\n%s", head)
|
||||
}
|
||||
if strings.Contains(own, "0x") {
|
||||
t.Fatalf("the request's own stack holds values:\n%s", own)
|
||||
}
|
||||
}
|
||||
|
||||
// heldOf finds a goroutine by its id at the dump's start or after a
|
||||
// blank line, never one whose id only begins the same, and strips what
|
||||
// values the runtime writes.
|
||||
func TestHeldOfFindsItsGoroutine(t *testing.T) {
|
||||
dump := "goroutine 12 [running]:\nmain.x(0x1)\n\t/a.go:1 +0x2\n\n" +
|
||||
"goroutine 1 [sync.Mutex.Lock, 2 minutes]:\nsync.(*Mutex).Lock(...)\n\t/go/sync/mutex.go:90\n" +
|
||||
"github.com/yetone/magpie/internal/gateway.(*Server).pick(0xc000123, {0x10, 0x2})\n\t/m/internal/gateway/x.go:7 +0x1c\n" +
|
||||
"created by net/http.(*Server).Serve in goroutine 9\n\t/go/net/http/server.go:3 +0x5\n"
|
||||
got := heldOf(dump, 1)
|
||||
if got.at != "gateway.(*Server).pick (sync.Mutex.Lock, 2 minutes)" {
|
||||
t.Fatalf("at %q", got.at)
|
||||
}
|
||||
if strings.Contains(got.stack, "0x") || !strings.Contains(got.stack, "/m/internal/gateway/x.go:7") || strings.Contains(got.stack, "main.x") {
|
||||
t.Fatalf("stack:\n%s", got.stack)
|
||||
}
|
||||
if heldOf(dump, 2).stack != "" || heldOf(dump, 13).stack != "" {
|
||||
t.Fatal("found a goroutine that isn't in the dump")
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -118,7 +119,7 @@ func HeldReport(name string) (string, error) {
|
||||
}
|
||||
|
||||
// heldReport is the report of u's request, held for held and stopped.
|
||||
func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who, asked, where string) string {
|
||||
func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who, asked, where string, own heldStack) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "magpie held a request before routing it, and stopped it with %d\n\n", status)
|
||||
fmt.Fprintf(&b, "time: %s\n", time.Now().UTC().Format(time.RFC3339))
|
||||
@@ -128,6 +129,9 @@ func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who
|
||||
fmt.Fprintf(&b, "agent: %s\n", who)
|
||||
fmt.Fprintf(&b, "held: %s,%s\n", held, where)
|
||||
fmt.Fprintf(&b, "known waits:%s\n", cmpOr(strings.TrimPrefix(u.waitsSaid(), ";"), " none"))
|
||||
// the step that held it, by name, though it is no wait magpie knows
|
||||
// of: the first of magpie's own functions on its handler's stack
|
||||
fmt.Fprintf(&b, "stood at: %s\n", cmpOr(own.at, "? (its goroutine not found)"))
|
||||
// a slow body from a body that stopped coming: what had come, and
|
||||
// when the last of it did
|
||||
fmt.Fprintf(&b, "body read: %s\n", u.bodySaid())
|
||||
@@ -138,6 +142,9 @@ func (s *Server) heldReport(u *unroutedHold, held time.Duration, status int, who
|
||||
n := len(s.active.m)
|
||||
s.active.mu.Unlock()
|
||||
fmt.Fprintf(&b, "requests in flight: %d\n", n)
|
||||
if own.stack != "" {
|
||||
fmt.Fprintf(&b, "\nwhere this request stood:\n%s\n", own.stack)
|
||||
}
|
||||
fmt.Fprintf(&b, "\nwhere every goroutine stood:\n%s", heldStacks())
|
||||
return b.String()
|
||||
}
|
||||
@@ -191,3 +198,96 @@ func heldStacks() string {
|
||||
heldStacksAt, heldStacksLast = time.Now(), b.String()
|
||||
return heldStacksLast
|
||||
}
|
||||
|
||||
// heldStack is where a held request's handler stood: its stack, with no
|
||||
// values, and at, the first of magpie's own functions on it with what it
|
||||
// waited in ("gateway.(*Server).serveAgent (sync.Mutex.Lock, 2 minutes)").
|
||||
type heldStack struct {
|
||||
stack string
|
||||
at string
|
||||
}
|
||||
|
||||
// heldOwnMost bounds the dump heldOwn looks for one goroutine in.
|
||||
const heldOwnMost = 64 << 20
|
||||
|
||||
// heldModule is magpie's own functions' prefix.
|
||||
const heldModule = "github.com/yetone/magpie/internal/"
|
||||
|
||||
// heldArgs is a frame's argument words, and heldPC its pc offset: values,
|
||||
// which a report never holds.
|
||||
var (
|
||||
heldArgs = lazyre.New(`\([^()]*\)$`)
|
||||
heldPC = lazyre.New(` \+0x[0-9a-f]+$`)
|
||||
)
|
||||
|
||||
// goroutineID is the calling goroutine's id, as its stack names it.
|
||||
func goroutineID() uint64 {
|
||||
var buf [64]byte
|
||||
n := runtime.Stack(buf[:], false)
|
||||
rest, ok := strings.CutPrefix(string(buf[:n]), "goroutine ")
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
id, _, _ := strings.Cut(rest, " ")
|
||||
v, _ := strconv.ParseUint(id, 10, 64)
|
||||
return v
|
||||
}
|
||||
|
||||
// heldOwn is where goroutine gid stands now; zero when it isn't found.
|
||||
func heldOwn(gid uint64) heldStack {
|
||||
if gid == 0 {
|
||||
return heldStack{}
|
||||
}
|
||||
buf := make([]byte, 1<<20)
|
||||
for {
|
||||
n := runtime.Stack(buf, true)
|
||||
if n < len(buf) || len(buf) >= heldOwnMost {
|
||||
buf = buf[:n]
|
||||
break
|
||||
}
|
||||
buf = make([]byte, 2*len(buf))
|
||||
}
|
||||
return heldOf(string(buf), gid)
|
||||
}
|
||||
|
||||
// heldOf is goroutine gid's stack in dump, every goroutine's as
|
||||
// runtime.Stack writes them.
|
||||
func heldOf(dump string, gid uint64) heldStack {
|
||||
head := fmt.Sprintf("goroutine %d [", gid)
|
||||
i := 0
|
||||
if !strings.HasPrefix(dump, head) {
|
||||
j := strings.Index(dump, "\n"+head)
|
||||
if j < 0 {
|
||||
return heldStack{}
|
||||
}
|
||||
i = j + 1
|
||||
}
|
||||
block := dump[i:]
|
||||
if j := strings.Index(block, "\n\n"); j >= 0 {
|
||||
block = block[:j]
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(block, "\n"), "\n")
|
||||
state := ""
|
||||
if l := lines[0]; strings.HasSuffix(l, "]:") {
|
||||
state = l[len(head) : len(l)-2]
|
||||
}
|
||||
var out heldStack
|
||||
for k, l := range lines {
|
||||
switch {
|
||||
case k == 0:
|
||||
case strings.HasPrefix(l, "\t"):
|
||||
l = heldPC.ReplaceAllString(l, "")
|
||||
default:
|
||||
l = heldArgs.ReplaceAllString(l, "")
|
||||
if fn, ok := strings.CutPrefix(l, heldModule); ok && out.at == "" && !strings.HasPrefix(l, "created by ") {
|
||||
out.at = fn
|
||||
if state != "" {
|
||||
out.at += " (" + state + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
lines[k] = l
|
||||
}
|
||||
out.stack = strings.Join(lines, "\n")
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -266,6 +266,11 @@ type unroutedHold struct {
|
||||
mexcused time.Duration
|
||||
mdue bool
|
||||
most *time.Timer
|
||||
// gid is its handler's goroutine, whose own stack the report puts
|
||||
// first (heldOwn): a report cut short, or pasted in part, still says
|
||||
// where the request itself stood (wilsonxuuuu on X: 30s in no wait
|
||||
// magpie knew of, the stacks cut from the tweet)
|
||||
gid uint64
|
||||
}
|
||||
|
||||
type unroutedKey struct{}
|
||||
@@ -614,7 +619,7 @@ func (s *Server) watchUnrouted(w http.ResponseWriter, r *http.Request, f *inflig
|
||||
return w, r, func() {}
|
||||
}
|
||||
ctx, cancel := context.WithCancelCause(r.Context())
|
||||
u := &unroutedHold{s: s, f: f, w: newHeldWriter(w), cancel: cancel, agent: callerFrom(r).agent, saved: make(chan struct{})}
|
||||
u := &unroutedHold{s: s, f: f, w: newHeldWriter(w), cancel: cancel, agent: callerFrom(r).agent, saved: make(chan struct{}), gid: goroutineID()}
|
||||
// The timers and the context reach u through held alone, let go as
|
||||
// the handler returns. A stopped timer is not gone: the runtime keeps
|
||||
// it, and its func, in the timer heap of the P that set it until its
|
||||
@@ -748,7 +753,8 @@ func (u *unroutedHold) giveUp(unknown bool) {
|
||||
who := cmpOr(u.agent, cmpOr(f.agent, "?"))
|
||||
said := cmpOr(where, " not masking it")
|
||||
waits := u.waitsSaid()
|
||||
report := u.s.heldReport(u, held, status, who, asked, said)
|
||||
own := heldOwn(u.gid)
|
||||
report := u.s.heldReport(u, held, status, who, asked, said, own)
|
||||
// Saved before it is answered too, so the route the answer finds
|
||||
// names it (#4200); out of f.mu, as it is a file written.
|
||||
name, err := writeHeld(report)
|
||||
@@ -796,7 +802,7 @@ func (u *unroutedHold) giveUp(unknown bool) {
|
||||
(*hook)(u)
|
||||
}
|
||||
u.cancel(errUnrouted)
|
||||
log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s; stopped with %d%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, said, waits, status, saved, unroutedStacks())
|
||||
log.Printf("gateway: %s %s for %s from %s held %s before routing,%s%s, standing at %s; stopped with %d%s%s", u.r.Method, u.r.URL.Path, cmpOr(asked, "?"), who, held, said, waits, cmpOr(own.at, "?"), status, saved, unroutedStacks())
|
||||
}
|
||||
|
||||
// unroutedMsg is the error of a request held for held before routing:
|
||||
|
||||
Reference in New Issue
Block a user