usage: the Requests page reads packed chunks in place, and owns its strings
The first Requests page after a start unpacked every local and shared chunk whole and held them all while it built the page, so a cold page on the owner's real usage peaked at ~450-480 MB footprint (#3493 follow-up: "发版后把 RSS 峰值也修了"). queryPage now keeps chunks packed. visibleLocal, matchedBlocks, the Codex identity fold, the chart and rowsOf read a packed chunk through chunkRows, a one-entry cache that decodes into one reused buffer. The Codex response pairs are read per chunk (codexChunkResponsePairs), and pack records Count so a packed chunk's length is known without a decode. An unpacked block's strings are substrings of one text, so a row or name the page kept would hold that whole block (~9 MB, kept by the request cache): buildRequestBlocksWithCodex now copies every string of the finished page (ownStrings). Measured (owner's real usage copied into a sandbox HOME, warm caches, first /v1/magpie/requests page, base =2009d33a6): - peak footprint 452-481 MB -> 351-389 MB; peak RSS 577-616 -> ~495-505 - live heap at 6s ~306 MB -> 203-229 MB - settled footprint 246 -> 226-239 MB; settled live heap 142-143 -> 147-148.6 MB. ~4 MB of one block's text is still held from the chart loop; its holder wasn't found (keyer, Row fields, Locations, EffortFamily ruled out). Cloning every chart row reached 143.8 MB but costs CPU per row, so it was left out. - process CPU over 15s: 8.25/8.35s -> 9.29/11.65s at load 77-95; the profile puts most of it in syscalls and CodexModelEffort's reads, and the page's own work at queryPage 1.61 -> 1.97s, unpackInto 0.17s. Tests: TestRequestPageSameFromPackedLocalChunks builds the same page from packed and unpacked chunks (Codex pairs, compactions, actors, Claude duplicates, request-id and fallback matches); red with chunkRows' cache never refreshed (r.c == nil) and with an empty decode. TestRequestPageOwnsItsStrings is red with ownStrings' clone removed. Run: go test -tags nogui -timeout 45m -count=1 ./internal/usage ./internal/gui ./internal/gateway ok at this head (gateway run after rebase onto3133f6343); gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage ok. Not run: the full ./... suite (other sessions' suites are on this machine).
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"hash/maphash"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -179,104 +180,168 @@ func cloneCodexChunks(chunks []*rowChunk) []*rowChunk {
|
||||
return out
|
||||
}
|
||||
|
||||
func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[rowRef]bool) map[rowRef]rowRef {
|
||||
gatewayIDs := map[string][]rowRef{}
|
||||
// rowResponseID is rowText's slot of Record.ResponseID.
|
||||
const rowResponseID = 25
|
||||
|
||||
// codexChunkResponsePairs are the Codex calls the gateway and a session file
|
||||
// both name by one response id, gateway to local, and each local call's
|
||||
// compaction. Only the ids the gateway names are kept of the locals': a map
|
||||
// of every Codex call's id held each decoded chunk's strings.
|
||||
func codexChunkResponsePairs(gateways, locals []*rowChunk, duplicateLocal map[rowRef]bool) (map[rowRef]rowRef, map[rowRef]*bool) {
|
||||
type pick struct {
|
||||
gateways, locals int
|
||||
gateway, local rowRef
|
||||
gatewayOK, localOK bool
|
||||
compaction *bool
|
||||
}
|
||||
picks := map[string]*pick{}
|
||||
var rows chunkRows
|
||||
for _, chunk := range gateways {
|
||||
for i := range chunk.Rows {
|
||||
row := chunk.row(i)
|
||||
if row.ResponseID != "" {
|
||||
gatewayIDs[row.ResponseID] = append(gatewayIDs[row.ResponseID], rowRef{chunk, i})
|
||||
open := rows.of(chunk)
|
||||
for i := range open.Rows {
|
||||
if open.text(&open.Rows[i], rowResponseID) == 0 {
|
||||
continue
|
||||
}
|
||||
row := open.row(i)
|
||||
p := picks[row.ResponseID]
|
||||
if p == nil {
|
||||
p = &pick{}
|
||||
picks[row.ResponseID] = p
|
||||
}
|
||||
p.gateways++
|
||||
p.gateway = rowRef{chunk, i}
|
||||
p.gatewayOK = isCodexRow(row) && !row.IsRejected() && row.Source != SourceReported
|
||||
}
|
||||
}
|
||||
localIDs := map[string][]rowRef{}
|
||||
for _, chunk := range locals {
|
||||
for i := range chunk.Rows {
|
||||
open := rows.of(chunk)
|
||||
for i := range open.Rows {
|
||||
ref := rowRef{chunk, i}
|
||||
if duplicateLocal[ref] {
|
||||
continue
|
||||
}
|
||||
row := chunk.row(i)
|
||||
if row.ResponseID != "" {
|
||||
localIDs[row.ResponseID] = append(localIDs[row.ResponseID], ref)
|
||||
p := picks[open.Strings[open.text(&open.Rows[i], rowResponseID)]]
|
||||
if p == nil {
|
||||
continue
|
||||
}
|
||||
row := open.row(i)
|
||||
p.locals++
|
||||
p.local = ref
|
||||
p.localOK = isCodexRow(row) && row.Source == "log"
|
||||
p.compaction = row.Compaction
|
||||
}
|
||||
}
|
||||
pairs := map[rowRef]rowRef{}
|
||||
for id, gatewayRefs := range gatewayIDs {
|
||||
localRefs := localIDs[id]
|
||||
if len(gatewayRefs) != 1 || len(localRefs) != 1 {
|
||||
continue
|
||||
}
|
||||
gateway, local := gatewayRefs[0], localRefs[0]
|
||||
gatewayRow, localRow := gateway.row(), local.row()
|
||||
if isCodexRow(gatewayRow) && !gatewayRow.IsRejected() && gatewayRow.Source != SourceReported && isCodexRow(localRow) && localRow.Source == "log" {
|
||||
pairs[gateway] = local
|
||||
pairs, compactions := map[rowRef]rowRef{}, map[rowRef]*bool{}
|
||||
for _, p := range picks {
|
||||
if p.gateways == 1 && p.locals == 1 && p.gatewayOK && p.localOK {
|
||||
pairs[p.gateway] = p.local
|
||||
compactions[p.local] = p.compaction
|
||||
}
|
||||
}
|
||||
return pairs
|
||||
return pairs, compactions
|
||||
}
|
||||
|
||||
func foldCodexRows(locals []*rowChunk) map[rowRef]bool {
|
||||
localIDs := map[string][]rowRef{}
|
||||
// The calls are found by a hash of their response id, not the id: a map
|
||||
// keyed by every Codex call's id held each decoded chunk's strings. Calls
|
||||
// whose hash is the same are told apart by their ids after.
|
||||
seed := maphash.MakeSeed()
|
||||
first := map[uint64]rowRef{}
|
||||
again := map[uint64][]rowRef{}
|
||||
var rows chunkRows
|
||||
for _, chunk := range locals {
|
||||
for i := range chunk.Rows {
|
||||
row := chunk.row(i)
|
||||
if isCodexRow(row) && row.Source == "log" && row.ResponseID != "" {
|
||||
localIDs[row.ResponseID] = append(localIDs[row.ResponseID], rowRef{chunk, i})
|
||||
open := rows.of(chunk)
|
||||
for i := range open.Rows {
|
||||
id := open.Strings[open.text(&open.Rows[i], rowResponseID)]
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if row := open.row(i); !isCodexRow(row) || row.Source != "log" {
|
||||
continue
|
||||
}
|
||||
ref, h := rowRef{chunk, i}, maphash.String(seed, id)
|
||||
if f, ok := first[h]; !ok {
|
||||
first[h] = ref
|
||||
} else {
|
||||
if again[h] == nil {
|
||||
again[h] = []rowRef{f}
|
||||
}
|
||||
again[h] = append(again[h], ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
var refs []rowRef
|
||||
for _, hashed := range again {
|
||||
refs = append(refs, hashed...)
|
||||
}
|
||||
read := rowsOf(locals, refs)
|
||||
skip := map[rowRef]bool{}
|
||||
for _, refs := range localIDs {
|
||||
if len(refs) < 2 {
|
||||
continue
|
||||
}
|
||||
actors := make([]string, len(refs))
|
||||
rows := make([]Row, len(refs))
|
||||
identical := true
|
||||
actor := ""
|
||||
actorConflict := false
|
||||
for i, ref := range refs {
|
||||
rows[i] = ref.row()
|
||||
if ref.Index < len(ref.Chunk.codexActors) {
|
||||
actors[i] = ref.Chunk.codexActors[ref.Index]
|
||||
}
|
||||
if i == 0 {
|
||||
actor = actors[i]
|
||||
} else {
|
||||
if actors[i] != actor {
|
||||
actorConflict = true
|
||||
}
|
||||
if !sameCodexCall(rows[0], rows[i]) {
|
||||
identical = false
|
||||
}
|
||||
for _, hashed := range again {
|
||||
byID := map[string][]rowRef{}
|
||||
var ids []string
|
||||
for _, ref := range hashed {
|
||||
id := read[ref].ResponseID
|
||||
if byID[id] == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
byID[id] = append(byID[id], ref)
|
||||
}
|
||||
if !identical {
|
||||
for _, ref := range refs {
|
||||
setCodexActor(ref.Chunk, ref.Index, "")
|
||||
}
|
||||
continue
|
||||
for _, id := range ids {
|
||||
foldCodexCall(byID[id], read, skip)
|
||||
}
|
||||
if actorConflict {
|
||||
setCodexActor(refs[0].Chunk, refs[0].Index, "")
|
||||
}
|
||||
for _, ref := range refs[1:] {
|
||||
skip[ref] = true
|
||||
}
|
||||
compactions := make([]*bool, len(refs))
|
||||
for i := range refs {
|
||||
compactions[i] = rows[i].Compaction
|
||||
}
|
||||
refs[0].Chunk.setCodexCompaction(refs[0].Index, mergeCodexCompactions(compactions))
|
||||
}
|
||||
return skip
|
||||
}
|
||||
|
||||
// foldCodexCall keeps the first of refs, the calls a session file names by
|
||||
// one response id, and skips the rest when they are the same call.
|
||||
func foldCodexCall(refs []rowRef, read map[rowRef]Row, skip map[rowRef]bool) {
|
||||
if len(refs) < 2 {
|
||||
return
|
||||
}
|
||||
actors := make([]string, len(refs))
|
||||
rows := make([]Row, len(refs))
|
||||
identical := true
|
||||
actor := ""
|
||||
actorConflict := false
|
||||
for i, ref := range refs {
|
||||
rows[i] = read[ref]
|
||||
if ref.Index < len(ref.Chunk.codexActors) {
|
||||
actors[i] = ref.Chunk.codexActors[ref.Index]
|
||||
}
|
||||
if i == 0 {
|
||||
actor = actors[i]
|
||||
} else {
|
||||
if actors[i] != actor {
|
||||
actorConflict = true
|
||||
}
|
||||
if !sameCodexCall(rows[0], rows[i]) {
|
||||
identical = false
|
||||
}
|
||||
}
|
||||
}
|
||||
if !identical {
|
||||
for _, ref := range refs {
|
||||
setCodexActor(ref.Chunk, ref.Index, "")
|
||||
}
|
||||
return
|
||||
}
|
||||
if actorConflict {
|
||||
setCodexActor(refs[0].Chunk, refs[0].Index, "")
|
||||
}
|
||||
for _, ref := range refs[1:] {
|
||||
skip[ref] = true
|
||||
}
|
||||
compactions := make([]*bool, len(refs))
|
||||
for i := range refs {
|
||||
compactions[i] = rows[i].Compaction
|
||||
}
|
||||
refs[0].Chunk.setCodexCompaction(refs[0].Index, mergeCodexCompactions(compactions))
|
||||
}
|
||||
|
||||
func setCodexActor(chunk *rowChunk, index int, actor string) {
|
||||
if len(chunk.codexActors) != len(chunk.Rows) {
|
||||
actors := make([]string, len(chunk.Rows))
|
||||
if n := rowsIn(chunk); len(chunk.codexActors) != n {
|
||||
actors := make([]string, n)
|
||||
copy(actors, chunk.codexActors)
|
||||
chunk.codexActors = actors
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ func directRows(p Period, now time.Time) []Row {
|
||||
}
|
||||
}
|
||||
duplicates := foldCodexRows([]*rowChunk{local})
|
||||
pairs := codexChunkResponsePairs(gateways, []*rowChunk{local}, duplicates)
|
||||
pairs, _ := codexChunkResponsePairs(gateways, []*rowChunk{local}, duplicates)
|
||||
for ref := range matchedBlocks(gateways, []*rowChunk{local}, duplicates, pairs, since, false) {
|
||||
matched[ref.Index] = true
|
||||
}
|
||||
|
||||
+203
-70
@@ -14,6 +14,7 @@ import (
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -345,11 +346,24 @@ type rowRef struct {
|
||||
Index int
|
||||
}
|
||||
|
||||
func (r rowRef) row() Row { return r.Chunk.row(r.Index) }
|
||||
func (r rowRef) at() time.Time { return r.Chunk.Rows[r.Index].Time }
|
||||
func (r rowRef) row() Row { return r.Chunk.row(r.Index) }
|
||||
func refNewer(a, b rowRef) bool {
|
||||
if !a.at().Equal(b.at()) {
|
||||
return a.at().After(b.at())
|
||||
return timedOf(a, &a.Chunk.Rows[a.Index]).newer(timedOf(b, &b.Chunk.Rows[b.Index]))
|
||||
}
|
||||
|
||||
// timedRef is a ref with what puts it in order, newest first: its row's
|
||||
// time and order. A packed chunk's refs are put in order without its rows.
|
||||
type timedRef struct {
|
||||
rowRef
|
||||
at time.Time
|
||||
order int64
|
||||
}
|
||||
|
||||
func timedOf(ref rowRef, p *packedRow) timedRef { return timedRef{ref, p.Time, p.Order} }
|
||||
|
||||
func (a timedRef) newer(b timedRef) bool {
|
||||
if !a.at.Equal(b.at) {
|
||||
return a.at.After(b.at)
|
||||
}
|
||||
if (a.Chunk.Source.Path == "") != (b.Chunk.Source.Path == "") {
|
||||
return a.Chunk.Source.Path == ""
|
||||
@@ -357,17 +371,86 @@ func refNewer(a, b rowRef) bool {
|
||||
if a.Chunk.Source.Path != b.Chunk.Source.Path {
|
||||
return a.Chunk.Source.Path > b.Chunk.Source.Path
|
||||
}
|
||||
return a.Chunk.Rows[a.Index].Order > b.Chunk.Rows[b.Index].Order
|
||||
return a.order > b.order
|
||||
}
|
||||
|
||||
type newestHeap []rowRef
|
||||
type newestHeap []timedRef
|
||||
|
||||
func (h newestHeap) Len() int { return len(h) }
|
||||
func (h newestHeap) Less(i, j int) bool { return refNewer(h[j], h[i]) }
|
||||
func (h newestHeap) Less(i, j int) bool { return h[j].newer(h[i]) }
|
||||
func (h newestHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
func (h *newestHeap) Push(v any) { *h = append(*h, v.(rowRef)) }
|
||||
func (h *newestHeap) Push(v any) { *h = append(*h, v.(timedRef)) }
|
||||
func (h *newestHeap) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
||||
|
||||
// rowsIn is how many rows c has, packed or not.
|
||||
func rowsIn(c *rowChunk) int {
|
||||
if len(c.Archive) != 0 {
|
||||
return c.Count
|
||||
}
|
||||
return len(c.Rows)
|
||||
}
|
||||
|
||||
// chunkRows reads chunks' rows one chunk at a time. A page of the whole
|
||||
// history held every session file's rows decoded at once, beside the
|
||||
// packed copies it keeps: ~100 MB of a start that peaked at 508 MB over
|
||||
// 420k calls. A packed chunk is decoded when a pass reaches it, into a
|
||||
// buffer the next one's decode reuses, and refs still name the packed
|
||||
// chunk.
|
||||
type chunkRows struct {
|
||||
c, open *rowChunk
|
||||
buf []packedRow
|
||||
}
|
||||
|
||||
// of is c's rows to read. What the page set on c since (a Codex actor or
|
||||
// compaction, the identities) is read through c.
|
||||
func (r *chunkRows) of(c *rowChunk) *rowChunk {
|
||||
if len(c.Archive) == 0 {
|
||||
return c
|
||||
}
|
||||
if r.c != c {
|
||||
open := c.unpackInto(r.buf)
|
||||
if open == nil { // never written so: pack wrote it in this process
|
||||
open = &rowChunk{Source: c.Source, Computer: c.Computer}
|
||||
}
|
||||
if cap(open.Rows) > cap(r.buf) {
|
||||
r.buf = open.Rows[:0]
|
||||
}
|
||||
r.c, r.open = c, open
|
||||
}
|
||||
r.open.codexActors, r.open.codexCompactions, r.open.codexIdentities = c.codexActors, c.codexCompactions, c.codexIdentities
|
||||
return r.open
|
||||
}
|
||||
|
||||
func (r *chunkRows) row(ref rowRef) Row { return r.of(ref.Chunk).row(ref.Index) }
|
||||
|
||||
// rowsOf reads the rows refs name, each chunk once, in the order of chunks.
|
||||
func rowsOf(chunks []*rowChunk, refs []rowRef) map[rowRef]Row {
|
||||
out := make(map[rowRef]Row, len(refs))
|
||||
byChunk := map[*rowChunk][]int{}
|
||||
for _, ref := range refs {
|
||||
byChunk[ref.Chunk] = append(byChunk[ref.Chunk], ref.Index)
|
||||
}
|
||||
var rows chunkRows
|
||||
for _, c := range chunks {
|
||||
indexes, ok := byChunk[c]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
delete(byChunk, c)
|
||||
open := rows.of(c)
|
||||
for _, i := range indexes {
|
||||
out[rowRef{c, i}] = open.row(i)
|
||||
}
|
||||
}
|
||||
for c, indexes := range byChunk { // a ref to a chunk not in chunks
|
||||
open := rows.of(c)
|
||||
for _, i := range indexes {
|
||||
out[rowRef{c, i}] = open.row(i)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type pageKey struct {
|
||||
Period Period
|
||||
Filter Filter
|
||||
@@ -639,10 +722,10 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
if !since.IsZero() && s.Modified.Before(since) {
|
||||
continue
|
||||
}
|
||||
cached := idx.chunks[s.Path]
|
||||
c := cached.unpack()
|
||||
reused := c != nil && c.Source.Size == s.Size && c.Source.Modified.Equal(s.Modified)
|
||||
if !reused {
|
||||
// kept packed: the page reads a chunk's rows when it reaches them
|
||||
// (chunkRows), not every file's at once
|
||||
c := idx.chunks[s.Path]
|
||||
if reused := c != nil && c.Source.Size == s.Size && c.Source.Modified.Equal(s.Modified); !reused {
|
||||
if resolver == nil {
|
||||
resolver = newSessionResolver([]sessions.Call{{}})
|
||||
}
|
||||
@@ -659,19 +742,12 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
}
|
||||
c.Bytes -= int64(32 * len(c.Strings))
|
||||
c.dict, c.shapeIDs = nil, nil // local chunks are immutable until the source changes
|
||||
idx.chunks[s.Path] = c
|
||||
c = c.pack()
|
||||
}
|
||||
next := *c
|
||||
c = &next
|
||||
c.Used = idx.tick
|
||||
if reused {
|
||||
kept := *cached
|
||||
kept.Used = idx.tick
|
||||
idx.chunks[s.Path] = &kept
|
||||
} else {
|
||||
idx.chunks[s.Path] = c.pack()
|
||||
}
|
||||
chunks = append(chunks, c)
|
||||
kept, next := *c, *c
|
||||
kept.Used, next.Used = idx.tick, idx.tick
|
||||
idx.chunks[s.Path] = &kept
|
||||
chunks = append(chunks, &next)
|
||||
}
|
||||
// the other computers' days (#542), a chunk each, read again only when
|
||||
// sync brought a new copy
|
||||
@@ -686,10 +762,8 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
if s.day < from {
|
||||
continue
|
||||
}
|
||||
cached := idx.chunks[s.path]
|
||||
c := cached.unpack()
|
||||
reused := c != nil && c.Source.Size == s.size && c.Source.Modified.Equal(s.mod)
|
||||
if !reused {
|
||||
c := idx.chunks[s.path]
|
||||
if reused := c != nil && c.Source.Size == s.size && c.Source.Modified.Equal(s.mod); !reused {
|
||||
d, _ := readShared(s.path)
|
||||
if renames == nil {
|
||||
renames = provider.Renamed()
|
||||
@@ -705,18 +779,12 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
}
|
||||
c.Bytes -= int64(32 * len(c.Strings))
|
||||
c.dict, c.shapeIDs = nil, nil
|
||||
c = c.pack()
|
||||
}
|
||||
next := *c
|
||||
c = &next
|
||||
c.Used = idx.tick
|
||||
if reused {
|
||||
kept := *cached
|
||||
kept.Used = idx.tick
|
||||
idx.chunks[s.path] = &kept
|
||||
} else {
|
||||
idx.chunks[s.path] = c.pack()
|
||||
}
|
||||
others = append(others, c)
|
||||
kept, next := *c, *c
|
||||
kept.Used, next.Used = idx.tick, idx.tick
|
||||
idx.chunks[s.path] = &kept
|
||||
others = append(others, &next)
|
||||
}
|
||||
for path := range idx.chunks {
|
||||
if !on[path] {
|
||||
@@ -794,17 +862,20 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
func visibleLocal(chunks []*rowChunk) map[rowRef]bool {
|
||||
duplicates := map[rowRef]bool{}
|
||||
seen := map[string]bool{}
|
||||
var rows chunkRows
|
||||
for _, c := range chunks {
|
||||
for i := range c.Rows {
|
||||
p := &c.Rows[i]
|
||||
msg := c.Strings[c.text(p, rowMsg)]
|
||||
open := rows.of(c)
|
||||
for i := range open.Rows {
|
||||
p := &open.Rows[i]
|
||||
msg := open.Strings[open.text(p, rowMsg)]
|
||||
if msg == "" {
|
||||
continue
|
||||
}
|
||||
if seen[msg] {
|
||||
duplicates[rowRef{c, i}] = true
|
||||
} else {
|
||||
seen[msg] = true
|
||||
// a copy: a decoded chunk's strings are one allocation
|
||||
seen[strings.Clone(msg)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -882,27 +953,32 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
|
||||
}
|
||||
}
|
||||
}
|
||||
byRequest := map[string][]rowRef{}
|
||||
byRequest := map[string][]timedRef{}
|
||||
var rows chunkRows
|
||||
for _, c := range chunks {
|
||||
for i := range c.Rows {
|
||||
p := &c.Rows[i]
|
||||
open := rows.of(c)
|
||||
for i := range open.Rows {
|
||||
p := &open.Rows[i]
|
||||
ref := rowRef{c, i}
|
||||
if skip[ref] || reserved[ref] || p.Time.Before(since) {
|
||||
continue
|
||||
}
|
||||
if id := c.Strings[c.text(p, 11)]; len(byID[id]) > 0 {
|
||||
byRequest[id] = append(byRequest[id], ref)
|
||||
if id := open.Strings[open.text(p, 11)]; len(byID[id]) > 0 {
|
||||
if _, ok := byRequest[id]; !ok {
|
||||
id = strings.Clone(id)
|
||||
}
|
||||
byRequest[id] = append(byRequest[id], timedOf(ref, p))
|
||||
}
|
||||
}
|
||||
}
|
||||
used := map[rowRef]bool{}
|
||||
for id, refs := range byRequest {
|
||||
if newestIDs {
|
||||
slices.SortFunc(refs, func(a, b rowRef) int {
|
||||
if refNewer(a, b) {
|
||||
slices.SortFunc(refs, func(a, b timedRef) int {
|
||||
if a.newer(b) {
|
||||
return -1
|
||||
}
|
||||
if refNewer(b, a) {
|
||||
if b.newer(a) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
@@ -912,7 +988,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
|
||||
if j >= len(byID[id]) {
|
||||
break
|
||||
}
|
||||
matched[ref], used[byID[id][j]] = true, true
|
||||
matched[ref.rowRef], used[byID[id][j]] = true, true
|
||||
}
|
||||
}
|
||||
groups := map[matchKey]*matchGroup{}
|
||||
@@ -950,10 +1026,11 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]boo
|
||||
g.counts = make([]int, len(g.ends)+1)
|
||||
}
|
||||
candidates := map[rowRef]rowRef{}
|
||||
for _, c := range chunks {
|
||||
for _, chunk := range chunks {
|
||||
c := rows.of(chunk)
|
||||
for j := range c.Rows {
|
||||
p := &c.Rows[j]
|
||||
ref := rowRef{c, j}
|
||||
ref := rowRef{chunk, j}
|
||||
if skip[ref] || reserved[ref] || matched[ref] || p.Time.Before(since) {
|
||||
continue
|
||||
}
|
||||
@@ -1038,10 +1115,58 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga
|
||||
return buildRequestBlocksWithCodex(p, f, offset, limit, now, gateways, chunks, others, names, sessions.CodexIdentities())
|
||||
}
|
||||
|
||||
// buildRequestBlocksWithCodex's page owns its strings. A packed chunk is
|
||||
// read through one block of strings at a time (chunkRows), and a row, an
|
||||
// agent's name or a group kept by the page from it would hold that whole
|
||||
// block: ~9 MB after the first page, kept by the request cache.
|
||||
func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string, identities map[string]sessions.CodexIdentity) RequestPage {
|
||||
out := buildRequestBlocksOf(p, f, offset, limit, now, gateways, chunks, others, names, identities)
|
||||
ownStrings(reflect.ValueOf(&out).Elem())
|
||||
return out
|
||||
}
|
||||
|
||||
// ownStrings copies every string v holds that can be set, map keys too.
|
||||
func ownStrings(v reflect.Value) {
|
||||
switch v.Kind() {
|
||||
case reflect.String:
|
||||
if v.CanSet() && v.Len() > 0 {
|
||||
v.SetString(strings.Clone(v.String()))
|
||||
}
|
||||
case reflect.Pointer:
|
||||
if !v.IsNil() {
|
||||
ownStrings(v.Elem())
|
||||
}
|
||||
case reflect.Struct:
|
||||
for i := range v.NumField() {
|
||||
if f := v.Field(i); f.CanSet() {
|
||||
ownStrings(f)
|
||||
}
|
||||
}
|
||||
case reflect.Slice, reflect.Array:
|
||||
for i := range v.Len() {
|
||||
ownStrings(v.Index(i))
|
||||
}
|
||||
case reflect.Map:
|
||||
if v.IsNil() || !v.CanSet() {
|
||||
return
|
||||
}
|
||||
m := reflect.MakeMapWithSize(v.Type(), v.Len())
|
||||
for it := v.MapRange(); it.Next(); {
|
||||
k, e := reflect.New(v.Type().Key()).Elem(), reflect.New(v.Type().Elem()).Elem()
|
||||
k.Set(it.Key())
|
||||
e.Set(it.Value())
|
||||
ownStrings(k)
|
||||
ownStrings(e)
|
||||
m.SetMapIndex(k, e)
|
||||
}
|
||||
v.Set(m)
|
||||
}
|
||||
}
|
||||
|
||||
func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string, identities map[string]sessions.CodexIdentity) RequestPage {
|
||||
gateways, chunks, others = cloneCodexChunks(gateways), cloneCodexChunks(chunks), cloneCodexChunks(others)
|
||||
duplicateSkip := foldCodexRows(chunks)
|
||||
pairs := codexChunkResponsePairs(gateways, chunks, duplicateSkip)
|
||||
pairs, compactions := codexChunkResponsePairs(gateways, chunks, duplicateSkip)
|
||||
for _, set := range [][]*rowChunk{gateways, chunks, others} {
|
||||
for _, chunk := range set {
|
||||
chunk.codexIdentities = identities
|
||||
@@ -1059,18 +1184,20 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
actor = local.Chunk.codexActors[local.Index]
|
||||
}
|
||||
setCodexActor(gateway.Chunk, gateway.Index, actor)
|
||||
gateway.Chunk.setCodexCompaction(gateway.Index, local.row().Compaction)
|
||||
gateway.Chunk.setCodexCompaction(gateway.Index, compactions[local])
|
||||
}
|
||||
all := append(append(slices.Clone(gateways), chunks...), others...)
|
||||
visit := func(fn func(rowRef, Row)) {
|
||||
visit := func(fn func(timedRef, Row)) {
|
||||
var rows chunkRows
|
||||
for _, c := range all {
|
||||
for i := range c.Rows {
|
||||
pr := &c.Rows[i] // not a copy: a row is 216 bytes
|
||||
open := rows.of(c)
|
||||
for i := range open.Rows {
|
||||
pr := &open.Rows[i] // not a copy: a row is 216 bytes
|
||||
ref := rowRef{c, i}
|
||||
if pr.Time.Before(since) || after(until, pr.Time) || len(skip) > 0 && skip[ref] || len(matched) > 0 && matched[ref] {
|
||||
continue
|
||||
}
|
||||
fn(ref, c.row(i))
|
||||
fn(timedOf(ref, pr), open.row(i))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1081,7 +1208,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
// year the groups, shares and series below took seconds a call (#3493).
|
||||
if p == heatmapPeriod {
|
||||
out.Heat = heatmapOf(since, now, func(add func(Row)) {
|
||||
visit(func(_ rowRef, r Row) {
|
||||
visit(func(_ timedRef, r Row) {
|
||||
if chartFilter.keepsRow(r) {
|
||||
add(r)
|
||||
}
|
||||
@@ -1107,7 +1234,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
// reach MaxInt, and a page beyond all sources needs no heap at all.
|
||||
maxRows := 0
|
||||
for _, c := range all {
|
||||
maxRows += len(c.Rows)
|
||||
maxRows += rowsIn(c)
|
||||
}
|
||||
take := 0
|
||||
if offset < maxRows {
|
||||
@@ -1121,7 +1248,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
// the rows the chart counts, kept as the first pass
|
||||
// finds them so that theirs needn't read every row of the period again
|
||||
var charted []rowRef
|
||||
visit(func(ref rowRef, r Row) {
|
||||
visit(func(ref timedRef, r Row) {
|
||||
// looked up before they are set: most rows name what an earlier
|
||||
// one did, and a map's lookup is cheaper than its write
|
||||
if !agents[r.Agent] {
|
||||
@@ -1140,7 +1267,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
out.Total++
|
||||
if take > 0 && len(selected) < take {
|
||||
heap.Push(&selected, ref)
|
||||
} else if take > 0 && refNewer(ref, selected[0]) {
|
||||
} else if take > 0 && ref.newer(selected[0]) {
|
||||
selected[0] = ref
|
||||
heap.Fix(&selected, 0)
|
||||
}
|
||||
@@ -1167,7 +1294,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
return
|
||||
}
|
||||
if keep || f.Day != "" && chartFilter.keepsRow(r) {
|
||||
charted = append(charted, ref)
|
||||
charted = append(charted, ref.rowRef)
|
||||
for _, d := range Dimensions {
|
||||
k := keys.key(r, d)
|
||||
s := seriesGroups[d][k]
|
||||
@@ -1217,17 +1344,22 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
s.addRow(r)
|
||||
}
|
||||
})
|
||||
slices.SortFunc(selected, func(a, b rowRef) int {
|
||||
if refNewer(a, b) {
|
||||
slices.SortFunc(selected, func(a, b timedRef) int {
|
||||
if a.newer(b) {
|
||||
return -1
|
||||
}
|
||||
if refNewer(b, a) {
|
||||
if b.newer(a) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
var page []rowRef
|
||||
for _, ref := range selected[min(offset, len(selected)):] {
|
||||
out.Rows = append(out.Rows, ref.row())
|
||||
page = append(page, ref.rowRef)
|
||||
}
|
||||
read := rowsOf(all, page)
|
||||
for _, ref := range page {
|
||||
out.Rows = append(out.Rows, read[ref])
|
||||
}
|
||||
for a := range agents {
|
||||
out.Agents = append(out.Agents, a)
|
||||
@@ -1267,8 +1399,9 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time
|
||||
out.Series[i].By[d] = map[string]Part{}
|
||||
}
|
||||
}
|
||||
var chartRows chunkRows // charted is in the order of all: each chunk is read once
|
||||
for _, ref := range charted {
|
||||
r := ref.row()
|
||||
r := chartRows.row(ref)
|
||||
t := r.Time.In(now.Location())
|
||||
if t.Before(chartSince) {
|
||||
continue
|
||||
|
||||
@@ -91,6 +91,7 @@ func (c *rowChunk) pack() *rowChunk {
|
||||
return c
|
||||
}
|
||||
next := *c
|
||||
next.Count = len(c.Rows) // what rowsIn says of it
|
||||
next.Rows, next.Strings, next.Shapes, next.dict, next.shapeIDs = nil, nil, nil, nil, nil
|
||||
next.Archive, next.Locations = slices.Clone(encoded), locations
|
||||
next.Bytes = int64(len(next.Archive)+len(locations)*8) + codexActorBytes(next.codexActors)
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// The Requests page reads a packed local chunk one chunk at a time instead of
|
||||
// unpacking every chunk first (the warm start's peak). The page it builds is
|
||||
// the page the unpacked rows build: Codex copies folded, gateway pairs with
|
||||
// their compaction, Claude message copies, request-id and fallback matches.
|
||||
func TestRequestPageSameFromPackedLocalChunks(t *testing.T) {
|
||||
pageHome(t)
|
||||
now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)
|
||||
identities := map[string]sessions.CodexIdentity{
|
||||
"main-a": {ID: "main-a", Role: "main", RootSession: "main-a"},
|
||||
"child-b": {ID: "child-b", Role: "subagent", ParentSession: "main-a", RootSession: "main-a"},
|
||||
}
|
||||
yes := true
|
||||
build := func(pack bool) (RequestPage, []*rowChunk) {
|
||||
gateway := &rowChunk{}
|
||||
var locals []*rowChunk
|
||||
for k := 0; k < 3; k++ {
|
||||
local := &rowChunk{}
|
||||
for i := 0; i < 80; i++ {
|
||||
at := now.Add(-time.Duration(k*100+i) * time.Minute)
|
||||
switch i % 4 {
|
||||
case 0: // a Codex call written twice, with its gateway row
|
||||
id := fmt.Sprintf("resp-%d-%d", k, i)
|
||||
if i%8 == 0 { // the other half has no gateway row and shows as written
|
||||
gateway.add(Row{Record: Record{Time: at.Add(time.Second), Agent: "codex", Provider: "openai", Model: "gw", Input: 500 + i, Output: 50, Status: 200, ResponseID: id}}, "", int64(k*1000+i), false)
|
||||
}
|
||||
for copy := 0; copy < 2; copy++ {
|
||||
local.add(Row{Record: Record{Time: at, Agent: "codex", Model: "native", Input: 80, Output: 8, Session: "s-child", ResponseID: id, Compaction: &yes}, Source: "log", codexActor: "child-b"}, "", int64(i*2+copy), false)
|
||||
}
|
||||
case 1: // a Claude message in two files
|
||||
msg := fmt.Sprintf("msg-%d-%d", k, i)
|
||||
local.add(Row{Record: Record{Time: at, Agent: "claude", Model: "claude-x", Input: 10 + i, Output: 1, Session: "c-" + msg}, Source: "log"}, msg, int64(i), false)
|
||||
local.add(Row{Record: Record{Time: at, Agent: "claude", Model: "claude-x", Input: 10 + i, Output: 1, Session: "c-" + msg}, Source: "log"}, msg, int64(i+1), false)
|
||||
case 2: // matched to a gateway row by request id
|
||||
rid := fmt.Sprintf("rid-%d-%d", k, i)
|
||||
gateway.add(Row{Record: Record{Time: at.Add(2 * time.Second), Agent: "claude", Provider: "anthropic", Model: "gw-claude", Input: 30, Output: 3, Status: 200, RequestID: rid}}, "", int64(k*1000+i), false)
|
||||
local.add(Row{Record: Record{Time: at, Agent: "claude", Model: "claude-x", Input: 30, Output: 3, RequestID: rid, Session: "r-" + rid}, Source: "log"}, "", int64(i), false)
|
||||
default: // matched by time and tokens, or left alone
|
||||
gateway.add(Row{Record: Record{Time: at.Add(time.Second), Agent: "claude", Provider: "anthropic", Model: "gw-claude", Input: 70 + i, Output: 7, Status: 200}}, "", int64(k*1000+i), false)
|
||||
local.add(Row{Record: Record{Time: at, Agent: "claude", Model: "claude-x", Input: 70 + i, Output: 7, Session: fmt.Sprintf("t-%d-%d", k, i)}, Source: "log"}, "", int64(i), false)
|
||||
}
|
||||
}
|
||||
if pack {
|
||||
local = local.pack()
|
||||
}
|
||||
locals = append(locals, local)
|
||||
}
|
||||
return buildRequestBlocksWithCodex(All, Filter{}, 0, 100, now, []*rowChunk{gateway}, locals, nil, nil, identities), locals
|
||||
}
|
||||
want, _ := build(false)
|
||||
got, packed := build(true)
|
||||
for _, c := range packed {
|
||||
if len(c.Archive) == 0 {
|
||||
t.Fatalf("a local chunk of %d rows was not packed", len(c.Rows))
|
||||
}
|
||||
}
|
||||
if len(want.Rows) == 0 || want.Sum.Calls == 0 {
|
||||
t.Fatalf("the unpacked page is empty: %+v", want)
|
||||
}
|
||||
subagent := false
|
||||
for _, r := range want.Rows {
|
||||
subagent = subagent || (r.Model == "native" && r.Subagent == "child-b")
|
||||
}
|
||||
if !subagent {
|
||||
t.Fatalf("no unpaired Codex row carries its subagent: %+v", want.Rows)
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("packed page differs:\n got %+v\nwant %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A page's strings are its own: a row or a name the page keeps from a packed
|
||||
// chunk would otherwise hold the whole block of strings that chunk was read
|
||||
// into, in the request cache, for as long as the page is kept.
|
||||
func TestRequestPageOwnsItsStrings(t *testing.T) {
|
||||
pageHome(t)
|
||||
page := RequestPage{
|
||||
Rows: []Row{{Record: Record{Agent: "codex", Model: "m", Session: "s"}}},
|
||||
Agents: []string{"codex"},
|
||||
By: map[string][]Share{"agent": {{ID: "codex"}}},
|
||||
Names: map[string]string{"pc": "laptop"},
|
||||
Heat: &Heatmap{From: "2026-09-01"},
|
||||
Series: []SeriesPoint{{Point: Point{Label: "12:00"}, By: map[string]map[string]Part{"model": {"m": {Calls: 1}}}}},
|
||||
}
|
||||
before := map[*byte]bool{}
|
||||
var walk func(v reflect.Value, see func(string))
|
||||
walk = func(v reflect.Value, see func(string)) {
|
||||
switch v.Kind() {
|
||||
case reflect.String:
|
||||
see(v.String())
|
||||
case reflect.Pointer:
|
||||
if !v.IsNil() {
|
||||
walk(v.Elem(), see)
|
||||
}
|
||||
case reflect.Struct:
|
||||
for i := range v.NumField() {
|
||||
if v.Type().Field(i).IsExported() {
|
||||
walk(v.Field(i), see)
|
||||
}
|
||||
}
|
||||
case reflect.Slice, reflect.Array:
|
||||
for i := range v.Len() {
|
||||
walk(v.Index(i), see)
|
||||
}
|
||||
case reflect.Map:
|
||||
for it := v.MapRange(); it.Next(); {
|
||||
walk(it.Key(), see)
|
||||
walk(it.Value(), see)
|
||||
}
|
||||
}
|
||||
}
|
||||
n := 0
|
||||
walk(reflect.ValueOf(page), func(s string) {
|
||||
if s != "" {
|
||||
before[unsafe.StringData(s)] = true
|
||||
n++
|
||||
}
|
||||
})
|
||||
ownStrings(reflect.ValueOf(&page).Elem())
|
||||
kept := 0
|
||||
walk(reflect.ValueOf(page), func(s string) {
|
||||
if s != "" && before[unsafe.StringData(s)] {
|
||||
t.Errorf("%q still shares its bytes", s)
|
||||
}
|
||||
if s != "" {
|
||||
kept++
|
||||
}
|
||||
})
|
||||
if n != 12 || kept != n || page.Heat.From != "2026-09-01" || page.Names["pc"] != "laptop" || page.By["agent"][0].ID != "codex" || page.Series[0].By["model"]["m"].Calls != 1 {
|
||||
t.Fatalf("strings %d before, %d after: %+v", n, kept, page)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user