gateway: hash Gemini contents for the session-affinity fallback ID (#165)

* gateway: hash Gemini contents for the session-affinity fallback

Add Contents field to JSON structure and update item selection logic.

* gateway: test conversationID reads Gemini contents

* gateway: test Gemini session affinity keeps the provider key

Add test for Gemini client session affinity behavior.
This commit is contained in:
Charan Rathore
2026-09-29 03:40:00 +08:00
committed by GitHub
parent 3b6ea8b589
commit bdf3d11f50
3 changed files with 56 additions and 0 deletions
+4
View File
@@ -1713,10 +1713,14 @@ func conversationID(in http.Header, body []byte) string {
var m struct {
Messages []json.RawMessage `json:"messages"`
Input json.RawMessage `json:"input"`
Contents []json.RawMessage `json:"contents"`
}
// An undecodable body still gets an id: the hash of the whole body.
_ = json.Unmarshal(body, &m)
items := m.Messages
if len(items) == 0 {
items = m.Contents // Gemini generateContent repeats the first user turn.
}
if len(items) == 0 && len(m.Input) > 0 && m.Input[0] == '[' {
// A malformed input array leaves items empty, and the whole body is hashed.
_ = json.Unmarshal(m.Input, &items)
+8
View File
@@ -931,6 +931,14 @@ func TestConversationID(t *testing.T) {
if r1 != r2 {
t.Errorf("responses ids: %q %q", r1, r2)
}
// Gemini requests have contents, not messages or input. Later turns repeat
// the first user content even as the system instruction and history grow.
g1 := conversationID(http.Header{}, []byte(`{"model":"m","contents":[{"role":"user","parts":[{"text":"fix the bug"}]}]}`))
g2 := conversationID(http.Header{}, []byte(`{"model":"m","systemInstruction":{"parts":[{"text":"help"}]},"contents":[{"role":"user","parts":[{"text":"fix the bug"}]},{"role":"model","parts":[{"text":"done"}]},{"role":"user","parts":[{"text":"thanks"}]}]}`))
gOther := conversationID(http.Header{}, []byte(`{"model":"m","contents":[{"role":"user","parts":[{"text":"write docs"}]}]}`))
if g1 != g2 || g1 == gOther || !strings.HasPrefix(g1, "magpie-") {
t.Errorf("gemini derived ids: %q %q %q", g1, g2, gOther)
}
}
func TestSessionOf(t *testing.T) {
+44
View File
@@ -377,3 +377,47 @@ func TestKeyPoolsByProtocol(t *testing.T) {
t.Fatalf("aside key: %d %s, tried %v", code, body, v.tried)
}
}
// A Gemini client without a recognized session header keeps its provider key
// across turns even when the request's contents, model and instructions grow.
func TestGeminiFallbackSessionAffinity(t *testing.T) {
fresh(t)
v := &geminiKeyed{}
serveOn(t, "aff", "k1", []string{"m"}, v, "k2")
provider.SetAffinity("aff", provider.AffinitySession)
s := New()
for _, body := range []string{
`{"contents":[{"role":"user","parts":[{"text":"fix the bug"}]}]}`,
`{"systemInstruction":{"parts":[{"text":"help"}]},"contents":[{"role":"user","parts":[{"text":"fix the bug"}]},{"role":"model","parts":[{"text":"done"}]},{"role":"user","parts":[{"text":"thanks"}]}]}`,
} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1beta/models/aff/m:generateContent", strings.NewReader(body))
s.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("Gemini request: %d %s", rec.Code, rec.Body.String())
}
}
if len(v.tried) != 2 || v.tried[0] != v.tried[1] {
t.Fatalf("Gemini turns changed key: %v", v.tried)
}
r := s.trace.routes[len(s.trace.routes)-1]
if r.Affinity == nil || !r.Affinity.Kept || r.Affinity.Why != "session" {
t.Fatalf("Gemini turn did not keep session affinity: %+v", r.Affinity)
}
}
// Gemini is translated to a streamed Chat response by the gateway.
type geminiKeyed struct{ tried []string }
func (k *geminiKeyed) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
k.tried = append(k.tried, key)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`data: {"id":"x","choices":[{"delta":{"content":"from `+key+`"}}]}`,
`data: {"id":"x","choices":[{"delta":{},"finish_reason":"stop"}]}`,
`data: {"id":"x","choices":[],"usage":{"prompt_tokens":3000,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":2500}}}`,
`data: [DONE]`,
))
}