affinity: a Claude Code subagent's answer no longer moves its lead off its account's cache

Claude Code sends its session's id (x-claude-code-session-id) with every
request of the session, its subagents' too; only x-claude-code-agent-id
says a request is a subagent's. Affinity kept one stick per scope and
session, so a subagent on the lead's model wrote its own answer over the
lead's stick. The lead's next turn was then judged by the subagent's cache
("no-cache" for a small one, "cold" for a 5-minute write past five
minutes) or kept wherever the subagent had gone, and with two Claude
accounts it moved to the other one: a new Claude Code there was told the
whole conversation and Anthropic wrote it all to that account's cache
again, at the 1-hour write price (slkassinthehood on X: two Pro accounts'
5 hours spent in ten minutes, ~318k tokens a request).

stickKey keeps a subagent's stick apart, by its agent id. The lead's key
is the session's, as before: sticks on disk are found after the upgrade,
and Codex's leadFirst, which reads a lead's stick by its thread id, is
unchanged. strictKeep reads the same key.

Run, at this commit's tree (base 42ec2700b):
- TestClaudeConversationKeepsItsAccountsCache: two Claude accounts (fake
  Claude Code reporting a 300k 1-hour write), least-used routing, a lead
  conversation through the gateway with Claude Code's headers. Red on the
  old affinity.go: after a subagent's turn the lead was answered by tok-b
  in a new Claude Code, logged "a new Claude Code is told the whole
  conversation: 7 messages"; also red 20 minutes on. Green with the fix:
  the lead stays on tok-a, in the same Claude Code, every step.
- go vet -tags nogui ./internal/gateway/
- go test -tags nogui ./internal/gateway/ -run
  'Affinity|TestClaude|Strict|Rotate|Codex.*Lead|LeadFirst|Subagent|HourCache': ok
- Full suite (go test -tags nogui ./... -timeout 45m, suite-lock, sandbox
  HOME, at 5e566f0c3 on base 42ec2700b): 70 packages ok, internal/gateway
  ok (675s); internal/provider FAIL: "close of synctest channel from
  outside bubble" in filememo.Forget under
  TestUnreadLoginsWriteErrorsKeepCredentials, red on main since 091153bf
  and filed as #3632. Not touched by this change.
- After rebasing onto origin/main 5214d5114 (the two claude bridge fixes):
  gofmt -l, go vet and go test -tags nogui -timeout 45m ./internal/gateway/
  at cf69f883b's tree: ok (419s).

Not tried: the reporter's own accounts and client; whether their lead
moved this way is not known from their screenshot (it shows the hour's
total, not reads against writes).
This commit is contained in:
yetone
2026-10-26 02:21:36 +08:00
parent 722483c089
commit 3b717d5e0d
3 changed files with 170 additions and 3 deletions
File diff suppressed because one or more lines are too long
+22 -2
View File
@@ -378,7 +378,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate,
return cs, pl, nil
}
sticks.Lock()
st, had := stickOf(scope + "|" + conversationID(in, body))
st, had := stickOf(stickKey(scope, in, body))
sticks.Unlock()
if !had || time.Since(st.at) > stickKeep || slices.ContainsFunc(cs, func(c candidate) bool { return c.who() == st.who }) {
return cs, pl, nil
@@ -452,6 +452,26 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {
return out, pl
}
// stickKey is the conversation a stick is kept for: scope's, by the
// conversation's id, and a Claude Code subagent's apart from its lead's.
// Claude Code sends its session's id with every request of the session,
// its subagents' too, which say only by x-claude-code-agent-id that they
// are one (subagentOf). Under the session's key, a subagent's answer took
// the lead's stick over: the lead's next turn was judged by the cache of
// the subagent's conversation, moved to another account as "no-cache" or
// "cold" or to wherever the subagent had gone, and the lead's whole
// conversation written to that account's cache again (slkassinthehood on
// X: two Pro accounts' 5 hours spent in ten minutes). The lead's key is
// the session's as before, so what is kept of it, and Codex's leadFirst,
// which reads a lead's stick by its thread id, are as they were.
func stickKey(scope string, in http.Header, body []byte) string {
key := scope + "|" + conversationID(in, body)
if sub := subOf(in); sub != "" {
key += "|agent:" + sub
}
return key
}
// affine puts first whoever answered the conversation last, while its
// affinity says to keep it there. Its turn is counted in written, the body
// as the agent wrote it, which the turn's folder is read from too
@@ -459,7 +479,7 @@ func strictOnly(cs []candidate, pl planned, at int) ([]candidate, planned) {
// it in the masked body parsed the conversation a second time, ~27 MB
// more for each 4 MB Codex request in flight.
func affine(scope, mode string, rotate bool, in http.Header, from provider.Protocol, body, written []byte, cs []candidate, pl planned) ([]candidate, planned, *Affinity, string) {
key := scope + "|" + conversationID(in, body)
key := stickKey(scope, in, body)
a := &Affinity{Mode: mode}
a.Turn, a.Within = turnOf(from, written)
sticks.Lock()
@@ -0,0 +1,147 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// claudeCaching has the fake Claude Code of claudeMadeFirst answer on both
// accounts, each healthy, and report its prompt cache as Claude Code's
// stream does for a subscription: the conversation written for an hour.
// A turn whose text holds SMALL reports a small, 5-minute write only.
func claudeCaching(t *testing.T) {
t.Helper()
claudeMadeFirst(t, false)
reset := strconv.FormatInt(time.Now().Add(3*time.Hour).Unix(), 10)
script := `#!/bin/sh
case "$1" in auth) exit 1;; esac
creds="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json"
if [ "$2" = "/usage" ]; then
echo '{"type":"result","is_error":false,"result":"Current session: 10% used"}'
exit 0
fi
n=0
while read -r line; do
case $line in *'"type":"control_request"'*)
id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/')
echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}'
continue ;;
esac
n=$((n+1))
tok=$(grep -o 'tok-[a-z]*' "$creds" | head -1)
usage='"input_tokens":5,"cache_read_input_tokens":20000,"cache_creation_input_tokens":300000,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":300000}'
case $line in *SMALL*) usage='"input_tokens":5,"cache_read_input_tokens":0,"cache_creation_input_tokens":300' ;; esac
echo '{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","rateLimitType":"five_hour","utilization":0.1,"resetsAt":` + reset + `}}'
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-opus-5-5","usage":{'"$usage"'}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'$tok' pid '$$' turn '$n'"}}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
done
`
bin := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator))[0]
testenv.Program(t, filepath.Join(bin, "claude"), script)
}
// A conversation on one of two Claude accounts goes on on that account, in
// the Claude Code that had its last turn, so Anthropic's cache of it — the
// account's own — is read again rather than the whole conversation written
// on the other account (slkassinthehood on X: two Pro accounts' 5 hours
// spent in ten minutes).
func TestClaudeConversationKeepsItsAccountsCache(t *testing.T) {
claudeCaching(t)
restingUntil.Lock()
restingUntil.m = map[string]time.Time{}
restingUntil.Unlock()
p, err := provider.Find("claude")
if err != nil {
t.Fatal(err)
}
p.Routing = provider.LeastUsed
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
s := New()
t.Cleanup(s.subscription.abortAll)
h := s.Handler()
sendAs := func(session, agent, msgs string) string {
t.Helper()
body := `{"model":"claude/claude-opus-5-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}`
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
r.Header.Set("x-claude-code-session-id", session)
if agent != "" {
// as Claude Code marks a subagent's requests; its lead's carry none
r.Header.Set("x-claude-code-agent-id", agent)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
var res struct {
Content []struct{ Text string } `json:"content"`
}
json.Unmarshal(rec.Body.Bytes(), &res)
if rec.Code != 200 || len(res.Content) == 0 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
a := s.trace.routes[len(s.trace.routes)-1].Affinity
t.Logf("%q affinity %+v", res.Content[0].Text, a)
return res.Content[0].Text
}
send := func(msgs string) string { t.Helper(); return sendAs("s-1", "", msgs) }
msg := func(role, text string) string { return `{"role":"` + role + `","content":` + strconv.Quote(text) + `}` }
age := func(d time.Duration) {
sticks.Lock()
for k, st := range sticks.m {
st.at = st.at.Add(-d)
if !st.hour.at.IsZero() {
st.hour.at = st.hour.at.Add(-d)
}
sticks.m[k] = st
}
sticks.Unlock()
}
who := func(reply string) string { tok, _, _ := strings.Cut(reply, " pid"); return tok }
run := func(reply string) string {
_, rest, _ := strings.Cut(reply, " pid ")
p, _, _ := strings.Cut(rest, " ")
return p
}
conv := msg("user", "lead: fix the bug")
first := send(`[` + conv + `]`)
conv += `,` + msg("assistant", first)
// a new conversation goes to the account that has served less
if got := sendAs("s-2", "", `[`+msg("user", "SMALL another session")+`]`); who(got) == who(first) {
t.Fatalf("a new conversation went to %q, not the less used account", got)
}
for i, step := range []struct {
name string
do func()
}{
{"next turn", func() {}},
{"after 20 minutes", func() { age(20 * time.Minute) }},
{"after a sub-agent on the same model and session", func() {
sendAs("s-1", "agent-1", `[`+msg("user", "SMALL subagent: look around")+`]`)
}},
{"after a sub-agent, 20 minutes on", func() {
sendAs("s-1", "agent-2", `[`+msg("user", "SMALL subagent: look again")+`]`)
age(20 * time.Minute)
}},
} {
step.do()
conv += `,` + msg("user", "and "+strconv.Itoa(i))
got := send(`[` + conv + `]`)
if who(got) != who(first) || run(got) != run(first) {
t.Errorf("%s: answered %q, the conversation began as %q: moved off its cache", step.name, got, first)
}
conv += `,` + msg("assistant", got)
}
}