From cbfbcb383b3d36ecd0f2b8aa53e186560244d402 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 18:33:49 +0800 Subject: [PATCH] usage: a lead's answers are looked up in the blocks that name its conversation (#4370) loggedAnswers, which leadFirst falls back to when affinity has lost a Codex subagent's lead, read thirty days of the log into a Record a row and kept the rows of one conversation. usage.VisitSessions reads only those rows: a block whose Session and NativeSession strings don't name the conversation is skipped, a row of another session is passed over by its shape's string ids without becoming a Record, and a matched row's strings are cloned out of the lent decode buffer. Each packed block's sessions are kept once it is decoded (blockSessions, by weak pointer, so no block the log let go is held), so a lookup decodes only the blocks the conversation is in and the open tail. A page's copy with Codex identities (which rewrite Session as a row is read) is read whole and filtered on its records. Run on mote (macOS 27.2), at load ~70: - BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300): visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and 12KB. - A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions, 18 blocks): every session looked up both ways gives the same records; 6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for a conversation that isn't there. - TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions, red with the known-sessions skip taken out. - GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean. - go test -race of the new tests and the gateway tests of a lead's answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s). - go test ./internal/usage ./internal/gateway (whole packages) was still running on mote at load ~190 when this was pushed; its result goes on #4370. Not tried: a real Codex subagent whose lead lost affinity; the lookup's callers and filters are as they were, and the gateway's loggedAnswers tests cover them. --- internal/gateway/codex_backend.go | 5 +- internal/usage/ledger.go | 6 ++ internal/usage/log_index.go | 118 ++++++++++++++++++++++++ internal/usage/visit_sessions_test.go | 126 ++++++++++++++++++++++++++ 4 files changed, 251 insertions(+), 4 deletions(-) create mode 100644 internal/usage/visit_sessions_test.go diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 29d9c499a..a1fbbfe46 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -467,7 +467,7 @@ func loggedAnswers(convs ...string) []loggedAnswer { // its candidates have (cybercaius: a renamed provider was told apart // from itself) renamed := provider.UsageRenames() - usage.Visit(time.Now().Add(-sealerKeep), func(r usage.Record) { + usage.VisitSessions(time.Now().Add(-sealerKeep), convs, func(r usage.Record) { // the provider that answered, not one a deleted provider's // calls were merged into on the Usage page (Renames.Own) r.Provider = renamed.Own(r.Provider, r.Time) @@ -480,9 +480,6 @@ func loggedAnswers(convs ...string) []loggedAnswer { if ownRelay && strings.HasPrefix(r.Endpoint, CodexPath) { return // Codex's own sign-in } - if !slices.Contains(convs, r.NativeSession) && !slices.Contains(convs, r.Session) { - return - } a := loggedAnswer{provider: r.Provider, at: r.Time} switch { case r.ProviderAccount != "": diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 7fbfac6a7..1efdc06c8 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -1166,6 +1166,12 @@ func ledgerSeriesAt(p Period, rows []Row, now time.Time) (bucket string, pts []S // does so itself). func Visit(since time.Time, fn func(Record)) { readLogSnapshot().visit(since, fn) } +// VisitSessions is Visit for the records whose Session or NativeSession +// is one of sessions, read without making a Record of any other. +func VisitSessions(since time.Time, sessions []string, fn func(Record)) { + readLogSnapshot().visitSessions(since, sessions, fn) +} + // NewCoster prices one record at a time at the effective prices the // ledger uses, read once: its cost in USD, and false for a call with // tokens but no known price. diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go index 1e3f32228..dbe5693bf 100644 --- a/internal/usage/log_index.go +++ b/internal/usage/log_index.go @@ -17,6 +17,7 @@ import ( "strings" "sync" "time" + "weak" ) const ( @@ -320,6 +321,123 @@ func visitBlocks(blocks []*rowChunk, since time.Time, fn func(Record)) { } } +// rowSession and rowNativeSession are the Text slots of a row's session +// and its agent's own conversation id (rowText) +const ( + rowSession = 13 + rowNativeSession = 14 +) + +// visitSessions is visit for the rows of the sessions named, by Session +// or NativeSession: a row of another session is passed over by its +// strings' ids, never made a Record. Codex's lead lookup read thirty +// days of the log into a Record a row, for every request a subagent +// sent (#4370). +func (s *logSnapshot) visitSessions(since time.Time, sessions []string, fn func(Record)) { + if len(sessions) == 0 { + return + } + rows := lentRows() // a matched row's strings are cloned + defer rows.release() + var ids []uint32 + var shapes []bool + for _, packed := range s.blocks { + if !since.IsZero() && packed.Latest.Before(since) { + continue + } + if known, ok := blockSessions.of(packed); ok && !slices.ContainsFunc(sessions, func(s string) bool { _, in := known[s]; return in }) { + continue + } + if sessionsDecoding != nil { + sessionsDecoding() + } + c := rows.of(packed) + blockSessions.learn(packed, c) + // a row a Codex identity names is told its root session as it is + // read (codexIdentityRow): only a page's copies have them + named := c.codexIdentities != nil + ids = ids[:0] + for id, str := range c.Strings { + if id != 0 && slices.Contains(sessions, str) { + ids = append(ids, uint32(id)) + } + } + if len(ids) == 0 && !named { + continue + } + shapes = slices.Grow(shapes[:0], len(c.Shapes))[:len(c.Shapes)] + for k, t := range c.Shapes { + shapes[k] = named || slices.Contains(ids, t[rowSession]) || slices.Contains(ids, t[rowNativeSession]) + } + for i := range c.Rows { + p := &c.Rows[i] + if int(p.Shape) >= len(shapes) || !shapes[p.Shape] || p.Time().Before(since) { + continue + } + r := c.row(i) + if named && !slices.Contains(sessions, r.Session) && !slices.Contains(sessions, r.NativeSession) { + continue + } + for _, str := range rowText(&r) { + *str = strings.Clone(*str) + } + fn(r.Record) + } + } +} + +// blockSessions are the sessions each packed block's rows name, by +// Session or NativeSession, so a lookup of a session decodes only the +// blocks it is in: decoding every block of a month for each of a +// subagent's requests still took ~20ms (#4370). A packed block isn't +// written again. A block is known by a weak pointer, so the map keeps no +// block the log has let go (a tail block is packed anew as calls come +// in); their entries go when it has 4096. +var blockSessions sessionsByBlock + +// sessionsDecoding, in tests, is told each block visitSessions decodes. +var sessionsDecoding func() + +type sessionsByBlock struct { + sync.Mutex + m map[weak.Pointer[rowChunk]]map[string]struct{} +} + +func (b *sessionsByBlock) of(c *rowChunk) (map[string]struct{}, bool) { + if len(c.Archive) == 0 || c.codexIdentities != nil { + return nil, false + } + b.Lock() + defer b.Unlock() + known, ok := b.m[weak.Make(c)] + return known, ok +} + +// learn keeps the sessions of packed, open being its rows +func (b *sessionsByBlock) learn(packed, open *rowChunk) { + if len(packed.Archive) == 0 || packed.codexIdentities != nil { + return + } + known := map[string]struct{}{} + for _, t := range open.Shapes { + for _, slot := range [...]int{rowSession, rowNativeSession} { + if t[slot] != 0 { + if s := open.Strings[t[slot]]; s != "" { + if _, in := known[s]; !in { + known[strings.Clone(s)] = struct{}{} + } + } + } + } + } + b.Lock() + defer b.Unlock() + if b.m == nil || len(b.m) >= 4096 { + b.m = map[weak.Pointer[rowChunk]]map[string]struct{}{} + } + b.m[weak.Make(packed)] = known +} + func (c *rowChunk) writable() *rowChunk { d := c.unpack() if d == nil { diff --git a/internal/usage/visit_sessions_test.go b/internal/usage/visit_sessions_test.go new file mode 100644 index 000000000..4cf6d90f9 --- /dev/null +++ b/internal/usage/visit_sessions_test.go @@ -0,0 +1,126 @@ +package usage + +import ( + "fmt" + "slices" + "testing" + "time" +) + +// sessionChunks are benchChunks with a row in every tenth told its +// agent's own conversation id, "conv-". +func sessionChunks(t testing.TB, n, size int) []*rowChunk { + t.Helper() + at := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + var chunks []*rowChunk + for k := range n { + c := &rowChunk{} + for i := range size { + at = at.Add(time.Second) + r := Record{Time: at, Agent: "codex", Provider: fmt.Sprint("p", k%3), Model: "gpt-5", Input: i, Session: fmt.Sprint("s", k), RequestID: fmt.Sprint("req-", k, "-", i)} + if i%10 == 0 { + r.NativeSession = fmt.Sprint("conv-", k) + } + c.add(Row{Record: r}, fmt.Sprint("resp-", k, "-", i), int64(i), false) + } + packed := c.pack() + if len(packed.Archive) == 0 { + t.Fatal("not packed") + } + chunks = append(chunks, packed) + } + return chunks +} + +// visitSessions hands on the records visit does whose Session or +// NativeSession is named, from since on, and nothing else. +func TestVisitSessionsIsVisitOfThoseSessions(t *testing.T) { + s := &logSnapshot{blocks: sessionChunks(t, 12, 200)} + since := s.blocks[3].Latest.Add(-50 * time.Second) + // twice: the second pass reads only the blocks it learnt name them + cases := [][]string{{"s5"}, {"conv-7"}, {"s4", "conv-9", "nobody"}, {"s3"}, {"nobody"}, {""}} + for _, named := range append(cases, cases...) { + var want, got []Record + s.visit(since, func(r Record) { + if r.Session != "" && slices.Contains(named, r.Session) || r.NativeSession != "" && slices.Contains(named, r.NativeSession) { + want = append(want, r) + } + }) + s.visitSessions(since, named, func(r Record) { got = append(got, r) }) + if len(got) != len(want) { + t.Fatalf("%q: %d records, want %d", named, len(got), len(want)) + } + for i := range want { + if got[i].RequestID != want[i].RequestID || !got[i].Time.Equal(want[i].Time) || got[i].Provider != want[i].Provider { + t.Fatalf("%q record %d: %+v, want %+v", named, i, got[i], want[i]) + } + } + } +} + +// A record visitSessions hands on keeps its strings after the next +// block is decoded over the one it came from. +func TestVisitSessionsRecordsKeepTheirStrings(t *testing.T) { + s := &logSnapshot{blocks: sessionChunks(t, 6, 300)} + var got []Record + s.visitSessions(time.Time{}, []string{"conv-0", "conv-1", "conv-2", "conv-3", "conv-4", "conv-5"}, func(r Record) { got = append(got, r) }) + if len(got) != 6*30 { + t.Fatalf("%d records, want %d", len(got), 6*30) + } + for i, r := range got { + k, n := i/30, i%30*10 + if r.RequestID != fmt.Sprint("req-", k, "-", n) || r.NativeSession != fmt.Sprint("conv-", k) || r.Session != fmt.Sprint("s", k) { + t.Fatalf("record %d reads %q %q %q after the blocks after it were decoded", i, r.RequestID, r.NativeSession, r.Session) + } + } +} + +// BenchmarkLeadLookup is Codex's lead lookup over a month's log: every +// record, then the ones of one conversation, against those alone (#4370). +func BenchmarkLeadLookup(b *testing.B) { + s := &logSnapshot{blocks: sessionChunks(b, 40, 3000)} + conv := []string{"conv-17"} + b.Run("visit", func(b *testing.B) { + b.ReportAllocs() + for range b.N { + n := 0 + s.visit(time.Time{}, func(r Record) { + if slices.Contains(conv, r.NativeSession) || slices.Contains(conv, r.Session) { + n++ + } + }) + if n != 300 { + b.Fatal(n) + } + } + }) + b.Run("visitSessions", func(b *testing.B) { + b.ReportAllocs() + for range b.N { + n := 0 + s.visitSessions(time.Time{}, conv, func(Record) { n++ }) + if n != 300 { + b.Fatal(n) + } + } + }) +} + +// A block that names none of the sessions looked up is not decoded once +// its sessions are known. +func TestVisitSessionsSkipsBlocksOfOtherSessions(t *testing.T) { + s := &logSnapshot{blocks: sessionChunks(t, 20, 2000)} + decoded := 0 + sessionsDecoding = func() { decoded++ } + t.Cleanup(func() { sessionsDecoding = nil }) + s.visitSessions(time.Time{}, []string{"nobody"}, func(Record) {}) + if decoded != 20 { + t.Fatalf("the first lookup decoded %d blocks of 20", decoded) + } + decoded = 0 + n := 0 + s.visitSessions(time.Time{}, []string{"conv-19", "nobody"}, func(Record) { n++ }) + if decoded != 1 || n != 200 { + t.Fatalf("a lookup of one block's conversation decoded %d blocks of 20 and read %d records, want 1 and 200", decoded, n) + } +}