usage: a Requests page sums each chunk once and reuses it while the chunk is the same
Turning a page, or the 15s refresh of the open page, built every sum, chart and share from every row of history again. On the owner's real history that was 1.15-1.36s a page (load 170) after the chunks were already cached. Each chunk's rows are now folded into cells: one per provider, agent, model, kind, caller, account, computer, source, filter bits and chart bucket, with its totals. A page merges the cells. The cells of a chunk are kept per (period, filter, since, until, zone), up to 4 such sets, keyed by the chunk's serial (a new one every time a chunk is read or frozen) and a signature of what pairing gave it: rows skipped or matched, Codex actors and their identities (with the parent's role), and compactions. A changed file, a gateway tail block or an identity change from another file sums that chunk again. The newest rows are taken from chunks in Latest order, stopping once the heap holds rows newer than the next chunk. Cell strings are unique handles, so the cache holds no chunk's string block. Totals and Part sums are linear, so merged cells equal the row-by-row sums; date-mode buckets store the day number and are placed against the chart's first day at merge time. What was run (macOS, arm64): - Real history (sbmem sandbox HOME, read-only links to the owner's data), zzbench dump of 9 cases x 2 pages (offset 0/50 after a warm 7/50 call, and 120/30) with the base1313b047fand this change: 0 differences over 18 pages (floats at rel 1e-9). - zzbench timing at load 170: warm pages 1.15s / 1.36s mean -> 0.45s / 0.41s; first page 3.1s / 2.8s -> 2.4s / 2.6s. - New TestRequestCellsFollowIdentityAndFiles: a child chunk whose parent's file changes (its root moves to top-z) without the child being read again, a changed child file, a gateway append, compared to pageFromLedger for All and Week. Broken by hand: reusing a part whatever its signature turns it red ("a cached part kept the old root: 0 rows, 0 input"). Passes in TZ=UTC too. - go test -count=1 -timeout 45m ./internal/usage/... ./internal/usageapi/... ./internal/sessions/...: usageapi and sessions ok; usage red only on TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp, #3511 (taken by another session). -count=10 of it: 2 FAIL on this change and 2 FAIL on the base1313b047f, at load ~100-145. Every other usage test passes. - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/. Not done here: the pairing setup (unpacking unchanged chunks for visibleLocal, matchedBlocks and foldCodexRows) is now most of a warm page, ~0.18s each; it is next.
This commit is contained in:
@@ -272,7 +272,9 @@ func (c *rowChunk) freeze() *rowChunk {
|
||||
c.Bytes -= int64(32 * len(c.Strings))
|
||||
}
|
||||
c.shapeIDs = nil
|
||||
return c.pack()
|
||||
c = c.pack()
|
||||
c.serial = nextChunkSerial()
|
||||
return c
|
||||
}
|
||||
|
||||
func resumeLogHash(h hash.Hash, state []byte) bool {
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"container/heap"
|
||||
"hash/maphash"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unique"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A page's sums are made of each chunk's own: its rows told apart by all a
|
||||
// sum, a group or a point of the chart reads of them (pageCell). A call
|
||||
// changes one session file's chunk, or the gateway's last block, and every
|
||||
// other chunk's cells are the same as on the page before, so a page built
|
||||
// after a call adds up the cells kept for those (partCache) and reads only
|
||||
// the chunks that changed. Reading every row of the history again was ~1s a
|
||||
// refresh of All over 420k calls, every few seconds a live agent wrote
|
||||
// (#3493).
|
||||
|
||||
// cellDims is how many Dimensions there are: a cell has a bit for each.
|
||||
const cellDims = 5
|
||||
|
||||
func init() {
|
||||
if len(Dimensions) != cellDims {
|
||||
panic("usage: cellDims is not len(Dimensions)")
|
||||
}
|
||||
}
|
||||
|
||||
// chunkSerial names a chunk as it was made: a packed session file's, another
|
||||
// computer's day, a frozen block of the gateway's. Its copies keep it, and
|
||||
// nothing a page reads of a chunk changes while it has it; 0 is a chunk
|
||||
// kept for no page (a probe's, a test's).
|
||||
var chunkSerial atomic.Uint64
|
||||
|
||||
func nextChunkSerial() uint64 { return chunkSerial.Add(1) }
|
||||
|
||||
// a cell's bits
|
||||
const (
|
||||
cellKeep = 1 << iota // the filter keeps its rows
|
||||
cellUncounted // turned away or a probe: listed, in no sum
|
||||
cellVia // kept with the source pick cleared
|
||||
cellCharted // in the chart
|
||||
cellComputer // in the computers' shares
|
||||
cellGroup // and on, one a dimension: in its groups
|
||||
cellChart = cellGroup << cellDims // one a dimension: in its ChartBy
|
||||
)
|
||||
|
||||
// cell sources, as the source cells count them
|
||||
const (
|
||||
cellThrough = iota
|
||||
cellDirect
|
||||
cellReported
|
||||
)
|
||||
|
||||
// cellRow is what a cell tells its rows apart by, as the chunk's strings.
|
||||
type cellRow struct {
|
||||
provider, agent, model, kind, callerID, callerName, account, computer string
|
||||
source uint8
|
||||
bits uint16
|
||||
// bucket is the chart's hour from the period's start (-1 before it),
|
||||
// or the row's day (dayNumber) for a chart of days or weeks
|
||||
bucket int32
|
||||
}
|
||||
|
||||
// pageCell is a chunk's rows of one cellRow: n of them, d their sums. Its
|
||||
// strings are unique's, so the cells kept hold no chunk's strings.
|
||||
type pageCell struct {
|
||||
provider, agent, model, kind, callerID, callerName, account, computer unique.Handle[string]
|
||||
source uint8
|
||||
bits uint16
|
||||
bucket int32
|
||||
n int
|
||||
d Totals
|
||||
}
|
||||
|
||||
// chunkPart is a chunk's cells, in the order of their rows' last (so the
|
||||
// last row's caller key name is the one shown, as before), for the state
|
||||
// sig is of (pairedRows.sig).
|
||||
type chunkPart struct {
|
||||
sig uint64
|
||||
cells []pageCell
|
||||
kept int // rows the filter keeps
|
||||
first time.Time // the oldest charted row's time
|
||||
}
|
||||
|
||||
// partKey is what a chunk's cells are of besides the chunk: the page's
|
||||
// period at now and its filter.
|
||||
type partKey struct {
|
||||
p Period
|
||||
f Filter
|
||||
since, until time.Time
|
||||
loc *time.Location
|
||||
}
|
||||
|
||||
// partCache is the cells a page is built with: old, those kept by the
|
||||
// page of the same partKey before, next, those of this page's chunks, which
|
||||
// the index keeps for the next.
|
||||
type partCache struct {
|
||||
old, next map[uint64]*chunkPart
|
||||
}
|
||||
|
||||
// partSets bounds the partKeys kept: a page is open on one period and
|
||||
// filter, and its card and the Sessions page ask for a few more.
|
||||
const partSets = 4
|
||||
|
||||
// dayNumber is t's day as a count of days, as calendarDays counts them.
|
||||
func dayNumber(t time.Time) int32 {
|
||||
y, m, d := t.Date()
|
||||
return int32(time.Date(y, m, d, 0, 0, 0, 0, time.UTC).Unix() / 86400)
|
||||
}
|
||||
|
||||
// cellPass is how a page reads a row into its cell.
|
||||
type cellPass struct {
|
||||
f, chart, via, computer Filter
|
||||
without, withoutDay [cellDims]Filter
|
||||
unpicked [cellDims]bool
|
||||
computerUnpicked, names bool
|
||||
hours bool
|
||||
since time.Time
|
||||
loc *time.Location
|
||||
}
|
||||
|
||||
func newCellPass(p Period, f Filter, now time.Time, names bool) *cellPass {
|
||||
c := &cellPass{f: f, chart: f, via: f, computer: f, names: names, since: p.Since(now), loc: now.Location()}
|
||||
c.chart.Day = ""
|
||||
c.via.Through = ""
|
||||
c.computer.Computer, c.computer.Day = "", ""
|
||||
c.computerUnpicked = c.computer == f
|
||||
for i, d := range Dimensions {
|
||||
c.without[i] = f.Without(d)
|
||||
c.unpicked[i] = c.without[i] == f
|
||||
c.withoutDay[i] = c.without[i]
|
||||
c.withoutDay[i].Day = ""
|
||||
}
|
||||
_, bucket, _ := timeline(p, now, time.Time{})
|
||||
c.hours = bucket == "hour"
|
||||
return c
|
||||
}
|
||||
|
||||
// part is c's cells, read through rows into r.
|
||||
func (pass *cellPass) part(ps *pairedRows, rows *chunkRows, c *rowChunk, r *Row) *chunkPart {
|
||||
part := &chunkPart{}
|
||||
at := map[cellRow]int{}
|
||||
var raw []cellRow
|
||||
var cells []pageCell
|
||||
var last []int
|
||||
n := 0
|
||||
ps.visitChunk(rows, c, r, func(_ timedRef, r *Row) {
|
||||
n++
|
||||
f := &pass.f
|
||||
uncounted := r.IsRejected() || r.IsProbe()
|
||||
keep := f.keepsRow(r)
|
||||
k := cellRow{provider: r.Provider, agent: r.Agent, kind: r.Kind}
|
||||
if keep {
|
||||
k.bits |= cellKeep
|
||||
part.kept++
|
||||
}
|
||||
if uncounted {
|
||||
k.bits |= cellUncounted
|
||||
} else {
|
||||
k.model, k.callerID, k.callerName, k.account, k.computer = r.Model, r.CallerKeyID, r.CallerKeyName, r.Account(), r.Computer
|
||||
switch r.Source {
|
||||
case "log":
|
||||
k.source = cellDirect
|
||||
case SourceReported:
|
||||
k.source = cellReported
|
||||
default:
|
||||
k.source = cellThrough
|
||||
}
|
||||
if pass.via.keepsRow(r) {
|
||||
k.bits |= cellVia
|
||||
}
|
||||
if keep || f.Day != "" && pass.chart.keepsRow(r) {
|
||||
k.bits |= cellCharted
|
||||
if part.first.IsZero() || r.Time.Before(part.first) {
|
||||
part.first = r.Time
|
||||
}
|
||||
t := r.Time.In(pass.loc)
|
||||
switch {
|
||||
case !pass.hours:
|
||||
k.bucket = dayNumber(t)
|
||||
case t.Before(pass.since):
|
||||
k.bucket = -1
|
||||
default:
|
||||
k.bucket = int32(t.Sub(pass.since).Hours())
|
||||
}
|
||||
}
|
||||
if pass.names && (pass.computerUnpicked && keep || !pass.computerUnpicked && pass.computer.keepsRow(r)) {
|
||||
k.bits |= cellComputer
|
||||
}
|
||||
for i := range cellDims {
|
||||
if f.Day != "" && pass.withoutDay[i].keepsRow(r) {
|
||||
k.bits |= cellChart << i
|
||||
}
|
||||
if pass.unpicked[i] && keep || !pass.unpicked[i] && pass.without[i].keepsRow(r) {
|
||||
k.bits |= cellGroup << i
|
||||
}
|
||||
}
|
||||
}
|
||||
i, ok := at[k]
|
||||
if !ok {
|
||||
i = len(cells)
|
||||
at[k] = i
|
||||
raw = append(raw, k)
|
||||
cells = append(cells, pageCell{source: k.source, bits: k.bits, bucket: k.bucket})
|
||||
last = append(last, 0)
|
||||
}
|
||||
cells[i].n++
|
||||
last[i] = n
|
||||
if !uncounted {
|
||||
cells[i].d.addRow(*r)
|
||||
}
|
||||
})
|
||||
for i := range cells {
|
||||
k, cell := &raw[i], &cells[i]
|
||||
cell.provider, cell.agent, cell.model, cell.kind = unique.Make(k.provider), unique.Make(k.agent), unique.Make(k.model), unique.Make(k.kind)
|
||||
cell.callerID, cell.callerName, cell.account, cell.computer = unique.Make(k.callerID), unique.Make(k.callerName), unique.Make(k.account), unique.Make(k.computer)
|
||||
}
|
||||
order := make([]int, len(cells))
|
||||
for i := range order {
|
||||
order[i] = i
|
||||
}
|
||||
slices.SortFunc(order, func(a, b int) int { return cmp.Compare(last[a], last[b]) })
|
||||
part.cells = make([]pageCell, len(cells))
|
||||
for i, j := range order {
|
||||
part.cells[i] = cells[j]
|
||||
}
|
||||
return part
|
||||
}
|
||||
|
||||
// row is the cell's names as a row has them, for Row.key.
|
||||
func (c *pageCell) row(r *Row) {
|
||||
r.Provider, r.Agent, r.Model = c.provider.Value(), c.agent.Value(), c.model.Value()
|
||||
r.CallerKeyID, r.Computer = c.callerID.Value(), c.computer.Value()
|
||||
}
|
||||
|
||||
var sigSeed = maphash.MakeSeed()
|
||||
|
||||
// mix is a well-spread hash of a few numbers, summed into a signature
|
||||
// whatever order a map hands them in.
|
||||
func mix(vs ...uint64) uint64 {
|
||||
h := uint64(0x9e3779b97f4a7c15)
|
||||
for _, v := range vs {
|
||||
h ^= v
|
||||
h *= 0xbf58476d1ce4e5b9
|
||||
h ^= h >> 31
|
||||
h *= 0x94d049bb133111eb
|
||||
h ^= h >> 29
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// sigs is what each chunk's rows read on this page beyond the chunk
|
||||
// itself: the rows another one stands for (skip, matched), the Codex
|
||||
// thread each is of (pairs, a session file's own) and what is known of
|
||||
// that thread, and each compaction a gateway call was told. Two pages
|
||||
// whose chunk has one serial and one sig read the same rows from it.
|
||||
func (ps *pairedRows) sigs(identities map[string]sessions.CodexIdentity) map[*rowChunk]uint64 {
|
||||
out := make(map[*rowChunk]uint64, len(ps.all))
|
||||
for ref := range ps.skip {
|
||||
out[ref.Chunk] += mix(1, uint64(ref.Index))
|
||||
}
|
||||
for ref := range ps.matched {
|
||||
out[ref.Chunk] += mix(2, uint64(ref.Index))
|
||||
}
|
||||
actors := map[string]uint64{}
|
||||
actor := func(a string) uint64 {
|
||||
h, ok := actors[a]
|
||||
if ok {
|
||||
return h
|
||||
}
|
||||
id := identities[a]
|
||||
parent := identities[id.ParentSession]
|
||||
h = mix(maphash.String(sigSeed, a), maphash.String(sigSeed, id.ID), maphash.String(sigSeed, id.Role), maphash.String(sigSeed, id.RootSession),
|
||||
maphash.String(sigSeed, id.ParentSession), maphash.String(sigSeed, parent.ID), maphash.String(sigSeed, parent.Role))
|
||||
actors[a] = h
|
||||
return h
|
||||
}
|
||||
for _, c := range ps.all {
|
||||
h := out[c]
|
||||
if c.codexIdentities != nil {
|
||||
h += mix(3)
|
||||
}
|
||||
for i, a := range c.codexActors {
|
||||
if a != "" {
|
||||
h += mix(4, uint64(i), actor(a))
|
||||
}
|
||||
}
|
||||
for i, compacted := range c.codexCompactions {
|
||||
v := uint64(2)
|
||||
if compacted != nil && *compacted {
|
||||
v = 1
|
||||
} else if compacted != nil {
|
||||
v = 0
|
||||
}
|
||||
h += mix(5, uint64(i), v)
|
||||
}
|
||||
out[c] = h
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// partsOf are the cells of each of ps's chunks, in all's order: cache's,
|
||||
// when it has them for the chunk as this page reads it, else read.
|
||||
func (ps *pairedRows) partsOf(pass *cellPass, cache *partCache, identities map[string]sessions.CodexIdentity) []*chunkPart {
|
||||
sigs := ps.sigs(identities)
|
||||
parts := make([]*chunkPart, len(ps.all))
|
||||
var rows chunkRows
|
||||
var r Row
|
||||
for i, c := range ps.all {
|
||||
sig := sigs[c]
|
||||
if cache != nil && c.serial != 0 {
|
||||
if old := cache.old[c.serial]; old != nil && old.sig == sig {
|
||||
parts[i] = old
|
||||
cache.next[c.serial] = old
|
||||
continue
|
||||
}
|
||||
}
|
||||
part := pass.part(ps, &rows, c, &r)
|
||||
part.sig = sig
|
||||
if cache != nil && c.serial != 0 {
|
||||
cache.next[c.serial] = part
|
||||
}
|
||||
parts[i] = part
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
// newest are the take newest rows f keeps, newest last in heap order. A
|
||||
// chunk is read only while its newest call (Latest) could be one of them,
|
||||
// newest chunk first: a page of All reads the few its rows are in, not
|
||||
// every one.
|
||||
func (ps *pairedRows) newest(f Filter, parts []*chunkPart, take int) newestHeap {
|
||||
selected := newestHeap{}
|
||||
if take <= 0 {
|
||||
return selected
|
||||
}
|
||||
var order []*rowChunk
|
||||
for i, c := range ps.all {
|
||||
if parts[i].kept > 0 {
|
||||
order = append(order, c)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(order, func(a, b *rowChunk) int {
|
||||
if a.Latest.IsZero() != b.Latest.IsZero() {
|
||||
if a.Latest.IsZero() {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return b.Latest.Compare(a.Latest)
|
||||
})
|
||||
var rows chunkRows
|
||||
var r Row
|
||||
for _, c := range order {
|
||||
if len(selected) == take && !c.Latest.IsZero() && c.Latest.Before(selected[0].at) {
|
||||
break
|
||||
}
|
||||
ps.visitChunk(&rows, c, &r, func(ref timedRef, r *Row) {
|
||||
if !f.keepsRow(r) {
|
||||
return
|
||||
}
|
||||
if len(selected) < take {
|
||||
heap.Push(&selected, ref)
|
||||
} else if ref.newer(selected[0]) {
|
||||
selected[0] = ref
|
||||
heap.Fix(&selected, 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
return selected
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
)
|
||||
|
||||
// A page's sums are kept per chunk and reused while the chunk's rows and
|
||||
// what pairing gave them are the same. A changed identity or file must be
|
||||
// summed again, not read from the last page.
|
||||
func TestRequestCellsFollowIdentityAndFiles(t *testing.T) {
|
||||
pageHome(t)
|
||||
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.Local))
|
||||
writeCodexIdentity(t, "main-a", "native-main", "vscode")
|
||||
childPath := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30", "rollout-2026-09-30T10-00-00-child-b.jsonl")
|
||||
writeCodexCall(t, childPath, "child-b", "native-main", `{"subagent":{"thread_spawn":{"parent_thread_id":"main-a"}}}`, "resp-local", "m", "low", now.Add(-time.Minute), 40, 4)
|
||||
Append(Record{Time: now.Add(-2 * time.Hour), Agent: "claude", Provider: "openai", Model: "m", Input: 7, Output: 1, Status: 200})
|
||||
|
||||
sums := func(f Filter) (int, int) {
|
||||
page := QueryPage(All, f, 0, 100)
|
||||
return page.Total, page.Sum.Input
|
||||
}
|
||||
for _, offset := range []int{0, 1, 0} {
|
||||
QueryPage(All, Filter{}, offset, 1)
|
||||
}
|
||||
if n, in := sums(Filter{Query: "main-a"}); n != 1 || in != 40 {
|
||||
t.Fatalf("subagent's call under its root: %d rows, %d input", n, in)
|
||||
}
|
||||
|
||||
// Only the parent's file changes: the child's chunk is the same, and
|
||||
// its root is now the parent's parent.
|
||||
for _, f := range []Filter{{Query: "top-z"}, {Query: "main-a"}} {
|
||||
QueryPage(All, f, 0, 100)
|
||||
}
|
||||
writeCodexIdentity(t, "main-a", "native-main", map[string]any{"subagent": map[string]any{"thread_spawn": map[string]any{"parent_thread_id": "top-z"}}})
|
||||
writeCodexIdentity(t, "top-z", "native-main", "vscode")
|
||||
if n, in := sums(Filter{Query: "top-z"}); n != 1 || in != 40 {
|
||||
t.Fatalf("a cached part kept the old root: %d rows, %d input", n, in)
|
||||
}
|
||||
|
||||
// The child is its own main thread now.
|
||||
writeCodexCall(t, childPath, "child-b", "native-main", `"vscode"`, "resp-local", "m", "low", now.Add(-time.Minute), 40, 4)
|
||||
if err := os.Chtimes(childPath, now, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, _ := sums(Filter{Query: "main-a"}); n != 0 {
|
||||
t.Fatalf("a changed file kept its old root: %d rows", n)
|
||||
}
|
||||
if n, in := sums(Filter{Query: "child-b"}); n != 1 || in != 40 {
|
||||
t.Fatalf("new main thread: %d rows, %d input", n, in)
|
||||
}
|
||||
|
||||
// The file's call changes.
|
||||
writeCodexCall(t, childPath, "child-b", "native-main", `"vscode"`, "resp-local", "m", "low", now.Add(-time.Minute), 90, 4)
|
||||
if err := os.Chtimes(childPath, now.Add(time.Second), now.Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, in := sums(Filter{}); n != 2 || in != 97 {
|
||||
t.Fatalf("changed file: %d rows, %d input", n, in)
|
||||
}
|
||||
Append(Record{Time: now.Add(-time.Hour), Agent: "claude", Provider: "openai", Model: "m", Input: 3, Output: 1, Status: 200})
|
||||
equalPage(t, QueryPage(All, Filter{}, 0, 100), pageFromLedger(All, Filter{}, 0, 100, LedgerOf(All, Filter{})))
|
||||
equalPage(t, QueryPage(Week, Filter{}, 0, 100), pageFromLedger(Week, Filter{}, 0, 100, LedgerOf(Week, Filter{})))
|
||||
}
|
||||
+197
-163
@@ -6,7 +6,6 @@ package usage
|
||||
// complete ledger explicitly. This cache is disposable and bounded.
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -122,6 +121,9 @@ type rowChunk struct {
|
||||
Latest time.Time
|
||||
// Computer is the other computer whose day this is (#542), by id
|
||||
Computer string
|
||||
// serial names the chunk as made, for the cells a page keeps of it
|
||||
// (chunkSerial)
|
||||
serial uint64
|
||||
}
|
||||
|
||||
// rowMsg is the Text of a row's Claude message id, after rowText's, and
|
||||
@@ -475,6 +477,11 @@ type requestIndex struct {
|
||||
heats map[pageKey]heatPage
|
||||
// idle trims the chunks once the page goes unasked (keepWhileAsked)
|
||||
idle *time.Timer
|
||||
// parts are the cells of each chunk the last pages of a few partKeys
|
||||
// were added up from, by chunk serial: kept until what prices or
|
||||
// names a call changes (meta), and read without the lock, since a
|
||||
// part is never written once made
|
||||
parts map[partKey]map[uint64]*chunkPart
|
||||
}
|
||||
|
||||
// heatPage is a heatmap's page, of the gateway log's snapshot version,
|
||||
@@ -657,6 +664,13 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
fl.page = page
|
||||
close(fl.done)
|
||||
}()
|
||||
// a rolling window's start moves with now, so its cells are never the
|
||||
// same twice; the heatmap is added up on its own
|
||||
var cache *partCache
|
||||
pk := partKey{p: p, f: f, since: p.Since(now), until: p.Until(now), loc: now.Location()}
|
||||
if p.Last() == 0 && p != heatmapPeriod {
|
||||
cache = &partCache{old: idx.parts[pk], next: map[uint64]*chunkPart{}}
|
||||
}
|
||||
shared := idx
|
||||
idx = shared.private()
|
||||
shared.Unlock()
|
||||
@@ -668,13 +682,20 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
|
||||
if building != nil {
|
||||
building()
|
||||
}
|
||||
page = buildRequestBlocksWithCodex(p, f, offset, limit, now, b.gateways, b.chunks, b.others, names, codexIdentities)
|
||||
page = buildRequestBlocksIn(p, f, offset, limit, now, b.gateways, b.chunks, b.others, names, codexIdentities, cache)
|
||||
ownStrings(reflect.ValueOf(&page).Elem())
|
||||
b.priced.release()
|
||||
shared.Lock()
|
||||
defer shared.Unlock()
|
||||
if !shared.keep(idx, b.on) {
|
||||
return page
|
||||
}
|
||||
if cache != nil {
|
||||
if shared.parts == nil || len(shared.parts) >= partSets && shared.parts[pk] == nil {
|
||||
shared.parts = map[partKey]map[uint64]*chunkPart{}
|
||||
}
|
||||
shared.parts[pk] = cache.next
|
||||
}
|
||||
if len(shared.pages) >= 16 {
|
||||
shared.pages = map[pageKey]RequestPage{}
|
||||
}
|
||||
@@ -701,9 +722,8 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]s
|
||||
idx := shared.private()
|
||||
shared.Unlock()
|
||||
b := readRequestBlocks(idx, st, p, now, sessions.ReadCallSource)
|
||||
_, visit := pairedRows(p, now, b.gateways, b.chunks, b.others, st.codexIdentities)
|
||||
sums := effortSums{}
|
||||
visit(func(_ timedRef, r *Row) { sums.add(r) })
|
||||
pairRows(p, now, b.gateways, b.chunks, b.others, st.codexIdentities).visit(func(_ timedRef, r *Row) { sums.add(r) })
|
||||
b.priced.release()
|
||||
shared.Lock()
|
||||
if shared.keep(idx, b.on) {
|
||||
@@ -811,6 +831,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
|
||||
c.Bytes -= int64(32 * len(c.Strings))
|
||||
c.dict, c.shapeIDs = nil, nil // local chunks are immutable until the source changes
|
||||
c = c.pack()
|
||||
c.serial = nextChunkSerial()
|
||||
}
|
||||
kept, next := *c, *c
|
||||
kept.Used, next.Used = idx.tick, idx.tick
|
||||
@@ -848,6 +869,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Ti
|
||||
c.Bytes -= int64(32 * len(c.Strings))
|
||||
c.dict, c.shapeIDs = nil, nil
|
||||
c = c.pack()
|
||||
c.serial = nextChunkSerial()
|
||||
}
|
||||
kept, next := *c, *c
|
||||
kept.Used, next.Used = idx.tick, idx.tick
|
||||
@@ -871,6 +893,7 @@ func (idx *requestIndex) adopt(st requestState) {
|
||||
idx.chunks = map[string]*rowChunk{}
|
||||
idx.pages = nil
|
||||
idx.heats = nil
|
||||
idx.parts = nil
|
||||
idx.key = ""
|
||||
}
|
||||
if idx.key != st.key {
|
||||
@@ -1265,11 +1288,19 @@ func ownStrings(v reflect.Value) {
|
||||
}
|
||||
|
||||
// pairedRows are the page's rows of p: each gateway call told the Codex
|
||||
// thread of the session file's call it is paired with, and the session
|
||||
// files' calls a gateway call matched, or another file's copy, left out.
|
||||
// visit hands each row on in all's order. The chunks are copies, so the
|
||||
// cached ones are left as they are.
|
||||
func pairedRows(p Period, now time.Time, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity) (all []*rowChunk, visit func(fn func(timedRef, *Row))) {
|
||||
// thread of the session file's call it is paired with (pairs), and the
|
||||
// session files' calls a gateway call matched, or another file's copy,
|
||||
// left out (matched, skip). visit hands each row on in all's order. The
|
||||
// chunks are copies, so the cached ones are left as they are.
|
||||
type pairedRows struct {
|
||||
all []*rowChunk
|
||||
skip, matched map[rowRef]bool
|
||||
pairs map[rowRef]rowRef
|
||||
compactions map[rowRef]*bool
|
||||
since, until time.Time
|
||||
}
|
||||
|
||||
func pairRows(p Period, now time.Time, gateways, chunks, others []*rowChunk, identities map[string]sessions.CodexIdentity) *pairedRows {
|
||||
gateways, chunks, others = cloneCodexChunks(gateways), cloneCodexChunks(chunks), cloneCodexChunks(others)
|
||||
duplicateSkip := foldCodexRows(chunks)
|
||||
pairs, compactions := codexChunkResponsePairs(gateways, chunks, duplicateSkip)
|
||||
@@ -1292,32 +1323,45 @@ func pairedRows(p Period, now time.Time, gateways, chunks, others []*rowChunk, i
|
||||
setCodexActor(gateway.Chunk, gateway.Index, actor)
|
||||
gateway.Chunk.setCodexCompaction(gateway.Index, compactions[local])
|
||||
}
|
||||
all = append(append(slices.Clone(gateways), chunks...), others...)
|
||||
visit = func(fn func(timedRef, *Row)) {
|
||||
var rows chunkRows
|
||||
// one row for the visit, written over for each: fn is not known
|
||||
// here, so a row of each would be an allocation of its own, and fn
|
||||
// keeps none of them
|
||||
var r Row
|
||||
for _, c := range all {
|
||||
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
|
||||
}
|
||||
r = open.row(i)
|
||||
fn(timedOf(ref, pr), &r)
|
||||
}
|
||||
all := append(append(slices.Clone(gateways), chunks...), others...)
|
||||
return &pairedRows{all: all, skip: skip, matched: matched, pairs: pairs, compactions: compactions, since: since, until: until}
|
||||
}
|
||||
|
||||
// visit calls fn with each row of the period that no other one stands for.
|
||||
func (ps *pairedRows) visit(fn func(timedRef, *Row)) {
|
||||
var rows chunkRows
|
||||
// one row for the visit, written over for each: fn is not known
|
||||
// here, so a row of each would be an allocation of its own, and fn
|
||||
// keeps none of them
|
||||
var r Row
|
||||
for _, c := range ps.all {
|
||||
ps.visitChunk(&rows, c, &r, fn)
|
||||
}
|
||||
}
|
||||
|
||||
// visitChunk is visit of c's rows alone, read through rows into r.
|
||||
func (ps *pairedRows) visitChunk(rows *chunkRows, c *rowChunk, r *Row, fn func(timedRef, *Row)) {
|
||||
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(ps.since) || after(ps.until, pr.Time) || len(ps.skip) > 0 && ps.skip[ref] || len(ps.matched) > 0 && ps.matched[ref] {
|
||||
continue
|
||||
}
|
||||
*r = open.row(i)
|
||||
fn(timedOf(ref, pr), r)
|
||||
}
|
||||
return all, visit
|
||||
}
|
||||
|
||||
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 {
|
||||
return buildRequestBlocksIn(p, f, offset, limit, now, gateways, chunks, others, names, identities, nil)
|
||||
}
|
||||
|
||||
// buildRequestBlocksIn is the page added up from each chunk's cells,
|
||||
// cache's for the chunks it has them for (nil: every chunk's read).
|
||||
func buildRequestBlocksIn(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string, identities map[string]sessions.CodexIdentity, cache *partCache) RequestPage {
|
||||
since := p.Since(now)
|
||||
all, visit := pairedRows(p, now, gateways, chunks, others, identities)
|
||||
ps := pairRows(p, now, gateways, chunks, others, identities)
|
||||
out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}}
|
||||
chartFilter := f
|
||||
chartFilter.Day = ""
|
||||
@@ -1325,7 +1369,7 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.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(_ timedRef, r *Row) {
|
||||
ps.visit(func(_ timedRef, r *Row) {
|
||||
if chartFilter.keepsRow(r) {
|
||||
add(*r)
|
||||
}
|
||||
@@ -1350,134 +1394,115 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time,
|
||||
// Bound the requested prefix before adding limit: external offsets can
|
||||
// reach MaxInt, and a page beyond all sources needs no heap at all.
|
||||
maxRows := 0
|
||||
for _, c := range all {
|
||||
for _, c := range ps.all {
|
||||
maxRows += rowsIn(c)
|
||||
}
|
||||
take := 0
|
||||
if offset < maxRows {
|
||||
take = offset + min(limit, maxRows-offset)
|
||||
}
|
||||
selected := newestHeap{}
|
||||
// the two source cells' own numbers, counted without the source pick
|
||||
viaFilter := f
|
||||
viaFilter.Through = ""
|
||||
// a kept cell says which computer its rows are of whether this page
|
||||
// counts computers or not: the next one of its partKey may
|
||||
pass := newCellPass(p, f, now, names != nil || cache != nil)
|
||||
parts := ps.partsOf(pass, cache, identities)
|
||||
var first time.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
|
||||
// Each dimension's groups are counted with its own pick cleared, and
|
||||
// the computers' with the computer's and day's: made once, and read as
|
||||
// the row's own keep when clearing changed nothing, which with no pick
|
||||
// at all is every one of them. A Row is 896 bytes and a page of the
|
||||
// whole history 400,000 of them, so each row's sums are made once (d)
|
||||
// and added to the dozen groups it is in, not read again by each
|
||||
// (#3493).
|
||||
without, withoutDay := map[string]Filter{}, map[string]Filter{}
|
||||
unpicked := map[string]bool{}
|
||||
for _, d := range Dimensions {
|
||||
without[d] = f.Without(d)
|
||||
unpicked[d] = without[d] == f
|
||||
g := without[d]
|
||||
g.Day = ""
|
||||
withoutDay[d] = g
|
||||
// the computers' with the computer's and day's (cellPass): a cell's
|
||||
// bits say which of them its rows are in, and its sums (d), made once,
|
||||
// are added to each (#3493).
|
||||
var r Row
|
||||
add := func(m map[string]*Share, k string, d *Totals) {
|
||||
s := m[k]
|
||||
if s == nil {
|
||||
s = &Share{ID: k}
|
||||
m[k] = s
|
||||
}
|
||||
s.plus(d)
|
||||
}
|
||||
computerFilter := f
|
||||
computerFilter.Computer, computerFilter.Day = "", ""
|
||||
computerUnpicked := computerFilter == f
|
||||
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] {
|
||||
agents[r.Agent] = true
|
||||
for _, part := range parts {
|
||||
if !part.first.IsZero() && (first.IsZero() || part.first.Before(first)) {
|
||||
first = part.first
|
||||
}
|
||||
if !kinds[r.Kind] {
|
||||
kinds[r.Kind] = true
|
||||
}
|
||||
if r.Provider != "" && !providers[r.Provider] {
|
||||
providers[r.Provider] = true
|
||||
}
|
||||
// a call turned away, and a request magpie sent on its own
|
||||
// (SourceProbe), are listed and counted in no total
|
||||
uncounted := r.IsRejected() || r.IsProbe()
|
||||
keep := f.keepsRow(r)
|
||||
if keep {
|
||||
out.Total++
|
||||
if take > 0 && len(selected) < take {
|
||||
heap.Push(&selected, ref)
|
||||
} else if take > 0 && ref.newer(selected[0]) {
|
||||
selected[0] = ref
|
||||
heap.Fix(&selected, 0)
|
||||
for i := range part.cells {
|
||||
cell := &part.cells[i]
|
||||
agent, kind, prov := cell.agent.Value(), cell.kind.Value(), cell.provider.Value()
|
||||
// looked up before they are set: most cells name what an
|
||||
// earlier one did, and a map's lookup is cheaper than its write
|
||||
if !agents[agent] {
|
||||
agents[agent] = true
|
||||
}
|
||||
}
|
||||
var d Totals
|
||||
if !uncounted {
|
||||
d.addRow(*r)
|
||||
if !kinds[kind] {
|
||||
kinds[kind] = true
|
||||
}
|
||||
if prov != "" && !providers[prov] {
|
||||
providers[prov] = true
|
||||
}
|
||||
keep := cell.bits&cellKeep != 0
|
||||
if keep {
|
||||
out.Sum.plus(&d)
|
||||
out.Total += cell.n
|
||||
}
|
||||
addCallerRow(callers, r, &d)
|
||||
addAccountRow(accounts, r, &d)
|
||||
}
|
||||
// The two sources are counted with the Via pick cleared, as the
|
||||
// dimension groups above are: the cells are what the reader
|
||||
// switches between, so each must go on saying its own number
|
||||
// while another is picked, or one of them would read 0 and
|
||||
// there would be no way back.
|
||||
if !uncounted && viaFilter.keepsRow(r) {
|
||||
switch r.Source {
|
||||
case "log":
|
||||
out.Direct.plus(&d)
|
||||
case SourceReported:
|
||||
out.Reported.plus(&d)
|
||||
default:
|
||||
out.Through.plus(&d)
|
||||
}
|
||||
}
|
||||
if uncounted {
|
||||
return
|
||||
}
|
||||
if keep || f.Day != "" && chartFilter.keepsRow(r) {
|
||||
charted = append(charted, ref.rowRef)
|
||||
for _, dim := range Dimensions {
|
||||
k := keys.key(r, dim)
|
||||
s := seriesGroups[dim][k]
|
||||
if s == nil {
|
||||
s = &Share{ID: k}
|
||||
seriesGroups[dim][k] = s
|
||||
}
|
||||
s.plus(&d)
|
||||
}
|
||||
if first.IsZero() || r.Time.Before(first) {
|
||||
first = r.Time
|
||||
}
|
||||
}
|
||||
if names != nil && (computerUnpicked && keep || !computerUnpicked && computerFilter.keepsRow(r)) {
|
||||
k := r.key("computer")
|
||||
if computers[k] == nil {
|
||||
computers[k] = &Share{ID: k}
|
||||
}
|
||||
computers[k].plus(&d)
|
||||
}
|
||||
for _, dim := range Dimensions {
|
||||
if f.Day != "" && withoutDay[dim].keepsRow(r) {
|
||||
k := keys.key(r, dim)
|
||||
if chartGroups[dim][k] == nil {
|
||||
chartGroups[dim][k] = &Share{ID: k}
|
||||
}
|
||||
chartGroups[dim][k].plus(&d)
|
||||
}
|
||||
if unpicked[dim] && !keep || !unpicked[dim] && !without[dim].keepsRow(r) {
|
||||
// a call turned away, and a request magpie sent on its own
|
||||
// (SourceProbe), are listed and counted in no total
|
||||
if cell.bits&cellUncounted != 0 {
|
||||
continue
|
||||
}
|
||||
k := keys.key(r, dim)
|
||||
s := groups[dim][k]
|
||||
if s == nil {
|
||||
s = &Share{ID: k}
|
||||
groups[dim][k] = s
|
||||
d := &cell.d
|
||||
if keep {
|
||||
out.Sum.plus(d)
|
||||
}
|
||||
if id := cell.callerID.Value(); id != "" {
|
||||
g := callers[id]
|
||||
if g == nil {
|
||||
g = &Group{ID: id, CallerKeyID: id}
|
||||
callers[id] = g
|
||||
}
|
||||
g.CallerKeyName = cell.callerName.Value()
|
||||
g.plus(d)
|
||||
}
|
||||
if who := cell.account.Value(); who != "" {
|
||||
k := [2]string{prov, who}
|
||||
g := accounts[k]
|
||||
if g == nil {
|
||||
g = &Group{ID: prov + "@" + who, Provider: prov, Account: who}
|
||||
accounts[k] = g
|
||||
}
|
||||
g.plus(d)
|
||||
}
|
||||
// The two sources are counted with the Via pick cleared, as the
|
||||
// dimension groups are: the cells are what the reader switches
|
||||
// between, so each must go on saying its own number while
|
||||
// another is picked, or one of them would read 0 and there
|
||||
// would be no way back.
|
||||
if cell.bits&cellVia != 0 {
|
||||
switch cell.source {
|
||||
case cellDirect:
|
||||
out.Direct.plus(d)
|
||||
case cellReported:
|
||||
out.Reported.plus(d)
|
||||
default:
|
||||
out.Through.plus(d)
|
||||
}
|
||||
}
|
||||
cell.row(&r)
|
||||
if cell.bits&cellCharted != 0 {
|
||||
for _, dim := range Dimensions {
|
||||
add(seriesGroups[dim], keys.key(&r, dim), d)
|
||||
}
|
||||
}
|
||||
if cell.bits&cellComputer != 0 {
|
||||
add(computers, r.key("computer"), d)
|
||||
}
|
||||
for j, dim := range Dimensions {
|
||||
if cell.bits&(cellChart<<j) != 0 {
|
||||
add(chartGroups[dim], keys.key(&r, dim), d)
|
||||
}
|
||||
if cell.bits&(cellGroup<<j) != 0 {
|
||||
add(groups[dim], keys.key(&r, dim), d)
|
||||
}
|
||||
}
|
||||
s.plus(&d)
|
||||
}
|
||||
})
|
||||
}
|
||||
selected := ps.newest(f, parts, take)
|
||||
slices.SortFunc(selected, func(a, b timedRef) int {
|
||||
if a.newer(b) {
|
||||
return -1
|
||||
@@ -1491,7 +1516,7 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time,
|
||||
for _, ref := range selected[min(offset, len(selected)):] {
|
||||
page = append(page, ref.rowRef)
|
||||
}
|
||||
read := rowsOf(all, page)
|
||||
read := rowsOf(ps.all, page)
|
||||
for _, ref := range page {
|
||||
out.Rows = append(out.Rows, read[ref])
|
||||
}
|
||||
@@ -1524,7 +1549,7 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.Time,
|
||||
}
|
||||
out.Computers, out.Names = computerShares(computers, names)
|
||||
var base []Point
|
||||
chartSince := since
|
||||
var chartSince time.Time
|
||||
chartSince, out.Bucket, base = timeline(p, now, first)
|
||||
out.Series = make([]SeriesPoint, len(base))
|
||||
for i := range base {
|
||||
@@ -1533,26 +1558,35 @@ func buildRequestBlocksOf(p Period, f Filter, offset, limit int, now time.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 := chartRows.row(ref)
|
||||
t := r.Time.In(now.Location())
|
||||
if t.Before(chartSince) {
|
||||
continue
|
||||
}
|
||||
i := bucketIndex(out.Bucket, chartSince, t)
|
||||
if i < 0 || i >= len(out.Series) {
|
||||
continue
|
||||
}
|
||||
pt := &out.Series[i]
|
||||
var d Totals
|
||||
d.addRow(r)
|
||||
pt.plus(&d)
|
||||
for _, dim := range Dimensions {
|
||||
k := keys.key(&r, dim)
|
||||
part := pt.By[dim][k]
|
||||
part.plus(&d)
|
||||
pt.By[dim][k] = part
|
||||
// a cell's bucket is its hour of the period, or its day: the chart of
|
||||
// days or weeks starts at the oldest charted call's, known only now
|
||||
sinceDay := dayNumber(chartSince)
|
||||
for _, part := range parts {
|
||||
for j := range part.cells {
|
||||
cell := &part.cells[j]
|
||||
if cell.bits&cellCharted == 0 || cell.bits&cellUncounted != 0 {
|
||||
continue
|
||||
}
|
||||
i := int(cell.bucket)
|
||||
if !pass.hours {
|
||||
i = int(cell.bucket - sinceDay)
|
||||
if i >= 0 && out.Bucket == "week" {
|
||||
i /= 7
|
||||
}
|
||||
}
|
||||
if i < 0 || i >= len(out.Series) {
|
||||
continue
|
||||
}
|
||||
pt := &out.Series[i]
|
||||
d := &cell.d
|
||||
pt.plus(d)
|
||||
cell.row(&r)
|
||||
for _, dim := range Dimensions {
|
||||
k := keys.key(&r, dim)
|
||||
part := pt.By[dim][k]
|
||||
part.plus(d)
|
||||
pt.By[dim][k] = part
|
||||
}
|
||||
}
|
||||
}
|
||||
// Match LedgerSeries's top-24 selection on the filtered data, not facets.
|
||||
|
||||
Reference in New Issue
Block a user