gateway: a streamed reasoning summary the upstream seals by its own id is not given to the client twice (#2974)

What changed:
- responsesDecoder remembers, by its output_index, the id a reasoning
  item went out added by, and tells the item's sealed done event by
  that id, so an upstream whose ids change per event (Copilot's) has
  its done recognized as the item that streamed.
- responsesEncoder remembers the id KThinkStart came with whatever its
  shape (thinkUp; thinkID kept taking rs_ ids only) and closes the
  streamed item with the sealed one when the seal is that item's,
  instead of closing it unsealed and adding the sealed item again.

Why: on the translated Responses -> Responses path, a reasoning item
whose upstream id does not start with rs_ and that streams a summary
reached the client twice — once under an rs_ id the encoder made up,
then again whole at output_item.done, because the seal's id never
matched the made-up one (#2974, reported and probed by yetone).

Run (darwin/arm64, go test -tags nogui):
- new TestResponsesStreamForeignReasoningIDNotDoubled (stable ids and
  ids that change per event) is red on ef655acb with the duplicate
  shown (added reasoning ids [rs_18dff…0001 Cp6820f38x Cp6820f3bx])
  and green with the fix
- ablation: upstream responses.go restored under the new test → red
  again; fix back → green
- mutations: dropping the remembered id → both subtests red; dropping
  the output_index rewrite → only the rotating-ids subtest red
- full ./internal/gateway/: ok 356.0s; -race targeted families:
  ok 11.1s; gofmt clean; go vet darwin/linux/windows clean; builds
  darwin ./..., linux ./... and GOOS=windows . all ok

Landing record (yetone):
Run at the pushed batch head (tree a6b084d0b, on origin/main 616405061),
go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider and internal/plugin (this batch's
packages and those main changed since the full run): all ok. gofmt -l
clean; go vet ./... (darwin), GOOS=linux and GOOS=windows go vet -tags
nogui ./... clean. internal/gui on macOS (mote-run):
TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners
(#3949), both red at main too.
- The full go test ./... -timeout 45m -count=1 ran one rebase earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2 (main then gained 5bfa9f076's
group stand-in, b19d08593, f856d381a and 616405061). It ran on Linux
(wsl-run): 82 packages ok. internal/agent has 4 reds, all red at
origin/main on that box as well: TestInstalledVersion,
TestGrokInstalled, TestOmpDetectedWithPiDir and
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, #3548). The root
package and internal/cli need gtk4 to build, so they ran on macOS
(mote-run): ok. TestColdTurnsTaken (#4510) was red there once. An
earlier full run at base d307aa648 was red once in
TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone at both
the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
Broken by hand: internal/gateway/responses.go put back to the base with
the test kept: TestResponsesStreamForeignReasoningIDNotDoubled goes red
with the doubled ids (rs_… Cp6820f38x Cp6820f3bx); restored, green.
Not tried: a real upstream that sends non-rs_ reasoning ids; the ids are
the reporter's shape in a fake stream.

Landing record (yetone):
Run at tree 7d7955eb9 (this batch on origin/main 3cfba2e37), go1.26.8:
- go test -count=1 -timeout 45m on Linux (wsl-run) of internal/gateway,
internal/redact, internal/provider, internal/agent and internal/usage
(this batch's packages, plus those main changed since the full run): all
ok except internal/agent's TestInstalledVersion, TestGrokInstalled and
TestOmpDetectedWithPiDir, red at origin/main on that box too (#4033,
#3548). gofmt -l clean; go vet ./... (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./... clean. On macOS (mote-run), the
root package and internal/cli ok; internal/gui red in
TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestMainWindowCorners
(#3949) and TestColdTurnsTaken (#4510), the first two red at main too.
- The full go test ./... -timeout 45m -count=1 ran two rebases earlier,
at tree 66a7a4c17 on origin/main 3a3bdb9f2, on Linux (wsl-run): 82
packages ok, internal/agent's 4 reds as above, plus
TestCopilotFolderFromAnIDEPluginIsNotTheCLI (#4033, red at main). The
root package, internal/cli and internal/gui need gtk4 to build, so they
ran on macOS as above. An earlier full run at base d307aa648 was red
once in TestUnroutedHeldReportSaved (#4300), which passes 5 of 5 alone
at both the head and main.
- Each landed patch's diff matches the head ggbdpq posted last on its
issue (patch-id).
- No GUI file is touched, so no GUI test file was run.
- Rebased after these runs onto origin/main c1457f2ee. Its two commits
since 3cfba2e37 (3f2faef62 gui, c1457f2ee agent) touch neither
internal/gateway nor internal/redact, nor any file this batch changes,
and were not run again here.
Broken by hand: internal/gateway/responses.go put back to the base with
the test kept: TestResponsesStreamForeignReasoningIDNotDoubled goes red
with the doubled ids (rs_… Cp6820f38x Cp6820f3bx); restored, green.
Not tried: a real upstream that sends non-rs_ reasoning ids; the ids are
the reporter's shape in a fake stream.

Generated-by: GLM-5.3-Flash (ZCode)
This commit is contained in:
ggbdpq
2026-11-01 06:38:01 +08:00
committed by yetone
parent 5b63dfd1a8
commit 0b9727ec93
2 changed files with 110 additions and 4 deletions
@@ -3,6 +3,7 @@ package gateway
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
@@ -159,3 +160,87 @@ func TestResponsesSealedReasoningStaysWithResponses(t *testing.T) {
}
}
}
// withID is a reasoning item raw under another id.
func withID(t *testing.T, raw, id string) string {
t.Helper()
var m map[string]any
if err := decodeJSON([]byte(raw), &m); err != nil {
t.Fatal(err)
}
m["id"] = id
b, _ := json.Marshal(m)
return string(b)
}
// cpStream is responsesSealedStream from an upstream whose reasoning ids
// aren't OpenAI's rs_ … (Copilot's begin Cp6820…): the item that streams
// its summary went out added and in every delta by one id, and comes back
// done as the sealed item by another (the same one when the upstream's ids
// are stable, as the summary's raw on done carries).
func cpStream(t *testing.T, summarizedAdded, summarizedDone, sealedAdded, sealedDone string) []string {
t.Helper()
rp := strings.NewReplacer(
rsSummarized, withID(t, rsSummarized, summarizedDone),
"rs_6820f383d7c08191846711c5df8233bc0ac5ba57aafcbac7", summarizedAdded,
rsSealed, withID(t, rsSealed, sealedDone),
"rs_6820f3b2e9fc8191a5c7d0ab1c8e2f4a0ac5ba57aafcbac7", sealedAdded,
)
out := make([]string, len(responsesSealedStream))
for i, l := range responsesSealedStream {
out[i] = rp.Replace(l)
}
return out
}
// A reasoning item the upstream seals at its done is the one that streamed
// its summary, whatever id it went by: the client reads the summary once.
// The old encoder knew its streamed item only by an OpenAI rs_ id, closed
// it unsealed at the seal, then added the sealed item again, so a client
// of the translated path read the summary as two items (#2974).
func TestResponsesStreamForeignReasoningIDNotDoubled(t *testing.T) {
for name, ids := range map[string]struct{ sumA, sumD, sealA, sealD string }{
"stable ids": {sumA: "Cp6820f38x", sumD: "Cp6820f38x", sealA: "Cp6820f3bx", sealD: "Cp6820f3bx"},
"ids that change per event": {sumA: "Cp6820f38a", sumD: "Cp6820f38b", sealA: "Cp6820f3ba", sealD: "Cp6820f3bb"},
} {
t.Run(name, func(t *testing.T) {
evs := translateStream(t, provider.Responses, provider.Responses,
cpStream(t, ids.sumA, ids.sumD, ids.sealA, ids.sealD)...)
var added []string
var done, completed []any
deltas := 0
for _, ev := range evs {
item, _ := ev["item"].(map[string]any)
switch ev["type"] {
case "response.output_item.added":
if item["type"] == "reasoning" {
added = append(added, item["id"].(string))
}
case "response.output_item.done":
if item["type"] == "reasoning" {
done = append(done, item)
}
case "response.reasoning_summary_text.delta":
deltas++
case "response.completed":
for _, it := range ev["response"].(map[string]any)["output"].([]any) {
if it.(map[string]any)["type"] == "reasoning" {
completed = append(completed, it)
}
}
}
}
if deltas == 0 {
t.Fatal("the summary never streamed")
}
if len(added) != 2 || !strings.HasPrefix(added[0], "rs_") || added[1] != ids.sealD {
t.Fatalf("added reasoning ids %v, want the streamed item under the encoder's rs_ id and %s", added, ids.sealD)
}
for form, items := range map[string][]any{"done": done, "completed": completed} {
if len(items) != 2 || !jsonIs(t, items[0], withID(t, rsSummarized, ids.sumD)) || !jsonIs(t, items[1], withID(t, rsSealed, ids.sealD)) {
t.Fatalf("%s reasoning items %v, want 2: %s sealed by %s, then %s", form, items, rsSummarized, ids.sumD, rsSealed)
}
}
})
}
}
+25 -4
View File
@@ -1615,6 +1615,10 @@ type responsesDecoder struct {
// giving, while it lasts, is the call whose lines are being given
waiting []*rCall
giving *rCall
// addedID is the id each reasoning item went out added by, by its
// output_index: an upstream whose ids change per event (Copilot's)
// does the same item done by another (#2974)
addedID map[int]string
}
// rCall is a function_call item added before its arguments came (#3985):
@@ -1837,6 +1841,12 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {
if ev.Item.Type == "reasoning" {
// an item of its own, by the id the upstream gave it (#1445)
emit(Event{Kind: KThinkStart, ID: ev.Item.ID})
if d.addedID == nil {
d.addedID = map[int]string{}
}
if ev.OutputIndex != nil {
d.addedID[*ev.OutputIndex] = ev.Item.ID
}
}
case "response.output_text.delta":
d.endCall(emit)
@@ -1897,7 +1907,14 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {
}
if ev.Item.Type == "reasoning" && ev.Item.EncryptedContent != "" {
// sealed: the item as the upstream wrote it, for a Responses
// client and for its next request (#1445)
// client and for its next request (#1445). An encoder knows
// the item by the id it went out added by, so when the ids
// change per event the done one is told by its own (#2974)
if ev.OutputIndex != nil {
if a := d.addedID[*ev.OutputIndex]; a != "" {
ev.Item.ID = a
}
}
var whole struct {
Item json.RawMessage `json:"item"`
}
@@ -2016,8 +2033,11 @@ type responsesEncoder struct {
text strings.Builder // text of the open message / reasoning
// a reasoning item began upstream (KThinkStart): the next thinking
// opens an item of its own, by thinkID when the upstream named it
// rs_ … . thinkUp is the id it came with whatever its shape: the
// sealed item done by it is the one that streamed, not another (#2974)
thinkNew bool
thinkID string
thinkUp string
// sig is Claude's signature of the open reasoning item's block, which
// its encrypted_content carries back (claudeseal); bare is an item of
// a block signed with no text, opened with no summary part
@@ -2213,7 +2233,8 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) {
}
e.send("response.output_item.done", map[string]any{"output_index": e.item, "item": item})
e.output = append(e.output, item)
e.open, e.text = "", strings.Builder{}
// the open item's upstream id went with it
e.open, e.text, e.thinkUp = "", strings.Builder{}, ""
e.sig, e.bare = strings.Builder{}, false
}
@@ -2266,7 +2287,7 @@ func (e *responsesEncoder) event(ev Event) {
e.text.WriteString(ev.Text)
e.send("response.reasoning_summary_text.delta", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "delta": ev.Text})
case KThinkStart:
e.thinkNew, e.thinkID = true, ""
e.thinkNew, e.thinkID, e.thinkUp = true, "", ev.ID
if strings.HasPrefix(ev.ID, "rs_") {
e.thinkID = ev.ID
}
@@ -2300,7 +2321,7 @@ func (e *responsesEncoder) event(ev Event) {
break // another API's, which a Responses client can't read
}
raw := json.RawMessage(ev.Text)
if e.open == Thinking && !e.thinkNew && (ev.ID == "" || ev.ID == e.itemID) {
if e.open == Thinking && !e.thinkNew && (ev.ID == "" || ev.ID == e.itemID || ev.ID == e.thinkUp) {
// the item streamed so far, done as the upstream wrote it
e.closeAs(raw)
break