aiirobyte (#3695): the gateway exited five times on 2026-10-26, and every client was refused until it was started again. The one exit with a stack died of "fatal error: concurrent map read and map write": two of seenBody's goroutines in middleware.(*Run).Tried at once, one of them in moejs's InternGoString. A request's middleware runs in runtimes of the request's own (serveAgent). Only one goroutine may use a runtime at a time (moejs), and Run has no lock to hold callers to it. serve runs each try's onProvider on them (triedOn) through the Tried the request's context carries. For a model that can't see, magpie has each image of the request described (seenBody), up to four at a time, and each description is a request it makes of its own gateway on a context made from the agent's (magpieChose(ctx)). So the descriptions carried the agent's Tried and ran onProvider on one runtime from as many goroutines. A model that can't search has its searches made the same way (searchWith): a search is asked beside the agent's own stream, which goes through the middleware's onEvent, and beside the round's other searches, so one search is enough to share the runtime when the middleware has onEvent. The runtime's maps were read and written from two goroutines and the gateway died. When it didn't, the calls' values crossed. In the runs below, hooks threw on values that weren't there ("Cannot read properties of undefined (reading 'push')", and "(reading 'messages')"), and a description went out as {"0":0,"messages":[0,{"content":[0,{"image_url":0}],...}],...}, its max_tokens, system prompt, text and image each turned into 0. An earlier run of the same break (tree e1c90a00, this code with older comments) had one image asked about twice and another never. ownAsk takes the request's Tried off the context of those two asks, so they go without the agent's middleware, as serveAgent's comment already said of them ("search and vision stand-ins") and as magpie's other own requests (titles, the classifier) go. The agent's own tries are as before: each runs onProvider once, on its runtime. The subsystem page now says why, and the user docs (en, zh, ja) name searches and image descriptions among magpie's own requests. Going without also keeps what the docs tell a hook. Its ctx.protocol, ctx.model and ctx.stream are the agent's request's, while a description's body is a Chat request and a search's an Anthropic one, whatever the agent speaks. A description is also kept for later requests (sights), so one asked through a request's middleware was handed to later requests, other agents' too. The one community middleware with onProvider, antigravity-cloak, rewrites Claude Code's and Codex's lines in the system prompt, which a description's or a search's prompt, magpie's own, doesn't have. Not changed: the report's other fixes, a lock over the runtime, one ask at a time, or a Run per ask. Each keeps the gateway up but still runs the agent's middleware on asks that are magpie's own, which the docs say go without it, and with the first two onProvider still gets bodies its ctx doesn't describe. With ownAsk nothing else uses a request's Run from two goroutines (holdWriter's keepalive writes under the h.mu the handler's writes hold). magpieChose is left as it is: it says whose pick a call is, and its other callers, Codex's thread titles, descriptions and predictions (codex_titles.go), run before serveAgent with no Tried to take off. What was run (tree 4f97ac18, on origin/main865df247, go1.26.8, linux/amd64): - TestImagesDescribedWithoutTheAgentsMiddleware, new: a text-only model asked with four images, and a middleware whose onProvider adds a line naming the provider's model. The four descriptions reach the model that sees without the line, the text model's request has it, and onProvider is called once, with no failure. - TestSearchesWithoutTheAgentsMiddleware, new: a model that can't search makes two web_search calls in one round, with a middleware that has onProvider and onEvent. Both searches reach the searcher without the line, the model is asked twice, its first ask with it (the second goes on from that ask's body), and no hook failed. - Both, without -race: -count=50 -v, 100 PASS; -count=40 three more times, ok. - go test -tags nogui -race -count=20 -cpu 1,2 ./internal/gateway with this -run, ok, no race: 'WithoutTheAgentsMiddleware|TestMiddleware|TestTextOnlyModel|TestVisionSetting|TestImageThatCant|TestGroupsTextOnly|TestDescriberThatCant|TestSeerPicks|TestManyImages|TestWebSearch' - Broken by hand, each run with -race -count=1, then without -race at -count=40 three times: - main's vision.go: the test red, onProvider called 5 times (each description and the agent's try), 3 of the calls throwing "Cannot read properties of undefined" (reading 'push' twice, 'messages' once), the fourth description reaching the model that sees through the middleware as the mangled body above, races reported. At -count=40 all three runs died: of "concurrent map read and map write" in InternGoString (intern.go:167) twice, and of "concurrent map writes" in internASCII (intern.go:195) once. - main's search.go: the test red, both searches through the middleware, races reported. At -count=40 each run had 40 of 40 red, and none died. - ownAsk returning the context as it is: both tests red, races reported. At -count=40 all three runs died of "concurrent map read and map write" in InternGoString. - A real run: magpie built at865df247and at this tree (go build -tags nogui -buildvcs=false), magpie serve in a sandbox HOME, a provider (a local server) with a text-only model and one that sees (from its /v1/models' modalities), Settings' vision model set to the one that sees, and a middleware added with magpie plugin add whose onProvider adds a line. 200 requests to the text-only model on /v1/chat/completions, four new images each, twice per build. 865df247's gateway answered 6 and died on the 7th request, of "concurrent map read and map write" at the report's intern.go:167 in InternGoString, reached from Run.Tried; in the other run it answered 7 and died on the 8th, of "concurrent map writes". 24 and 28 descriptions reached the vendor, all but one with the line; that one's onProvider threw "Cannot read properties of undefined (reading 'push')", so it went as it was. This tree's answered 200 of 200 both times, its 800 descriptions without the line and its 200 text requests with it. - gofmt -l lists nothing; GOOS=linux, windows and darwin go vet -tags nogui ./..., GOOS=windows go vet ./..., GOOS=linux and darwin go build -tags nogui ./... and GOOS=windows go build ./...: exit 0 each. go vet and go build without the tag on linux: exit 1 (this box has no GTK or WebKitGTK dev packages). - node --test site/*.test.mjs, as CI runs it (node v22.22.1): 45 pass (none of them reads plugins.html). - Full suite, -tags nogui (CI's Linux job tags gtk3), outside graftcp (systemd-run, umask 077, Bun 1.4.2 first on PATH as on CI, -timeout 45m, log kept): 65 ok, and 7 red, none in what this changes: - agent TestCodexDriftReached and TestCodexBehindReverseProxy: #3398; TestCopilotFolderFromAnIDEPluginIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath: #3141; TestReasonixCLIRequiresSupportedNativeVersion and TestReasonixCLIRecoversAfterProbeTimeout: this box's /tmp/.git, #3641. - edit TestWriteAtomicReadOnlyHardLink and testenv TestProgram: this box's umask 077, #3640. - gateway TestPluginToldWhereTheAgentWorks, the package's only red: this box's /tmp/.git, #3675. - gui TestGatewayHeldByAContainer and TestGatewayFixQuitsOnlyAMagpie: this box's millions of open fds, #3649. - pii TestFindJoinsTextsAndMapsBack, TestGPUDeathMovesToCPU, TestServeStartsWithoutResidencyHeartbeat and TestWarm: #3741, fixed on main byc84f859d. - provider: "fatal error: close of synctest channel from outside bubble", #3632; the package's tests after it didn't run. Not tried: macOS, Windows (built and vetted only), the reporter's middleware (the report doesn't name it), a real vision model or searcher.
159 lines
5.7 KiB
Go
159 lines
5.7 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"slices"
|
|
|
|
"github.com/yetone/magpie/internal/access"
|
|
"github.com/yetone/magpie/internal/gwmw"
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// serveAgent is serve for a request an agent sent: the agent middleware
|
|
// of the gateway's middleware point (gwmw.Agents: the JS gateway middleware
|
|
// plugins, internal/middleware, while plugins/middleware is on) see its
|
|
// body first, and its reply on the way back, in the agent's own API.
|
|
// magpie's own requests through serve (titles, the router's classifier,
|
|
// search and vision stand-ins) go without them, as their replies are
|
|
// magpie's to read.
|
|
func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) {
|
|
withGatewaySession(w, r)
|
|
w, recorded := recordConversation(w, r, from, body)
|
|
defer recorded()
|
|
// a conversation going round one tool call is answered here, before
|
|
// anything of it is asked of a hook, a middleware or a provider
|
|
if s.stoppedToolLoop(w, r, from, body) {
|
|
return
|
|
}
|
|
w, body, hooked := gatewayHooks(w, r, from, body)
|
|
defer hooked()
|
|
agents := gwmw.AgentsWanted(middlewareWanted)
|
|
if len(agents) == 0 {
|
|
s.serve(w, r, from, body)
|
|
return
|
|
}
|
|
info := gwmw.Info{Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r)}
|
|
var tried []gwmw.Tried
|
|
for _, a := range agents {
|
|
// the user's middleware runs before a route is begun: a wait
|
|
// magpie knows of (unrouted.go)
|
|
waited := noteWait(r.Context())
|
|
run := a.Begin(info)
|
|
if run == nil {
|
|
waited()
|
|
continue
|
|
}
|
|
defer run.End()
|
|
if t, ok := run.(gwmw.Tried); ok {
|
|
tried = append(tried, t)
|
|
}
|
|
var turned *gwmw.Reject
|
|
body, turned = run.Request(body)
|
|
waited()
|
|
if turned != nil {
|
|
writeError(w, from, turned.Status, turned.Message)
|
|
return
|
|
}
|
|
var done func()
|
|
w, done = run.Wrap(w)
|
|
defer done()
|
|
}
|
|
if len(tried) > 0 {
|
|
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, tried))
|
|
}
|
|
s.serve(w, r, from, body)
|
|
}
|
|
|
|
type triedKey struct{}
|
|
|
|
// triedOn is body as it goes to model on p, in the agent's API: what each
|
|
// middleware of the request that is also gwmw.Tried (the JS chain's
|
|
// onProvider) made of it for that provider. Each try starts from the body
|
|
// it is given, so a change for one provider never reaches another's.
|
|
func triedOn(ctx context.Context, p provider.Provider, model string, body []byte) []byte {
|
|
tried, _ := ctx.Value(triedKey{}).([]gwmw.Tried)
|
|
if len(tried) == 0 {
|
|
return body
|
|
}
|
|
to := gwmw.To{ID: p.ID, Name: p.Name, Account: accountAgent(p), Model: model}
|
|
for _, t := range tried {
|
|
body = t.Tried(body, to)
|
|
}
|
|
return body
|
|
}
|
|
|
|
// ownAsk is ctx for a request magpie asks of its own gateway while it
|
|
// serves an agent's (a web search, an image's description): the agent's
|
|
// middleware isn't run on it, as on magpie's other own requests. Its
|
|
// runtimes are the agent request's, which one goroutine may use at a time
|
|
// (moejs), and Run has no lock to hold callers to it, while these asks go
|
|
// beside the request and each other: images described at once ran
|
|
// onProvider on one runtime, and the gateway died of "concurrent map read
|
|
// and map write" (#3695). Nor does the hooks' ctx describe them: a
|
|
// description's body is Chat and a search's Anthropic, whatever
|
|
// ctx.protocol names, and ctx.model and ctx.stream are the agent's.
|
|
func ownAsk(ctx context.Context) context.Context {
|
|
return context.WithValue(ctx, triedKey{}, []gwmw.Tried(nil))
|
|
}
|
|
|
|
// middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware
|
|
// is in use.
|
|
func middlewareWanted() bool { return middleware.On() > 0 }
|
|
|
|
// gatewayHooks runs the asynchronous request hooks (OpenCode plugins'
|
|
// gateway entries, in the plugin host) on an agent's request: the body they
|
|
// leave is the one served, and they see the reply the agent got once it is
|
|
// whole. Its writer wraps the middleware's, so what they see is what the
|
|
// agent was given. With no hook it is the request as it came.
|
|
func gatewayHooks(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) (http.ResponseWriter, []byte, func()) {
|
|
if !plugin.HasGateway() {
|
|
return w, body, func() {}
|
|
}
|
|
info := plugin.GatewayContext{Origin: gatewayOrigin(r), Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r), Session: sessionOf(r.Header)}
|
|
if req, err := parse(from, body); err == nil {
|
|
info.Cwd = workDir(req)
|
|
info.Query = gatewayQuery(req)
|
|
}
|
|
// the plugin host, started for it if need be: a wait magpie knows of
|
|
// before a route is begun (unrouted.go)
|
|
waited := noteWait(r.Context())
|
|
run := plugin.GatewayBegin(r.Context(), body, info)
|
|
waited()
|
|
if run == nil {
|
|
return w, body, func() {}
|
|
}
|
|
w, done := gatewayResponse(w, r, from, run.Body, run)
|
|
return w, run.Body, func() { done(); run.Close() }
|
|
}
|
|
|
|
// gatewayQuery uses the same user-authored words as routing, excluding
|
|
// agent context, tool results and images. Tool-only increments have none.
|
|
func gatewayQuery(req *Request) string {
|
|
for i := len(req.Messages) - 1; i >= 0; i-- {
|
|
m := req.Messages[i]
|
|
if m.Role != "user" {
|
|
continue
|
|
}
|
|
if query := userSaid(m); query != "" {
|
|
return query
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// gatewayOrigin exposes provenance, never credentials or peer addresses.
|
|
// Forwarded traffic remains remote even when the administrator trusts its
|
|
// proxy for authentication: that trust does not establish conversation ownership.
|
|
func gatewayOrigin(r *http.Request) string {
|
|
if access.Caller(r.Context()).KeyID != "" || managedKey(r) {
|
|
return "gateway-key"
|
|
}
|
|
if local(r) && !slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) {
|
|
return "local"
|
|
}
|
|
return "remote"
|
|
}
|