dsh's chat and messages routes send no session id, so Routing and Context found a dsh session by the hash of the conversation's opening. A fork repeats its source's opening, so every request the fork made showed under the source, and the fork's name never appeared. Flandern1211's patch, ported: - The gateway keeps the id of the reply it gave the client (Route.ResponseID). It is set from clientResponseID in the same update that marks the route done, so a poll that sees Done also sees the id, with no race against the usage ledger. When magpie translates, it is the id after translation, e.g. chatcmpl-…, not the upstream's msg_…. - sessions reads dsh's replayState.response.responseId into Session.ResponseIDs. Only main files are read, only replies served by the gateway, and only the fork's own replies after its session/end-seed (seedLength for version 1). - Routing (pricedRoutes) and Context (joinConvs) look up a finished request by its reply id first, then by its opening. A request logged before this keeps the opening's session. Changed from the patch: - A reply id names a session over the opening only when the opening is that session's own, or a session it was forked from, or the opening is unknown. Vendors' ids can repeat: an encoder keeps the upstream's id, and Ollama's is chatcmpl-<0..999>. Without the guard, two unrelated conversations could swap names. Session.ForkOf comes from the fork header's parentSession, isSeeded and delegationDepth 0, which is how dsh's buildForkSeed writes it. ownerOf walks that chain, so a fork of a fork works too. - Poll cost: dsh never writes down some reply ids (a title call, a refused turn). Under the patch, each such id made Routing list every session again every 2s, for as long as the route was on the page. Now an id is waited for only up to a minute (convsKept) after its request ended (looseKeys). After that the regular one-minute rebuild covers it. - A page whose loose routes carry only a reply id still builds the map (looseRoute). - The patch's synthetic fork headers gain parentSession, as dsh writes them. - docs/subsystems/gateway-routing.md describes the reply-id join. Tests: - TestDshForkNamedByTheReplyTheGatewayGave sends dsh 0.2.0-rc.2's real captured completions request (testdata/dsh-gateway) through gateway.New() twice, to an Anthropic-only upstream, so the reply is translated. It writes the source's real session file with the first client id, and a fork shaped like dsh's buildForkSeed output with the second. It then checks that pricedRoutes and contextOf put each request under its own session, and an old route without an id under the source. - TestDshForkOfARealSessionListsItsOwnReplies forks the real fixture session: the fork lists only its own reply and ForkOf, the source keeps [c1]. - TestDshReplyIDOfAnotherConversationNamesNoOne covers the guard. - TestRoutingWaitsForAReplyIDOnlyAWhile covers the poll bound. - The patch's own tests: TestDoneRouteKeepsTheClientResponseID (json and stream), TestDshResponseIDs*, TestRoutingTellsAForkByItsReply, TestContextTellsAForkByItsReply. Run on mote (mote-run), at this tree on origin/mainbe5e8f29f. The vet and go test lines below were run again after rebasing one6b9d1199, which changed only the README and library (ok): - gofmt -l internal/ printed nothing. - go vet ./internal/... . is clean. - GOOS=linux go vet -tags nogui and GOOS=windows go vet of internal/{sessions,gui,gateway} are ok. - go test ./internal/sessions ./internal/gateway ./internal/gui -run 'Dsh|ResponseID|Fork|Routing|Context|Conv' -count=1: ok. - GUI: routing-by-key, routing-ctx-sessions, routing-request-metrics, routing-sessions, routing-session-folder, sessions-empty-range, ctx-route, context-map and panel-routing pass in chromium (120/120) and webkit (120/120). Broken by hand, each red, then restored: - guard off: TestDshReplyIDOfAnotherConversationNamesNoOne; - poll bound off: TestRoutingWaitsForAReplyIDOnlyAWhile; - end-seed keeps the inherited reply ids: TestDshResponseIDsSkipTheSeed, TestDshResponseIDsEndSeedAcrossReads and TestDshForkOfARealSessionListsItsOwnReplies; - ForkOf not set: TestDshForkOfARealSessionListsItsOwnReplies, TestDshForkNamedByTheReplyTheGatewayGave, TestRoutingTellsAForkByItsReply and TestContextTellsAForkByItsReply; - gateway keeps no id: TestDoneRouteKeepsTheClientResponseID and TestDshForkNamedByTheReplyTheGatewayGave. Not tried: - a real dsh fork against a running magpie. The session shapes come from the real rc.2 fixture and dsh's fork source. - A request still running, or a failed one, still shows under the source until it has a reply id. The patch says the same. - Delegated subagent files (delegationDepth > 0) are not read for reply ids; they stay under their parent as before. - Not changed: the gateway's turn clock (sessionTurnKey) also falls back to the opening's hash, so a fork and its source running at once share one. Filed as #5496. The full suite runs after the push. Co-authored-by: Flandern1211 <163982805+Flandern1211@users.noreply.github.com> Reported-by: flandern1211_58540 (Discord)
179 lines
7.3 KiB
Go
179 lines
7.3 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
func clientResponseID(t *testing.T, proto provider.Protocol, body string, stream bool) string {
|
|
t.Helper()
|
|
id := ""
|
|
see := func(data string) {
|
|
var obj map[string]json.RawMessage
|
|
if json.Unmarshal([]byte(data), &obj) != nil {
|
|
return
|
|
}
|
|
if stream {
|
|
if proto == provider.Responses {
|
|
if json.Unmarshal(obj["response"], &obj) != nil {
|
|
return
|
|
}
|
|
}
|
|
if proto == provider.Anthropic {
|
|
if json.Unmarshal(obj["message"], &obj) != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
key := "id"
|
|
if proto == provider.Gemini {
|
|
key = "responseId"
|
|
}
|
|
var got string
|
|
json.Unmarshal(obj[key], &got)
|
|
if got != "" {
|
|
if id != "" && got != id {
|
|
t.Fatalf("client received inconsistent IDs %q %q", id, got)
|
|
}
|
|
id = got
|
|
}
|
|
}
|
|
if stream {
|
|
if err := readSSE(strings.NewReader(body), func(_, data string) error { see(data); return nil }); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
} else {
|
|
see(body)
|
|
}
|
|
if id == "" {
|
|
t.Fatalf("client response ID missing in %s", body)
|
|
}
|
|
return id
|
|
}
|
|
|
|
func TestEncoderUsageKeepsActualClientResponseID(t *testing.T) {
|
|
for _, proto := range []provider.Protocol{provider.Chat, provider.Responses, provider.Anthropic, provider.Gemini} {
|
|
for _, upstreamID := range []string{"", "upstream", "resp_original"} {
|
|
for _, stream := range []bool{false, true} {
|
|
t.Run(string(proto)+"/"+upstreamID+"/"+map[bool]string{true: "stream", false: "json"}[stream], func(t *testing.T) {
|
|
req := &Request{Model: "model", Stream: stream}
|
|
u := Usage{RequestID: "request-header"}
|
|
rec := httptest.NewRecorder()
|
|
if stream {
|
|
enc := encoder(proto, newSSEWriter(rec), req, &u)
|
|
enc.event(Event{Kind: KStart, MsgID: upstreamID})
|
|
enc.event(Event{Kind: KText, Text: "answer"})
|
|
enc.event(Event{Kind: KUsage, Usage: Usage{Input: 10, Output: 2}})
|
|
enc.finish()
|
|
} else {
|
|
rec.Write(renderUsage(proto, Result{ID: upstreamID, Model: "model", Parts: []Part{{Kind: Text, Text: "answer"}}}, req, &u))
|
|
}
|
|
want := clientResponseID(t, proto, rec.Body.String(), stream)
|
|
if u.ResponseID != want || u.RequestID != "request-header" {
|
|
t.Fatalf("usage %+v, client %q", u, want)
|
|
}
|
|
if upstreamID == "upstream" && proto == provider.Responses && want != "resp_upstream" {
|
|
t.Fatal(want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSnifferResponseIDIgnoresItemIDs(t *testing.T) {
|
|
for _, tt := range []struct {
|
|
name string
|
|
proto provider.Protocol
|
|
ct, body, want string
|
|
}{
|
|
{"response JSON", provider.Responses, "application/json", `{"id":"resp_a","output":[{"id":"msg_tool"}],"usage":{"input_tokens":10,"output_tokens":2}}`, "resp_a"},
|
|
{"response multiline truncated SSE", provider.Responses, "text/event-stream", "data: {\"type\":\"response.created\",\n" + "data: \"response\":{\"id\":\"resp_a\"}}\n\n" + "data: {\"type\":\"response.output_item.added\",\"id\":\"item_event\",\"item\":{\"id\":\"msg_tool\"}}\n", "resp_a"},
|
|
{"response error terminal", provider.Responses, "text/event-stream", "data: {\"type\":\"response.failed\",\"response\":{\"id\":\"resp_failed\",\"error\":{\"message\":\"failed\"}}}\n\n", "resp_failed"},
|
|
{"response only item", provider.Responses, "text/event-stream", "data: {\"type\":\"response.output_item.added\",\"id\":\"item_event\",\"item\":{\"id\":\"msg_tool\"}}\n\n", ""},
|
|
{"Claude blocks", provider.Anthropic, "text/event-stream", "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_a\"}}\n\ndata: {\"type\":\"content_block_start\",\"id\":\"block\",\"content_block\":{\"id\":\"tool_b\"}}\n\n", "msg_a"},
|
|
{"chat error ID", provider.Chat, "text/event-stream", "data: {\"id\":\"error-event\",\"error\":{\"message\":\"failed\"}}\n\n", ""},
|
|
{"chat JSON", provider.Chat, "application/json", `{"id":"chatcmpl_a","choices":[{"message":{"tool_calls":[{"id":"tool_b"}]}}]}`, "chatcmpl_a"},
|
|
} {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
s := newSniffer(tt.proto, tt.ct)
|
|
for _, b := range []byte(tt.body) {
|
|
s.write([]byte{b})
|
|
}
|
|
if u := s.usage(); u.ResponseID != tt.want {
|
|
t.Fatalf("response ID %q want %q", u.ResponseID, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGatewayPersistsTranslatedClientResponseID(t *testing.T) {
|
|
for _, stream := range []bool{false, true} {
|
|
t.Run(map[bool]string{true: "stream", false: "json"}[stream], func(t *testing.T) {
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("X-Request-Id", "req-header")
|
|
w.Write([]byte("data: {\"id\":\"chatcmpl-upstream\",\"model\":\"model\",\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\ndata: {\"id\":\"chatcmpl-upstream\",\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n"))
|
|
}))
|
|
defer up.Close()
|
|
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"model"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body := `{"model":"fake/model","input":"hi","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `}`
|
|
rec := httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
id := clientResponseID(t, provider.Responses, rec.Body.String(), stream)
|
|
got := lastRecord(t)
|
|
if got.ResponseID != id || got.RequestID != "req-header" || id != "resp_chatcmpl-upstream" {
|
|
t.Fatalf("record %+v client %s", got, id)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A done route keeps the id of the reply the client was given: the agent
|
|
// stores that id with the reply it keeps (dsh's replay state), so the
|
|
// session that made the request can be found again after the fact even
|
|
// when its conversation opening is one a fork copied.
|
|
func TestDoneRouteKeepsTheClientResponseID(t *testing.T) {
|
|
for _, stream := range []bool{false, true} {
|
|
t.Run(map[bool]string{true: "stream", false: "json"}[stream], func(t *testing.T) {
|
|
fresh(t)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Write([]byte("data: {\"id\":\"chatcmpl-upstream\",\"model\":\"model\",\"choices\":[{\"delta\":{\"content\":\"answer\"}}]}\n\ndata: {\"id\":\"chatcmpl-upstream\",\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n"))
|
|
}))
|
|
defer up.Close()
|
|
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: up.URL + "/v1", Models: []string{"model"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body := `{"model":"fake/model","input":"hi","stream":` + map[bool]string{true: "true", false: "false"}[stream] + `}`
|
|
s := New()
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
id := clientResponseID(t, provider.Responses, rec.Body.String(), stream)
|
|
s.trace.mu.Lock()
|
|
got := ""
|
|
if n := len(s.trace.routes); n > 0 {
|
|
got = s.trace.routes[n-1].ResponseID
|
|
}
|
|
s.trace.mu.Unlock()
|
|
if got == "" || got != id {
|
|
t.Fatalf("route's reply id %q, the client's %q", got, id)
|
|
}
|
|
})
|
|
}
|
|
}
|