gateway: a Gemini thought signature goes back only to the provider that gave it

mimi001234 on Discord: Pi (openai-completions) on auto/gemini-4-argon, a
group of google-vertex and google-aistudio-paid. Vertex AI served turns
1 to 14 and signed its calls; on turn 15 it answered 429, the group moved
to AI Studio, and magpie replayed Vertex AI's signatures from
gemini-signatures/. AI Studio answered every try with 400 "Corrupted
thought signature." A signature is the issuing backend's, and only it
takes one.

- The provider that gave a signature is noted beside it,
  gemini-signatures/<key>.by (noteSigner, written through temp and
  rename), wherever a reply is read: decoderFor (every translated path:
  Chat, Anthropic and Responses clients, plugins, search, continuations)
  and sigTidy (a Chat relay, and a Gemini client's reply relayed as it
  came, now only read, in native mode).
- Every request is fitted to its provider: ownSignatures in
  forwardTranslated, chatCallSignatures and geminiBodySignatures in
  passthrough. Another provider's signature goes as Google's documented
  skip_thought_signature_validator on a call, and not at all on text. A
  signature of no known provider (ids from before this change, a note
  that couldn't be written) goes as before.
- A 400 "Invalid/Corrupted thought signature" (signatureRefused) is asked
  again once without signatures at any upstream Gemini's signatures
  reach (signaturesReach), relayed too, not only Vertex AI translated;
  it rests no account (restAfterMarked) and lets a group go on to its
  next member (shapeRefused).

The signer is the provider id, not the account: two accounts of one
provider share signatures as before.

Run on mote (mote-run), the targeted run and vets at this change on origin/main 0e55a7593:
- go test ./internal/gateway -run 'Signature|Signer|Vertex|Gemini|Corrupted': ok
- go test -timeout 45m ./internal/gateway: ok (876s), at this change on
  bf60ea596; the only commit since, 47d583939, touches internal/library
- gofmt -l internal/: clean; go vet ./...; GOOS=linux go vet -tags nogui
  ./...; GOOS=windows go vet ./...; go build ./...: ok

Red on the old code (origin/main 0e55a7593 with the new test file):
TestSignatureGoesOnlyToItsSigner (turn 3: 400 "AI Studio: ... Corrupted
thought signature."), TestCorruptedSignatureTriedWithout and
TestCorruptedSignatureNotTheAccount (rested "backoff" 60s).
Broken by hand on the new code:
- chatCallSignatures without the foreignSignature check:
  TestSignatureGoesOnlyToItsSigner red (AI Studio asked twice: refused,
  then the retry).
- ownSignatures in forwardTranslated commented out:
  TestSignatureGoesOnlyToItsSignerTranslated red the same way.
- the passthrough retry turned off: TestCorruptedSignatureTriedWithout
  red with the 400.

Not tried: real Vertex AI and AI Studio accounts; a Gemini client's
request relayed to Vertex AI end to end (TestGeminiBodyKeepsOnlyItsOwn
covers the body and the noting only); Code Assist relays, whose replies
are not noted, so their signatures count as of no known provider.
This commit is contained in:
yetone
2026-11-05 11:42:53 +08:00
parent 47d5839397
commit 2260390a01
9 changed files with 711 additions and 51 deletions
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -1680,12 +1680,15 @@ var unsaidWords = regexp.MustCompile(`(?i)(^|"|\\"|: )invalid request error trac
// 'messages[1].reasoning_content'", EDwinpzy) is one too: the client's
// request is whole, and a group of Beam then another model stopped at
// Beam before.
// Google's word for a thought signature it didn't give (signatureRefused:
// "Corrupted thought signature.", one Vertex AI gave replayed to AI Studio,
// mimi001234) is one: the member that gave it may take it.
// One that also says the account is out of quota or credit (quotaWords,
// creditWords: "请充值") is that, and rests it (#4095).
func shapeRefused(status int, body []byte) bool {
// the words are matched decoded, too (#1669)
body = wordsOf(body)
return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body) || customToolRefusal.Match(body) || zhipuImageRefusal.Match(body) || wrongEndpoint(status, body) || upstreamFailedWords.Match(body) || reasoningBackRefused(body)) &&
return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body) || customToolRefusal.Match(body) || zhipuImageRefusal.Match(body) || wrongEndpoint(status, body) || upstreamFailedWords.Match(body) || reasoningBackRefused(body) || signatureRefused.Match(body)) &&
!quotaWords.Match(body) && !creditWords.Match(body) && !unservedWords.Match(body) && !refusedWords.Match(body)
}
+38 -5
View File
@@ -5901,7 +5901,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// Gemini's thought signatures, which came to the client in its
// calls' ids, go back where Gemini wants them; another upstream
// gets the calls' own ids (#687)
body = chatCallSignatures(body, compat)
body = chatCallSignatures(body, compat, p.ID, true)
if p.Preset == "mistral" || p.Host() == "api.mistral.ai" {
// an earlier turn's reasoning_content, which Mistral turns
// away, as the thinking part it takes (#494)
@@ -5930,6 +5930,8 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// body has no such field, and Factory ignores it.
geminiWhole = !streamOf(body)
body = withoutFields(body, "stream")
// a signature another provider gave goes to none (ownSignatures)
body = geminiBodySignatures(body, p.ID, true)
case provider.Anthropic:
// what the client holds, taken before the upstream gets its own
// call ids back below, and those given back to it (tool_use_ids.go,
@@ -6084,6 +6086,25 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if err != nil {
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
}
if res.StatusCode == http.StatusBadRequest && (proto == provider.Chat || proto == provider.Gemini) && signaturesReach(p, proto, upstream) {
// a signature Google won't take (signatureRefused), one given
// before magpie noted whose it was: asked again once without
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if signatureRefused.Match(b) {
bare := geminiBodySignatures(body, p.ID, false)
if proto == provider.Chat {
bare = chatCallSignatures(body, true, p.ID, false)
}
if !bytes.Equal(bare, body) {
body = bare
if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil {
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
}
}
}
}
if delta && badRequest(res.StatusCode) || delta && res.StatusCode == http.StatusNotFound {
// one it no longer holds: the conversation whole
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
@@ -6509,7 +6530,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
}
var sigs *sigTidy
if proto == provider.Chat && geminiCompat(p.Host(), model) {
sigs = &sigTidy{sse: sse}
sigs = &sigTidy{sse: sse, by: p.ID}
} else if proto == provider.Gemini {
// a Gemini client keeps the signatures itself: noted as p's
sigs = &sigTidy{sse: sse, by: p.ID, native: true}
}
var search *searchTidy
if searchFn && sse {
@@ -7032,6 +7056,8 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
r.Effort, req = e, &r
}
}
// Gemini's signatures another provider gave go to none (ownSignatures)
req = ownSignatures(req, p.ID)
if p.IsVertex() && !provider.VertexPartner(model) && !provider.VertexClaude(model) {
// Gemini's levels; a partner model on chat completions, and
// Claude on Anthropic's Messages API, are sent their effort as
@@ -7495,9 +7521,9 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
continue
}
}
if p.IsVertex() && res.StatusCode == http.StatusBadRequest && vertexSignatureRefused.Match(b) {
// a call's signature Vertex AI won't take (a client changed
// it, or another API gave it, the conversation having moved):
if res.StatusCode == http.StatusBadRequest && signaturesReach(p, to, model) && signatureRefused.Match(b) {
// a signature Google won't take (a client changed it, or
// another provider gave it before magpie noted whose it was):
// the calls waved through instead, for this request
if r, had := withoutSignatures(req); had {
req = r
@@ -8444,7 +8470,14 @@ func build(proto provider.Protocol, r *Request, model, host string, rejectTemp b
// A ChatGPT account is given a declared tool whose name its backend
// refuses under another (provider.CodexToolName); the model's call to it
// comes back by the name the agent declared, from tools, the request's.
//
// Each Gemini thought signature the reply gives is noted as p's
// (signersNoted), so it goes back to p alone (ownSignatures).
func decoderFor(p provider.Provider, proto provider.Protocol, tools []Tool) func(data string, emit func(Event)) error {
return signersNoted(decoderOf(p, proto, tools), p.ID)
}
func decoderOf(p provider.Provider, proto provider.Protocol, tools []Tool) func(data string, emit func(Event)) error {
if proto == provider.Chat && p.IsPlugin() {
d := &chatDecoder{past: true}
return d.decode
+243 -11
View File
@@ -4,9 +4,13 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
"regexp"
"slices"
"strconv"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// Gemini's thought signatures on tool calls (#687). Gemini 3 signs the
@@ -179,11 +183,13 @@ func googleExtra(sig string) map[string]any {
return map[string]any{"google": map[string]any{"thought_signature": sig}}
}
// chatCallSignatures is a Chat request relayed as it is with the
// signatures off its call ids: for Gemini (gemini) each call has its own
// in extra_content, or skip_thought_signature_validator in a turn with
// none; for another upstream the ids are only the calls' own again.
func chatCallSignatures(body []byte, gemini bool) []byte {
// chatCallSignatures is a Chat request relayed as it is to provider by
// with the signatures off its call ids: for Gemini (gemini) each call has
// its own in extra_content, or skip_thought_signature_validator in a turn
// with none; for another upstream the ids are only the calls' own again.
// A signature another provider gave (foreignSignature) goes to none, nor
// does any when keep is false (signatureRefused: asked again without).
func chatCallSignatures(body []byte, gemini bool, by string, keep bool) []byte {
signed := bytes.Contains(body, []byte(sigMark))
if !signed && !(gemini && bytes.Contains(body, []byte(`"tool_calls"`))) {
return body
@@ -216,6 +222,15 @@ func chatCallSignatures(body []byte, gemini bool) []byte {
if s := googleSignature(c["extra_content"]); s != "" {
sig = s
}
if sig != "" && (!keep || foreignSignature(sig, by)) {
// another provider's, or one turned away: the call goes
// as one this provider didn't sign
sig = ""
if googleSignature(c["extra_content"]) != "" {
delete(c, "extra_content")
changed = true
}
}
sigs[i] = sig
signedStep = signedStep || sig != ""
}
@@ -245,14 +260,43 @@ func chatCallSignatures(body []byte, gemini bool) []byte {
// sigTidy gives, in a Chat reply from Gemini relayed as it is, each tool
// call that came with a thought signature an id carrying it (signedID).
// Lines, or a whole reply, pass as they came unless one has a signature.
//
// Each signature is noted as provider by's (noteSigner). For a Gemini
// client's reply (native), which carries its signatures where Gemini
// gives them, the signatures are only noted, and the reply goes as it
// came.
type sigTidy struct {
sse bool
buf []byte
sse bool
by string
native bool
buf []byte
}
var thoughtSignatureField = []byte(`"thought_signature"`)
// nativeNoteBytes bounds the copy of a whole Gemini reply kept to note
// its signatures: one past it has none noted, and its signatures go back
// as before signers were kept.
const nativeNoteBytes = 8 << 20
func (t *sigTidy) write(b []byte) []byte {
if t.native {
// the reply goes on as it comes; what it signed is read off a
// copy, by its lines on a stream, whole at the end otherwise
if !t.sse && len(t.buf)+len(b) > nativeNoteBytes {
t.buf, t.by = nil, ""
}
if t.by != "" {
t.buf = append(t.buf, b...)
}
if t.sse {
if i := bytes.LastIndexByte(t.buf, '\n'); i >= 0 {
noteGeminiSigners(t.buf[:i+1], t.by)
t.buf = append(t.buf[:0], t.buf[i+1:]...)
}
}
return b
}
t.buf = append(t.buf, b...)
if !t.sse {
return nil
@@ -269,8 +313,12 @@ func (t *sigTidy) write(b []byte) []byte {
func (t *sigTidy) flush() []byte {
b := t.buf
t.buf = nil
if t.native {
noteGeminiSigners(b, t.by)
return nil
}
if !t.sse {
if out, ok := signReply(b); ok {
if out, ok := signReply(b, t.by); ok {
return out
}
return b
@@ -296,7 +344,7 @@ func (t *sigTidy) lines(b []byte) []byte {
out = append(out, line...)
continue
}
nb, ok := signReply(data)
nb, ok := signReply(data, t.by)
if !ok {
out = append(out, line...)
continue
@@ -307,8 +355,9 @@ func (t *sigTidy) lines(b []byte) []byte {
}
// signReply is a chunk, or a whole reply, with the signed calls' ids
// carrying their signatures, and whether there was one.
func signReply(data []byte) ([]byte, bool) {
// carrying their signatures, noted as provider by's, and whether there
// was one.
func signReply(data []byte, by string) ([]byte, bool) {
if !bytes.Contains(data, thoughtSignatureField) {
return nil, false
}
@@ -337,6 +386,7 @@ func signReply(data []byte) ([]byte, bool) {
if sig == "" {
continue
}
noteSigner(sig, by)
var id string
json.Unmarshal(call["id"], &id)
if _, had := unsignedID(id); had != "" {
@@ -362,3 +412,185 @@ func signReply(data []byte) ([]byte, bool) {
}
return out, true
}
// A signature goes back only to the provider that gave it (mimi001234 on
// Discord: Pi on a group of Vertex AI and AI Studio; Vertex cooled down
// on turn 15 and AI Studio was sent Vertex's signatures, and answered
// every turn with 400 "Corrupted thought signature"). Google documents
// skip_thought_signature_validator for a function call it didn't sign
// ("when transferring history from a model that does not include thought
// signatures"), which a step's first call is given in place of another
// provider's signature; a text part's signature only helps, and goes.
// signersNoted is dec with each signature in its events noted as provider
// by's: a tool call's, which rides in its id (signedID), and a text's.
func signersNoted(dec func(string, func(Event)) error, by string) func(string, func(Event)) error {
return func(data string, emit func(Event)) error {
return dec(data, func(ev Event) {
switch ev.Kind {
case KToolStart:
if _, sig := unsignedID(ev.ID); sig != "" {
noteSigner(sig, by)
}
case KTextSig:
noteSigner(ev.Text, by)
}
emit(ev)
})
}
}
// ownSignatures is req for provider by with no signature another provider
// gave on its calls and texts (foreignSignature). Messages are copied
// before they change.
func ownSignatures(req *Request, by string) *Request {
return dropSignatures(req, func(sig string) bool { return foreignSignature(sig, by) })
}
// dropSignatures is req with the Gemini signatures drop says on its calls
// and texts taken off. Claude's signed thinking is no Gemini signature,
// and stays.
func dropSignatures(req *Request, drop func(sig string) bool) *Request {
var msgs []Message
for i, m := range req.Messages {
var parts []Part
for j, p := range m.Parts {
if (p.Kind != ToolCall && p.Kind != Text) || p.Signature == "" || !drop(p.Signature) {
continue
}
if parts == nil {
parts = slices.Clone(m.Parts)
}
parts[j].Signature = ""
}
if parts == nil {
continue
}
if msgs == nil {
msgs = slices.Clone(req.Messages)
}
msgs[i].Parts = parts
}
if msgs == nil {
return req
}
r := *req
r.Messages = msgs
return &r
}
// signatureRefused is Google turning a signature away as one it didn't
// give: Vertex AI's 400 "Invalid thought signature.", AI Studio's 400
// "Corrupted thought signature.". It is about the request's history, not
// the account: the request is asked again without signatures, and no
// account rests for it.
var signatureRefused = regexp.MustCompile(`(?i)\b(invalid|corrupted) thought signature`)
// signaturesReach says a request built for provider p on API to carries
// Gemini's signatures there: Gemini's own API (Vertex AI, AI Studio, Code
// Assist) or its OpenAI-compatible one.
func signaturesReach(p provider.Provider, to provider.Protocol, model string) bool {
return to == provider.Gemini || to == provider.CodeAssist || p.IsVertex() || to == provider.Chat && geminiCompat(p.Host(), model)
}
var geminiSignatureField = []byte(`"thoughtSignature"`)
// noteGeminiSigners notes each thoughtSignature in a Gemini reply, a chunk
// or a whole one (an object, or streamGenerateContent's array of them),
// as provider by's.
func noteGeminiSigners(b []byte, by string) {
if !bytes.Contains(b, geminiSignatureField) {
return
}
note := func(r gjson.Result) {
for _, c := range r.Get("candidates").Array() {
for _, p := range c.Get("content.parts").Array() {
noteSigner(p.Get("thoughtSignature").String(), by)
}
}
for _, c := range r.Get("response.candidates").Array() {
for _, p := range c.Get("content.parts").Array() {
noteSigner(p.Get("thoughtSignature").String(), by)
}
}
}
all := func(r gjson.Result) {
if r.IsArray() {
r.ForEach(func(_, v gjson.Result) bool { note(v); return true })
} else {
note(r)
}
}
if gjson.ValidBytes(b) {
// a whole reply, however it is laid out
all(gjson.ParseBytes(b))
return
}
for len(b) > 0 {
line := b
if i := bytes.IndexByte(b, '\n'); i >= 0 {
line, b = b[:i], b[i+1:]
} else {
b = nil
}
line = bytes.TrimSpace(line)
if d, ok := bytes.CutPrefix(line, []byte("data:")); ok {
line = bytes.TrimSpace(d)
}
if !bytes.Contains(line, geminiSignatureField) {
continue
}
all(gjson.ParseBytes(line))
}
}
// geminiBodySignatures is a Gemini client's request relayed as it is to
// provider by with no signature another provider gave (foreignSignature),
// nor any when keep is false: a function call that had one goes waved
// through (skipSignature), a text without.
func geminiBodySignatures(body []byte, by string, keep bool) []byte {
if !bytes.Contains(body, geminiSignatureField) {
return body
}
var q map[string]json.RawMessage
var contents []map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil || json.Unmarshal(q["contents"], &contents) != nil {
return body
}
changed := false
for _, c := range contents {
var parts []map[string]json.RawMessage
if json.Unmarshal(c["parts"], &parts) != nil {
continue
}
edited := false
for _, p := range parts {
var sig string
if json.Unmarshal(p["thoughtSignature"], &sig) != nil || sig == "" || sig == skipSignature {
continue
}
if keep && !foreignSignature(sig, by) {
continue
}
if _, call := p["functionCall"]; call {
p["thoughtSignature"], _ = marshalPlain(skipSignature)
} else {
delete(p, "thoughtSignature")
}
edited = true
}
if edited {
c["parts"], _ = marshalPlain(parts)
changed = true
}
}
if !changed {
return body
}
q["contents"], _ = marshalPlain(contents)
out, err := marshalPlain(q)
if err != nil {
return body
}
return out
}
+4 -4
View File
@@ -221,7 +221,7 @@ func TestGeminiCallsWithoutSignature(t *testing.T) {
} `json:"tool_calls"`
} `json:"messages"`
}
if err := json.Unmarshal(chatCallSignatures(body, true), &q); err != nil {
if err := json.Unmarshal(chatCallSignatures(body, true, "google", true), &q); err != nil {
t.Fatal(err)
}
sigOf := func(m, c int) string {
@@ -236,7 +236,7 @@ func TestGeminiCallsWithoutSignature(t *testing.T) {
if sigOf(3, 0) != "c2ln" || sigOf(3, 1) != "" || q.Messages[3].ToolCalls[0].ID != "call_a" || q.Messages[4].ToolCallID != "call_a" {
t.Errorf("a signed turn went as %+v", q.Messages[3:5])
}
other := string(chatCallSignatures(body, false))
other := string(chatCallSignatures(body, false, "google", true))
if strings.Contains(other, sigMark) || strings.Contains(other, "extra_content") || !strings.Contains(other, `"id":"call_a"`) {
t.Errorf("another upstream was sent %s", other)
}
@@ -357,7 +357,7 @@ func TestShortenedIDGoesUnsigned(t *testing.T) {
body := []byte(`{"messages":[{"role":"user","content":"list files"},
{"role":"assistant","tool_calls":[{"id":"` + cut + `","type":"function","function":{"name":"bash","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"` + cut + `","content":"a.txt"}]}`)
if relayed := string(chatCallSignatures(body, true)); !strings.Contains(relayed, `"thought_signature":"`+skipSignature+`"`) {
if relayed := string(chatCallSignatures(body, true, "google", true)); !strings.Contains(relayed, `"thought_signature":"`+skipSignature+`"`) {
t.Fatalf("%q cut to %d: relayed as %s", c.id, n, relayed)
}
r := &Request{Messages: []Message{
@@ -469,7 +469,7 @@ func TestKeptSignatureGoneOrChanged(t *testing.T) {
t.Fatalf("a gone file read as %q, %d bytes", got, len(back))
}
body := []byte(`{"messages":[{"role":"assistant","tool_calls":[{"id":"` + id + `","type":"function","function":{"name":"bash","arguments":"{}"}}]}]}`)
if out := string(chatCallSignatures(body, true)); !strings.Contains(out, `"thought_signature":"`+skipSignature+`"`) {
if out := string(chatCallSignatures(body, true, "google", true)); !strings.Contains(out, `"thought_signature":"`+skipSignature+`"`) {
t.Fatalf("relayed as %s", out)
}
// written again, it is read again
+340
View File
@@ -0,0 +1,340 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// studioCorrupted is how Gemini's OpenAI-compatible endpoint turns away a
// thought signature it didn't give (mimi001234, 2026-11-05).
const studioCorrupted = `[{"error":{"code":400,"message":"Corrupted thought signature.","status":"INVALID_ARGUMENT"}}]`
// studioSig is the signature studioUp gives its own calls.
const studioSig = "c3R1ZGlvLW1pbnRlZC1zaWduYXR1cmU="
// studioUp is Gemini on Google AI Studio's OpenAI-compatible chat
// completions: a call's signature has to be one it gave, or the value
// Google documents for calls it didn't make.
type studioUp struct {
mu sync.Mutex
sent [][]string // per request, the signature on each call, in order
reply string
}
func (u *studioUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var req struct {
Stream bool `json:"stream"`
Messages []struct {
ToolCalls []struct {
Extra json.RawMessage `json:"extra_content"`
} `json:"tool_calls"`
} `json:"messages"`
}
json.Unmarshal(b, &req)
var sigs []string
refused := false
for _, m := range req.Messages {
for _, c := range m.ToolCalls {
sig := googleSignature(c.Extra)
sigs = append(sigs, sig)
if sig != "" && sig != skipSignature && sig != studioSig {
refused = true
}
}
}
u.mu.Lock()
u.sent = append(u.sent, sigs)
reply := u.reply
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if refused {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, studioCorrupted)
return
}
if reply == "" {
reply = chatOK
}
if req.Stream && reply == chatOK {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, `data: {"id":"ok","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}`+"\n\n"+
`data: {"id":"ok","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
return
}
io.WriteString(w, reply)
}
func (u *studioUp) last(t *testing.T) []string {
t.Helper()
u.mu.Lock()
defer u.mu.Unlock()
if len(u.sent) == 0 {
t.Fatal("AI Studio was asked nothing")
}
return u.sent[len(u.sent)-1]
}
func (u *studioUp) count() int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.sent)
}
func studioServe(t *testing.T, u *studioUp) {
t.Helper()
up := httptest.NewServer(u)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "google-aistudio-paid", Name: "AI Studio", Key: "k",
Chat: up.URL + "/v1beta/openai", Models: []string{"gemini-3.8-flash"}}); err != nil {
t.Fatal(err)
}
}
func nobodyResting(t *testing.T) {
t.Helper()
restingUntil.Lock()
defer restingUntil.Unlock()
for id := range restingUntil.m {
if strings.Contains(id, "aistudio") {
t.Errorf("%s was rested", id)
}
}
}
// piTurn is Pi's next request on the group after the calls with ids
// (openai-completions).
func piTurn(ids []string) string {
return `{"model":"group/g","stream":false,"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}],"messages":[
{"role":"user","content":"Weather in Paris and in Tokyo?"},
{"role":"assistant","content":null,"tool_calls":[
{"id":"` + ids[0] + `","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}},
{"id":"` + ids[1] + `","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}}]},
{"role":"tool","tool_call_id":"` + ids[0] + `","content":"18C, clear"},
{"role":"tool","tool_call_id":"` + ids[1] + `","content":"21C, rain"}]}`
}
// mimi001234 (2026-11-05): Pi on a group of Vertex AI and AI Studio.
// Vertex AI served the turns and signed its calls; when it answered 429,
// the group moved to AI Studio with Vertex AI's signatures, and AI Studio
// answered every try with 400 "Corrupted thought signature.". A signature
// goes back only to the provider that gave it: AI Studio is sent its
// calls as ones it didn't make, and Vertex AI, and AI Studio, each still
// get their own.
func TestSignatureGoesOnlyToItsSigner(t *testing.T) {
limited := false
v := &vertexUp{reply: func(n int, body map[string]any) (int, string) {
if limited {
return http.StatusTooManyRequests, `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
}
return http.StatusOK, vertexCalls
}}
s := vertexServe(t, v, vertexLevels)
u := &studioUp{}
studioServe(t, u)
if err := provider.SaveGroup(provider.Group{Name: "G", Routing: provider.Ordered,
Members: []string{"google-vertex/gemini-3.8-flash", "google-aistudio-paid/gemini-3.8-flash"}}); err != nil {
t.Fatal(err)
}
s = New()
code, out := postAs(t, s, "", `{"model":"group/g","stream":false,"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object"}}}],
"messages":[{"role":"user","content":"Weather in Paris and in Tokyo?"}]}`)
if code != http.StatusOK {
t.Fatalf("turn 1: %d %s", code, out)
}
ids := vertexCallIDs.FindAllString(out, -1)
if len(ids) < 2 || !strings.Contains(ids[0], sigMark) {
t.Fatalf("turn 1: Vertex AI's calls came back as %v", ids)
}
ids = []string{ids[0], ids[len(ids)-1]}
// Vertex AI is sent its own signature, as before
if code, out := postAs(t, s, "", piTurn(ids)); code != http.StatusOK {
t.Fatalf("turn 2 on Vertex AI: %d %s", code, out)
}
parts := v.last(t).body["contents"].([]any)[1].(map[string]any)["parts"].([]any)
if sig := parts[0].(map[string]any)["thoughtSignature"]; sig != vertexCallSig {
t.Errorf("Vertex AI was sent %v for its own call, want its signature", sig)
}
// Vertex AI out of quota: AI Studio takes the turn, Vertex AI's
// signature not sent to it
limited = true
if code, out := postAs(t, s, "", piTurn(ids)); code != http.StatusOK || !strings.Contains(out, "hello") {
t.Fatalf("turn 3 on AI Studio: %d %s", code, out)
}
if u.count() != 1 {
t.Errorf("AI Studio was asked %d times, want once", u.count())
}
if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
t.Errorf("AI Studio was sent %q, want %s on the first call", got, skipSignature)
}
nobodyResting(t)
// AI Studio's own signature goes back to it
u.mu.Lock()
u.reply = `{"id":"s1","choices":[{"index":0,"finish_reason":"tool_calls","message":{"role":"assistant","content":null,"tool_calls":[
{"id":"call_s1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"},"extra_content":{"google":{"thought_signature":"` + studioSig + `"}}},
{"id":"call_s2","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}}]}}]}`
u.mu.Unlock()
code, out = postAs(t, s, "", piTurn(ids))
if code != http.StatusOK {
t.Fatalf("turn 4 on AI Studio: %d %s", code, out)
}
var reply struct {
Choices []struct {
Message struct {
ToolCalls []struct {
ID string `json:"id"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if json.Unmarshal([]byte(out), &reply) != nil || len(reply.Choices) == 0 || len(reply.Choices[0].Message.ToolCalls) != 2 {
t.Fatalf("turn 4: %s", out)
}
studioIDs := []string{reply.Choices[0].Message.ToolCalls[0].ID, reply.Choices[0].Message.ToolCalls[1].ID}
u.mu.Lock()
u.reply = ""
u.mu.Unlock()
if code, out := postAs(t, s, "", piTurn(studioIDs)); code != http.StatusOK {
t.Fatalf("turn 5 on AI Studio: %d %s", code, out)
}
if got := u.last(t); len(got) == 0 || got[0] != studioSig {
t.Errorf("AI Studio was sent %q for its own call, want its signature", got)
}
nobodyResting(t)
}
// A signature whose giver isn't known (an id from before signers were
// noted) that AI Studio turns away as corrupted is tried once more with
// the calls as ones it didn't make, and rests nobody.
func TestCorruptedSignatureTriedWithout(t *testing.T) {
fresh(t)
u := &studioUp{}
studioServe(t, u)
s := New()
ids := []string{signedID("call_1", "c2lnbmF0dXJlLW9uZQ=="), "call_2"}
body := strings.Replace(piTurn(ids), "group/g", "google-aistudio-paid/gemini-3.8-flash", 1)
if code, out := postAs(t, s, "", body); code != http.StatusOK {
t.Fatalf("%d %s", code, out)
}
if u.count() != 2 {
t.Fatalf("AI Studio was asked %d times, want the one turned away and the one after", u.count())
}
if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
t.Errorf("tried again with %q, want %s", got, skipSignature)
}
nobodyResting(t)
}
// A 400 for a signature is about the request's history, not the account:
// it rests nobody and the group goes on to its next member.
func TestCorruptedSignatureNotTheAccount(t *testing.T) {
if !shapeRefused(http.StatusBadRequest, []byte(studioCorrupted)) {
t.Error("a corrupted signature isn't taken as the request's shape")
}
if !shapeRefused(http.StatusBadRequest, []byte(vertexBadSig)) {
t.Error("an invalid signature isn't taken as the request's shape")
}
fresh(t)
s := New()
c := candidate{p: provider.Provider{ID: "google-aistudio-paid", Key: "k"}, model: "gemini-3.8-flash", rest: "google-aistudio-paid"}
if r := s.restAfter(c, http.StatusBadRequest, http.Header{}, []byte(studioCorrupted)); r.By != "off" || r.Until.After(time.Now()) {
t.Errorf("a corrupted signature rests the account by %q until %v", r.By, r.Until)
}
}
// The same on every client's protocol the gateway translates: Claude
// Code's calls Vertex AI signed reach AI Studio as calls it didn't make.
func TestSignatureGoesOnlyToItsSignerTranslated(t *testing.T) {
limited := false
v := &vertexUp{reply: func(n int, body map[string]any) (int, string) {
if limited {
return http.StatusTooManyRequests, `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
}
return http.StatusOK, vertexCalls
}}
s := vertexServe(t, v, vertexLevels)
u := &studioUp{}
studioServe(t, u)
if err := provider.SaveGroup(provider.Group{Name: "G", Routing: provider.Ordered,
Members: []string{"google-vertex/gemini-3.8-flash", "google-aistudio-paid/gemini-3.8-flash"}}); err != nil {
t.Fatal(err)
}
s = New()
const tools = `"tools":[{"name":"get_weather","input_schema":{"type":"object","properties":{"city":{"type":"string"}}}}]`
out := vertexAsk(t, s, "/v1/messages", `{"model":"group/g","max_tokens":4000,`+tools+`,"messages":[{"role":"user","content":"Weather in Paris and in Tokyo?"}]}`)
ids := vertexCallIDs.FindAllString(out, -1)
if len(ids) < 2 || !strings.Contains(ids[0], sigMark) {
t.Fatalf("Vertex AI's calls came back as %v", ids)
}
ids = []string{ids[0], ids[len(ids)-1]}
limited = true
vertexAsk(t, s, "/v1/messages", `{"model":"group/g","max_tokens":4000,`+tools+`,"messages":[
{"role":"user","content":"Weather in Paris and in Tokyo?"},
{"role":"assistant","content":[
{"type":"tool_use","id":"`+ids[0]+`","name":"get_weather","input":{"city":"Paris"}},
{"type":"tool_use","id":"`+ids[1]+`","name":"get_weather","input":{"city":"Tokyo"}}]},
{"role":"user","content":[
{"type":"tool_result","tool_use_id":"`+ids[0]+`","content":"18C, clear"},
{"type":"tool_result","tool_use_id":"`+ids[1]+`","content":"21C, rain"}]}]}`)
if u.count() != 1 {
t.Errorf("AI Studio was asked %d times, want once", u.count())
}
if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
t.Errorf("AI Studio was sent %q, want %s on the first call", got, skipSignature)
}
nobodyResting(t)
}
// A Gemini client's own history, relayed as it is: a signature another
// provider gave goes as Google's value for calls it didn't make on a call,
// and not at all on text; the provider that gave it gets it as it was.
func TestGeminiBodyKeepsOnlyItsOwn(t *testing.T) {
fresh(t)
const vsig, other = "dmVydGV4LXNpZ25lZA==", "dW5rbm93bi1zaWduZWQ="
noteGeminiSigners([]byte("data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hm\",\"thoughtSignature\":\""+vsig+"\"}]}}]}\r\n\r\n"), "google-vertex")
if got := signerOf(vsig); got != "google-vertex" {
t.Fatalf("signer noted as %q", got)
}
body := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]},{"role":"model","parts":[
{"functionCall":{"name":"f","args":{}},"thoughtSignature":"` + vsig + `"},
{"text":"ok","thoughtSignature":"` + vsig + `"},
{"functionCall":{"name":"g","args":{}},"thoughtSignature":"` + other + `"}]}]}`)
if got := geminiBodySignatures(body, "google-vertex", true); string(got) != string(body) {
t.Errorf("the signer's own body changed:\n%s", got)
}
got := geminiBodySignatures(body, "google", true)
var b struct {
Contents []struct {
Parts []map[string]any `json:"parts"`
} `json:"contents"`
}
if err := json.Unmarshal(got, &b); err != nil || len(b.Contents) != 2 || len(b.Contents[1].Parts) != 3 {
t.Fatalf("%v: %s", err, got)
}
parts := b.Contents[1].Parts
if parts[0]["thoughtSignature"] != skipSignature {
t.Errorf("the call went with %v", parts[0]["thoughtSignature"])
}
if _, ok := parts[1]["thoughtSignature"]; ok {
t.Errorf("the text went with %v", parts[1]["thoughtSignature"])
}
if parts[2]["thoughtSignature"] != other {
t.Errorf("a signature of no known giver went as %v, want as it was", parts[2]["thoughtSignature"])
}
bare := geminiBodySignatures(body, "google-vertex", false)
if strings.Contains(string(bare), vsig) || strings.Contains(string(bare), other) {
t.Errorf("asked again without signatures, still sent some: %s", bare)
}
}
+68
View File
@@ -107,3 +107,71 @@ func pruneSignatures(dir string) {
}
}
}
// Which provider gave a signature (a reply's tool call or text): a
// signature goes back only to the provider that gave it (ownSignatures).
// Vertex AI and AI Studio serve the same Gemini models, and a routing
// group of both falls over from one to the other mid-conversation; the
// other answers a signature it didn't give with 400 "Corrupted thought
// signature" (mimi001234 on Discord). It is kept beside the signature,
// <key>.by, the provider's id in it, keyed by the signature's hash, so
// it reads the same whichever way the signature came back: in a call's
// id, in extra_content, or in a Gemini client's own thoughtSignature.
const signerExt = ".by"
// noteSigner records that provider by gave sig. A record that couldn't
// be written leaves the signature's giver unknown (signerOf).
func noteSigner(sig, by string) {
if sig == "" || by == "" || sig == skipSignature {
return
}
dir := sigDir()
path := filepath.Join(dir, sigKey(sig)+signerExt)
if b, err := os.ReadFile(path); err == nil && string(b) == by {
now := time.Now()
os.Chtimes(path, now, now)
return
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return
}
tmp, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return
}
_, werr := tmp.WriteString(by)
cerr := tmp.Close()
if werr != nil || cerr != nil || os.Rename(tmp.Name(), path) != nil {
os.Remove(tmp.Name())
return
}
pruneSignatures(dir)
}
// signerOf is the id of the provider that gave sig, or "" when magpie
// doesn't know: a signature from before signers were kept, one whose
// record couldn't be written or read, or one a client made up.
func signerOf(sig string) string {
if sig == "" || sig == skipSignature {
return ""
}
path := filepath.Join(sigDir(), sigKey(sig)+signerExt)
b, err := os.ReadFile(path)
if err != nil {
return ""
}
now := time.Now()
os.Chtimes(path, now, now)
return string(b)
}
// foreignSignature says sig is known to come from a provider other than
// by. A signature whose giver isn't known goes as it did before signers
// were kept: dropping it would cost every conversation from before the
// upgrade its signatures on the very provider that gave them, and the
// one that can't read it says so (signatureRefused), which is answered
// by asking again without.
func foreignSignature(sig, by string) bool {
from := signerOf(sig)
return from != "" && from != by
}
+7
View File
@@ -1328,6 +1328,13 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// connection (regionFresh)
return Rest{Why: why, Status: status, By: "off", Until: now}
}
if status == http.StatusBadRequest && signatureRefused.Match(wordsOf(body)) {
// Google turned a thought signature away as one it didn't give
// (signatureRefused): the history's doing, not the account's. A
// group that moved from Vertex AI to AI Studio was refused on every
// account alike (mimi001234); none is set aside
return Rest{Why: why, Status: status, By: "off", Until: now}
}
if status == http.StatusBadGateway && bytes.Contains(body, []byte(openCodeBare)) {
// OpenCode's bare 400 (openCodeBareRefusal, #3740) is about the
// request, not the key: the key's other requests go through, so
+5 -28
View File
@@ -2,7 +2,6 @@ package gateway
import (
"encoding/json"
"regexp"
"slices"
"strings"
)
@@ -123,32 +122,10 @@ func vertexEffort(req *Request, levels []string) *Request {
return &r
}
// vertexSignatureRefused is Vertex AI turning a call's thought signature
// away as one it didn't give: "Invalid thought signature.".
var vertexSignatureRefused = regexp.MustCompile(`(?i)invalid thought signature`)
// withoutSignatures is req with no thought signature on its calls, each of
// which then goes to Vertex AI waved through (skipSignature); false when it
// had none.
// withoutSignatures is req with no Gemini signature on its calls and
// texts, each call then going waved through (skipSignature); false when
// it had none.
func withoutSignatures(req *Request) (*Request, bool) {
had := false
msgs := slices.Clone(req.Messages)
for i, m := range msgs {
if !slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == ToolCall && p.Signature != "" }) {
continue
}
parts := slices.Clone(m.Parts)
for j := range parts {
if parts[j].Kind == ToolCall {
parts[j].Signature = ""
}
}
msgs[i].Parts, had = parts, true
}
if !had {
return req, false
}
r := *req
r.Messages = msgs
return &r, true
r := dropSignatures(req, func(string) bool { return true })
return r, r != req
}