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) + } +}