Files
magpie/internal/usage/codex_identity_hash_test.go
T
yetone c2c08850f6 usage: a request state hashes Codex's thread identities without encoding them
readRequestState json.Marshal()ed every Codex thread's identity (~20k
over a real history) into a new buffer only to write it into the key's
hash, on every requests page and effort ask: every 15 s poll. They are
now written into the hash directly, each field length-prefixed, in the
order of their keys. The key lives in memory only (the disk index is
keyed by meta), so the changed form costs nothing on upgrade.

Benchmark, 20k identities (a throwaway benchmark, not committed):
json.Marshal + hash 7.06 ms, 6.49 MB, 40012 allocs an ask; now 3.36 ms,
0.36 MB, 3 allocs. In a 12-poll real-history run json.Marshal under
readRequestState was 116 MB.

Test: TestCodexIdentitiesHashed (same identities in another order hash
the same; a thread turning subagent changes it; ab|c is not a|bc; none
is not one). It fails with the length prefixes taken out by hand. The
rest of the package's tests passed with this hash removed altogether:
an identity changes only with a rollout, whose size and time are in the
key too.

Run at this tree: go test ./internal/usage/ ok (8 runs; one earlier run
of this change printed a bare FAIL whose test I lost to a tail, not
seen again in 8 package runs and 30 of the effort tests); gofmt -l
clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui
./internal/usage ok.
2026-10-27 08:04:30 +08:00

47 lines
1.5 KiB
Go

package usage
import (
"crypto/sha256"
"fmt"
"testing"
"github.com/yetone/magpie/internal/sessions"
)
// A request state's key changes with any thread's identity, and only with
// one: the same identities give the same key however the map was filled,
// and a field's end is not read as the next one's start.
func TestCodexIdentitiesHashed(t *testing.T) {
sum := func(ids map[string]sessions.CodexIdentity) string {
h := sha256.New()
hashCodexIdentities(h, ids)
return fmt.Sprintf("%x", h.Sum(nil))
}
many := func(n int, from int) map[string]sessions.CodexIdentity {
ids := map[string]sessions.CodexIdentity{}
for i := range n { // more than one write's worth
k := fmt.Sprintf("019a%028d", (i+from)%n)
ids[k] = sessions.CodexIdentity{ID: k, Role: "main", RootSession: k}
}
return ids
}
base := sum(many(5000, 0))
if got := sum(many(5000, 1234)); got != base {
t.Fatal("the same identities, filled in another order, hashed apart")
}
child := many(5000, 0)
k := fmt.Sprintf("019a%028d", 4321)
child[k] = sessions.CodexIdentity{ID: k, Role: "subagent", ParentSession: "p", RootSession: "p"}
if sum(child) == base {
t.Fatal("a thread that became a subagent left the key as it was")
}
a := map[string]sessions.CodexIdentity{"t": {ID: "ab", Role: "c"}}
b := map[string]sessions.CodexIdentity{"t": {ID: "a", Role: "bc"}}
if sum(a) == sum(b) {
t.Fatal("fields run together: ab|c hashed as a|bc")
}
if sum(nil) == sum(a) {
t.Fatal("no identities hashed as one")
}
}