package connect import ( "bufio" "encoding/json" "os" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) func notice(thread, turn, total string) json.RawMessage { return noticeLast(thread, turn, total, `{"inputTokens":1,"outputTokens":1}`) } func noticeLast(thread, turn, total, last string) json.RawMessage { return json.RawMessage(`{"threadId":"` + thread + `","turnId":"` + turn + `","tokenUsage":{"total":` + total + `,"last":` + last + `}}`) } func feed(t *testing.T, tally *CodexTally, params ...json.RawMessage) { t.Helper() for _, p := range params { thread, turn, total, last, ok := CodexNotice(p) if !ok { t.Fatalf("notice %s", p) } tally.Notice(thread, turn, total, last) } } func get(p *int64) int64 { if p == nil { return -1 } return *p } // The recorded probe: two notices in one turn; the turn's figure is the // last total, not the sum and not the last notice's "last". Figures the // notice did not carry stay null. func TestCodexTallyRecorded(t *testing.T) { f, err := os.Open("../provider/codex/testdata/probe.jsonl") if err != nil { t.Fatal(err) } defer f.Close() tally := NewCodexTally("thread-1", true) tally.Begin("turn-1") scan := bufio.NewScanner(f) scan.Buffer(make([]byte, 0, 1<<20), 1<<20) seen := 0 for scan.Scan() { var m struct { Method string `json:"method"` Params json.RawMessage `json:"params"` } if json.Unmarshal(scan.Bytes(), &m) != nil || m.Method != "thread/tokenUsage/updated" { continue } seen++ feed(t, tally, m.Params) } tally.End() row := tally.Row() if seen != 2 || !row.Complete || get(row.InputTokens) != 28254 || get(row.OutputTokens) != 142 || row.CachedInputTokens != nil || row.ReasoningOutputTokens != nil { t.Fatalf("%d notices, row %+v", seen, row) } } func TestCodexTally(t *testing.T) { // A fresh process resumes a thread: the replayed notice of the turn // before is not a verified base, so nothing is subtracted; the row is // the attempt's own "last" figures summed, complete false. Another // thread's notice and a resent one change nothing. tally := NewCodexTally("th", false) feed(t, tally, notice("th", "old", `{"inputTokens":900,"outputTokens":100,"cachedInputTokens":800}`)) tally.Begin("t2") feed(t, tally, noticeLast("th", "t2", `{"inputTokens":1500,"outputTokens":130,"cachedInputTokens":1100}`, `{"inputTokens":500,"outputTokens":30}`), notice("other", "t2", `{"inputTokens":99999,"outputTokens":99999}`), noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`), noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`)) tally.End() row := tally.Row() if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || row.CachedInputTokens != nil || row.Complete { t.Fatalf("resumed turn %+v", row) } // The next turn in the same process starts from that total: verified, // complete once its completion is seen. tally.Begin("t3") if r := tally.Row(); r.Complete || r.InputTokens != nil { t.Fatalf("no notice yet: %+v", r) } feed(t, tally, notice("th", "t3", `{"inputTokens":1800,"outputTokens":160,"cachedInputTokens":1250}`)) if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || r.Complete { t.Fatalf("next turn before its completion %+v", r) } tally.End() if r := tally.Row(); get(r.InputTokens) != 100 || !r.Complete { t.Fatalf("next turn (verified base) %+v", r) } // A late notice of the turn before moves the base, not the figure. tally.Begin("t4") feed(t, tally, notice("th", "t3", `{"inputTokens":1900,"outputTokens":170}`), notice("th", "t4", `{"inputTokens":2000,"outputTokens":180}`)) tally.End() if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || !r.Complete { t.Fatalf("late notice %+v", r) } // Resumed with no notice before the turn: the first notice already // includes new use and is counted in full, never subtracted. cold := NewCodexTally("th", false) cold.Begin("t9") feed(t, cold, noticeLast("th", "t9", `{"inputTokens":14054,"outputTokens":96}`, `{"inputTokens":14054,"outputTokens":96}`), noticeLast("th", "t9", `{"inputTokens":28254,"outputTokens":142}`, `{"inputTokens":14200,"outputTokens":46}`)) cold.End() if r := cold.Row(); get(r.InputTokens) != 28254 || get(r.OutputTokens) != 142 || r.Complete { t.Fatalf("resumed without a base %+v", r) } // A thread started here: zero is the verified base; a turn whose // completion was not seen (cancelled) is never complete. fresh := NewCodexTally("new", true) fresh.Begin("y") feed(t, fresh, notice("new", "y", `{"inputTokens":40,"outputTokens":4}`)) if r := fresh.Row(); get(r.InputTokens) != 40 || r.Complete { t.Fatalf("cancelled fresh turn %+v", r) } fresh.End() if r := fresh.Row(); !r.Complete { t.Fatalf("fresh turn %+v", r) } } func TestClaudeRows(t *testing.T) { rows := ClaudeRows([]byte(`{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":3},"modelUsage":{"claude-opus-5-5":{"inputTokens":99,"outputTokens":99}},"model_usage_since_last_result":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":4,"cacheReadInputTokens":3,"cacheCreationInputTokens":0},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`)) if len(rows) != 2 || rows[0].Model != "claude-haiku-5" || get(rows[1].InputTokens) != 8 || rows[0].CachedInputTokens != nil || rows[1].ReasoningOutputTokens != nil || !rows[0].Complete { t.Fatalf("rows %+v", rows) } rows = ClaudeRows([]byte(`{"type":"result","usage":{"input_tokens":10,"output_tokens":5}}`)) if len(rows) != 1 || rows[0].Model != "" || get(rows[0].OutputTokens) != 5 || rows[0].CacheWriteTokens != nil { t.Fatalf("no models %+v", rows) } var _ = strings.Contains var _ wire.Usage } // Turns: Claude's num_turns lands on one row of the attempt (the model // that wrote most), so a sum over rows counts each request once; a // result without it leaves turns null, never zero. func TestClaudeRowsTurns(t *testing.T) { rows := ClaudeRows([]byte(`{"type":"result","num_turns":7,"model_usage_since_last_result":{"claude-opus-5-5":{"inputTokens":8,"outputTokens":40},"claude-haiku-5":{"inputTokens":2,"outputTokens":1}}}`)) if len(rows) != 2 || rows[0].Turns != nil || get(rows[1].Turns) != 7 { t.Fatalf("rows %+v", rows) } rows = ClaudeRows([]byte(`{"type":"result","num_turns":3,"usage":{"input_tokens":10,"output_tokens":5}}`)) if len(rows) != 1 || get(rows[0].Turns) != 3 { t.Fatalf("no models %+v", rows) } if rows = ClaudeRows([]byte(`{"type":"result","usage":{"input_tokens":10,"output_tokens":5}}`)); rows[0].Turns != nil { t.Fatalf("no num_turns %+v", rows) } } // Turns: each distinct usage notice of the attempt's own turn is one // model request; a resent notice, another thread's, and the turn // before's late one are not. func TestCodexTallyTurns(t *testing.T) { tally := NewCodexTally("th", true) tally.Begin("t1") if r := tally.Row(); r.Turns != nil { t.Fatalf("no notice yet %+v", r) } feed(t, tally, notice("th", "t1", `{"inputTokens":100,"outputTokens":10}`), notice("th", "t1", `{"inputTokens":100,"outputTokens":10}`), notice("other", "t1", `{"inputTokens":5,"outputTokens":5}`), notice("th", "t1", `{"inputTokens":250,"outputTokens":30}`)) tally.End() if r := tally.Row(); get(r.Turns) != 2 { t.Fatalf("first turn %+v", r) } tally.Begin("t2") feed(t, tally, notice("th", "t1", `{"inputTokens":260,"outputTokens":31}`), notice("th", "t2", `{"inputTokens":400,"outputTokens":40}`)) if r := tally.Row(); get(r.Turns) != 1 { t.Fatalf("second turn %+v", r) } } // The recorded CLI's modelUsage is the session's running total (in a // resumed session too); each result's own use is // model_usage_since_last_result. A row is that, never the running // total, so a second turn or a resumed session counts only itself. func TestClaudeRowsPerResult(t *testing.T) { for file, want := range map[string][][4]int64{ // Two turns in one process: 2+3906 written, then 2+3566 read+378 written. "../provider/claude/testdata/stdout.jsonl": {{2, 3, 0, 3906}, {2, 3, 3566, 378}}, // A resumed session's turn: its own figures, not the 6/9 so far. "../provider/claude/testdata/resume-stdout.jsonl": {{2, 3, 3919, 63}}, } { raw, err := os.ReadFile(file) if err != nil { t.Fatal(err) } var got [][4]int64 for _, line := range strings.Split(string(raw), "\n") { if !strings.Contains(line, `"type":"result"`) { continue } rows := ClaudeRows([]byte(line)) if len(rows) != 1 || rows[0].Model != "claude-haiku-5-5" || get(rows[0].Turns) != 1 { t.Fatalf("%s: rows %+v", file, rows) } got = append(got, [4]int64{get(rows[0].InputTokens), get(rows[0].OutputTokens), get(rows[0].CachedInputTokens), get(rows[0].CacheWriteTokens)}) } if len(got) != len(want) { t.Fatalf("%s: %v, want %v", file, got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("%s result %d: %v, want %v", file, i, got[i], want[i]) } } } } // The recorded app-server's notice carries the thread's running total // (and the last request's figures). A tally's row is per turn, never // that running total: the recorded turn replayed as a second turn of // the same thread (its totals continuing from the first's, as the // app-server reports them) gives the same figures again, verified and // complete; replayed in a process that resumed the thread (no base), it // is the sum of the turn's own requests it saw, never complete. func TestCodexTallyRecordedPerTurn(t *testing.T) { raw, err := os.ReadFile("../provider/codex/testdata/probe.jsonl") if err != nil { t.Fatal(err) } var notices []json.RawMessage for _, line := range strings.Split(string(raw), "\n") { var m struct { Method string `json:"method"` Params json.RawMessage `json:"params"` } if json.Unmarshal([]byte(line), &m) == nil && m.Method == "thread/tokenUsage/updated" { notices = append(notices, m.Params) } } if len(notices) != 2 { t.Fatalf("%d notices", len(notices)) } // turn replays the recorded notices as turn id, its totals offset by // what the thread had used before it. turn := func(tally *CodexTally, id string, base, baseOut int64) { tally.Begin(id) for _, p := range notices { thread, _, total, last, ok := CodexNotice(p) if !ok { t.Fatal("notice") } in, out := *total.Input+base, *total.Output+baseOut total.Input, total.Output = &in, &out tally.Notice(thread, id, total, last) } tally.End() } same := NewCodexTally("thread-1", true) turn(same, "turn-1", 0, 0) first := same.Row() turn(same, "turn-2", 28254, 142) second := same.Row() if get(first.InputTokens) != 28254 || get(second.InputTokens) != 28254 || get(second.OutputTokens) != 142 || !second.Complete || get(second.Turns) != 2 { t.Fatalf("per turn in one process: first %+v second %+v", first, second) } resumed := NewCodexTally("thread-1", false) turn(resumed, "turn-3", 56508, 284) if r := resumed.Row(); get(r.InputTokens) != 14200 || r.Complete || get(r.Turns) != 2 { t.Fatalf("resumed: %+v", r) } }