diff --git a/internal/usage/cold_split.go b/internal/usage/cold_split.go index 1e84c74a2..d0fd36d0b 100644 --- a/internal/usage/cold_split.go +++ b/internal/usage/cold_split.go @@ -1,8 +1,10 @@ package usage import ( + "slices" "sync" "time" + "unsafe" ) // A first start, with no sums kept on disk, built the page's cells, the @@ -26,8 +28,9 @@ var coldSpanning func(chunks int) // coldSpans calls fn for each span of days from since, or the day of the // oldest row of sets, to cut, with the chunks of sets a pairing of that // span reaches: those with a row from heatReach before it to heatReach -// after. A gateway block not priced yet is priced for its span alone, and -// let go after it. False: coldSpan is zero, and fn was not called. +// after, of a chunk reaching past that its rows within it alone +// (within). A gateway block not priced yet is priced for its span alone, +// and let go after it. False: coldSpan is zero, and fn was not called. func coldSpans(since, cut time.Time, sets [3][]*rowChunk, fn func(from, to time.Time, span [3][]*rowChunk)) bool { if coldSpan <= 0 { return false @@ -70,6 +73,10 @@ func coldSpans(since, cut time.Time, sets [3][]*rowChunk, fn func(from, to time. copy := *c copy.lazy = alone[b] c = © + } else if c.raw == nil && (at.Before(lo) || !c.Latest.Before(hi)) { + if c = c.within(lo, hi); c == nil { + continue + } } span[k] = append(span[k], c) } @@ -86,6 +93,39 @@ func coldSpans(since, cut time.Time, sets [3][]*rowChunk, fn func(from, to time. return true } +// within is c's rows from lo to before hi, and those of no time, as a +// chunk of its own; nil for none. A session written over weeks was +// paired whole in each span it reached: the last spans of a long +// history paired ~340k rows each, ~230k of them a few hundred such +// files' (#2278). Its rows past a span's reach pair with none of it. +func (c *rowChunk) within(lo, hi time.Time) *rowChunk { + var rows chunkRows + defer rows.release() + open := rows.of(c) + out := &rowChunk{Source: c.Source, Computer: c.Computer} + var actors codexActors + for i := range open.Rows { + p := &open.Rows[i] + if t := p.Time(); !t.IsZero() && (t.Before(lo) || !t.Before(hi)) { + continue + } + out.Rows = append(out.Rows, *p) + if c.codexActors.ids != nil { + actors.add(c.codexActors.at(i)) + } + if t := p.Time(); t.After(out.Latest) { + out.Latest = t + } + } + if len(out.Rows) == 0 { + return nil + } + out.Strings, out.Shapes, out.codexActors = slices.Clone(open.Strings), slices.Clone(open.Shapes), actors + out.Count = len(out.Rows) + out.Bytes = int64(len(out.Rows)) * int64(unsafe.Sizeof(packedRow{})) + return out +} + // alone is a pricer of b's prices that keeps the blocks it prices to // itself, until release. func (b *blockPricer) alone() *blockPricer { diff --git a/internal/usage/cold_split_test.go b/internal/usage/cold_split_test.go index 307b715be..495dc23cc 100644 --- a/internal/usage/cold_split_test.go +++ b/internal/usage/cold_split_test.go @@ -1,6 +1,8 @@ package usage import ( + "encoding/json" + "fmt" "os" "path/filepath" "reflect" @@ -29,6 +31,9 @@ func TestFirstBuildPairsSpans(t *testing.T) { path := filepath.Join(sessions.CodexDir(), "sessions", at.Format("2006/01/02"), "rollout-"+at.Format("2006-01-02T15-04-05")+"-z.jsonl") writeCodexCall(t, path, "z", "sz", `"vscode"`, "resp-z", "m", "high", at, 300, 30) Append(Record{Time: at.Add(time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 300, Output: 30, Status: 200, ResponseID: "resp-z", Session: "sz"}) + // a Codex thread written over three weeks, one file: a call 20 days + // back and one 2 days back, each through magpie too + writeLongCodexThread(t, yesterday.AddDate(0, 0, -20), yesterday.AddDate(0, 0, -1)) // a call through magpie alone, 30 days back Append(Record{Time: yesterday.AddDate(0, 0, -30), Agent: "claude-code", Provider: "anthropic", Model: "c", Input: 50, Output: 5, Status: 200}) restart := func() { @@ -96,7 +101,39 @@ func TestFirstBuildPairsSpans(t *testing.T) { t.Fatalf("%d days a span: effort %+v, paired at once %+v", days, got.effort, whole.effort) } } - if whole.page.Total != 9 { + if whole.page.Total != 11 { t.Fatalf("page: %d rows", whole.page.Total) } } + +// writeLongCodexThread writes one Codex rollout with a call at each of +// ats, and the gateway's row of each. +func writeLongCodexThread(t *testing.T, ats ...time.Time) { + t.Helper() + path := filepath.Join(sessions.CodexDir(), "sessions", ats[0].Format("2006/01/02"), "rollout-"+ats[0].Format("2006-01-02T15-04-05")+"-long.jsonl") + lines := []any{map[string]any{"timestamp": ats[0].Add(-time.Minute).Format(time.RFC3339Nano), "type": "session_meta", "payload": map[string]any{"id": "long", "session_id": "slong", "source": "vscode"}}} + for i, at := range ats { + response := fmt.Sprintf("resp-long-%d", i) + lines = append(lines, + map[string]any{"timestamp": at.Add(-time.Second).Format(time.RFC3339Nano), "type": "turn_context", "payload": map[string]any{"turn_id": "turn-" + response, "model": "m", "effort": "low"}}, + map[string]any{"timestamp": at.Format(time.RFC3339Nano), "type": "token_usage_record", "payload": map[string]any{ + "response_id": response, "session_id": "slong", "thread_id": "long", "turn_id": "turn-" + response, + "usage": map[string]int{"input_tokens": 70 + i, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 7, "reasoning_output_tokens": 0, "total_tokens": 77 + i}, + }}) + Append(Record{Time: at.Add(time.Second), Agent: "codex", Provider: "openai", Model: "m", Input: 70 + i, Output: 7, Status: 200, ResponseID: response, Session: "slong"}) + } + var data []byte + for _, line := range lines { + b, err := json.Marshal(line) + if err != nil { + t.Fatal(err) + } + data = append(append(data, b...), '\n') + } + if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } +}