| 1 | package connect |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | ) |
| 12 | |
| 13 | func notice(thread, turn, total string) json.RawMessage { |
| 14 | return noticeLast(thread, turn, total, `{"inputTokens":1,"outputTokens":1}`) |
| 15 | } |
| 16 | |
| 17 | func noticeLast(thread, turn, total, last string) json.RawMessage { |
| 18 | return json.RawMessage(`{"threadId":"` + thread + `","turnId":"` + turn + `","tokenUsage":{"total":` + total + `,"last":` + last + `}}`) |
| 19 | } |
| 20 | |
| 21 | func feed(t *testing.T, tally *CodexTally, params ...json.RawMessage) { |
| 22 | t.Helper() |
| 23 | for _, p := range params { |
| 24 | thread, turn, total, last, ok := CodexNotice(p) |
| 25 | if !ok { |
| 26 | t.Fatalf("notice %s", p) |
| 27 | } |
| 28 | tally.Notice(thread, turn, total, last) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func get(p *int64) int64 { |
| 33 | if p == nil { |
| 34 | return -1 |
| 35 | } |
| 36 | return *p |
| 37 | } |
| 38 | |
| 39 | // The recorded probe: two notices in one turn; the turn's figure is the |
| 40 | // last total, not the sum and not the last notice's "last". Figures the |
| 41 | // notice did not carry stay null. |
| 42 | func TestCodexTallyRecorded(t *testing.T) { |
| 43 | f, err := os.Open("../provider/codex/testdata/probe.jsonl") |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | defer f.Close() |
| 48 | tally := NewCodexTally("thread-1", true) |
| 49 | tally.Begin("turn-1") |
| 50 | scan := bufio.NewScanner(f) |
| 51 | scan.Buffer(make([]byte, 0, 1<<20), 1<<20) |
| 52 | seen := 0 |
| 53 | for scan.Scan() { |
| 54 | var m struct { |
| 55 | Method string `json:"method"` |
| 56 | Params json.RawMessage `json:"params"` |
| 57 | } |
| 58 | if json.Unmarshal(scan.Bytes(), &m) != nil || m.Method != "thread/tokenUsage/updated" { |
| 59 | continue |
| 60 | } |
| 61 | seen++ |
| 62 | feed(t, tally, m.Params) |
| 63 | } |
| 64 | tally.End() |
| 65 | row := tally.Row() |
| 66 | if seen != 2 || !row.Complete || get(row.InputTokens) != 28254 || get(row.OutputTokens) != 142 || row.CachedInputTokens != nil || row.ReasoningOutputTokens != nil { |
| 67 | t.Fatalf("%d notices, row %+v", seen, row) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | func TestCodexTally(t *testing.T) { |
| 72 | // A fresh process resumes a thread: the replayed notice of the turn |
| 73 | // before is not a verified base, so nothing is subtracted; the row is |
| 74 | // the attempt's own "last" figures summed, complete false. Another |
| 75 | // thread's notice and a resent one change nothing. |
| 76 | tally := NewCodexTally("th", false) |
| 77 | feed(t, tally, notice("th", "old", `{"inputTokens":900,"outputTokens":100,"cachedInputTokens":800}`)) |
| 78 | tally.Begin("t2") |
| 79 | feed(t, tally, |
| 80 | noticeLast("th", "t2", `{"inputTokens":1500,"outputTokens":130,"cachedInputTokens":1100}`, `{"inputTokens":500,"outputTokens":30}`), |
| 81 | notice("other", "t2", `{"inputTokens":99999,"outputTokens":99999}`), |
| 82 | noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`), |
| 83 | noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`)) |
| 84 | tally.End() |
| 85 | row := tally.Row() |
| 86 | if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || row.CachedInputTokens != nil || row.Complete { |
| 87 | t.Fatalf("resumed turn %+v", row) |
| 88 | } |
| 89 | // The next turn in the same process starts from that total: verified, |
| 90 | // complete once its completion is seen. |
| 91 | tally.Begin("t3") |
| 92 | if r := tally.Row(); r.Complete || r.InputTokens != nil { |
| 93 | t.Fatalf("no notice yet: %+v", r) |
| 94 | } |
| 95 | feed(t, tally, notice("th", "t3", `{"inputTokens":1800,"outputTokens":160,"cachedInputTokens":1250}`)) |
| 96 | if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || r.Complete { |
| 97 | t.Fatalf("next turn before its completion %+v", r) |
| 98 | } |
| 99 | tally.End() |
| 100 | if r := tally.Row(); get(r.InputTokens) != 100 || !r.Complete { |
| 101 | t.Fatalf("next turn (verified base) %+v", r) |
| 102 | } |
| 103 | // A late notice of the turn before moves the base, not the figure. |
| 104 | tally.Begin("t4") |
| 105 | feed(t, tally, notice("th", "t3", `{"inputTokens":1900,"outputTokens":170}`), notice("th", "t4", `{"inputTokens":2000,"outputTokens":180}`)) |
| 106 | tally.End() |
| 107 | if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || !r.Complete { |
| 108 | t.Fatalf("late notice %+v", r) |
| 109 | } |
| 110 | // Resumed with no notice before the turn: the first notice already |
| 111 | // includes new use and is counted in full, never subtracted. |
| 112 | cold := NewCodexTally("th", false) |
| 113 | cold.Begin("t9") |
| 114 | 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}`)) |
| 115 | cold.End() |
| 116 | if r := cold.Row(); get(r.InputTokens) != 28254 || get(r.OutputTokens) != 142 || r.Complete { |
| 117 | t.Fatalf("resumed without a base %+v", r) |
| 118 | } |
| 119 | // A thread started here: zero is the verified base; a turn whose |
| 120 | // completion was not seen (cancelled) is never complete. |
| 121 | fresh := NewCodexTally("new", true) |
| 122 | fresh.Begin("y") |
| 123 | feed(t, fresh, notice("new", "y", `{"inputTokens":40,"outputTokens":4}`)) |
| 124 | if r := fresh.Row(); get(r.InputTokens) != 40 || r.Complete { |
| 125 | t.Fatalf("cancelled fresh turn %+v", r) |
| 126 | } |
| 127 | fresh.End() |
| 128 | if r := fresh.Row(); !r.Complete { |
| 129 | t.Fatalf("fresh turn %+v", r) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | func TestClaudeRows(t *testing.T) { |
| 134 | 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}}}`)) |
| 135 | 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 { |
| 136 | t.Fatalf("rows %+v", rows) |
| 137 | } |
| 138 | rows = ClaudeRows([]byte(`{"type":"result","usage":{"input_tokens":10,"output_tokens":5}}`)) |
| 139 | if len(rows) != 1 || rows[0].Model != "" || get(rows[0].OutputTokens) != 5 || rows[0].CacheWriteTokens != nil { |
| 140 | t.Fatalf("no models %+v", rows) |
| 141 | } |
| 142 | var _ = strings.Contains |
| 143 | var _ wire.Usage |
| 144 | } |
| 145 | |
| 146 | // Turns: Claude's num_turns lands on one row of the attempt (the model |
| 147 | // that wrote most), so a sum over rows counts each request once; a |
| 148 | // result without it leaves turns null, never zero. |
| 149 | func TestClaudeRowsTurns(t *testing.T) { |
| 150 | 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}}}`)) |
| 151 | if len(rows) != 2 || rows[0].Turns != nil || get(rows[1].Turns) != 7 { |
| 152 | t.Fatalf("rows %+v", rows) |
| 153 | } |
| 154 | rows = ClaudeRows([]byte(`{"type":"result","num_turns":3,"usage":{"input_tokens":10,"output_tokens":5}}`)) |
| 155 | if len(rows) != 1 || get(rows[0].Turns) != 3 { |
| 156 | t.Fatalf("no models %+v", rows) |
| 157 | } |
| 158 | if rows = ClaudeRows([]byte(`{"type":"result","usage":{"input_tokens":10,"output_tokens":5}}`)); rows[0].Turns != nil { |
| 159 | t.Fatalf("no num_turns %+v", rows) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | // Turns: each distinct usage notice of the attempt's own turn is one |
| 164 | // model request; a resent notice, another thread's, and the turn |
| 165 | // before's late one are not. |
| 166 | func TestCodexTallyTurns(t *testing.T) { |
| 167 | tally := NewCodexTally("th", true) |
| 168 | tally.Begin("t1") |
| 169 | if r := tally.Row(); r.Turns != nil { |
| 170 | t.Fatalf("no notice yet %+v", r) |
| 171 | } |
| 172 | feed(t, tally, |
| 173 | notice("th", "t1", `{"inputTokens":100,"outputTokens":10}`), |
| 174 | notice("th", "t1", `{"inputTokens":100,"outputTokens":10}`), |
| 175 | notice("other", "t1", `{"inputTokens":5,"outputTokens":5}`), |
| 176 | notice("th", "t1", `{"inputTokens":250,"outputTokens":30}`)) |
| 177 | tally.End() |
| 178 | if r := tally.Row(); get(r.Turns) != 2 { |
| 179 | t.Fatalf("first turn %+v", r) |
| 180 | } |
| 181 | tally.Begin("t2") |
| 182 | feed(t, tally, notice("th", "t1", `{"inputTokens":260,"outputTokens":31}`), notice("th", "t2", `{"inputTokens":400,"outputTokens":40}`)) |
| 183 | if r := tally.Row(); get(r.Turns) != 1 { |
| 184 | t.Fatalf("second turn %+v", r) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | // The recorded CLI's modelUsage is the session's running total (in a |
| 189 | // resumed session too); each result's own use is |
| 190 | // model_usage_since_last_result. A row is that, never the running |
| 191 | // total, so a second turn or a resumed session counts only itself. |
| 192 | func TestClaudeRowsPerResult(t *testing.T) { |
| 193 | for file, want := range map[string][][4]int64{ |
| 194 | // Two turns in one process: 2+3906 written, then 2+3566 read+378 written. |
| 195 | "../provider/claude/testdata/stdout.jsonl": {{2, 3, 0, 3906}, {2, 3, 3566, 378}}, |
| 196 | // A resumed session's turn: its own figures, not the 6/9 so far. |
| 197 | "../provider/claude/testdata/resume-stdout.jsonl": {{2, 3, 3919, 63}}, |
| 198 | } { |
| 199 | raw, err := os.ReadFile(file) |
| 200 | if err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | var got [][4]int64 |
| 204 | for _, line := range strings.Split(string(raw), "\n") { |
| 205 | if !strings.Contains(line, `"type":"result"`) { |
| 206 | continue |
| 207 | } |
| 208 | rows := ClaudeRows([]byte(line)) |
| 209 | if len(rows) != 1 || rows[0].Model != "claude-haiku-5-5" || get(rows[0].Turns) != 1 { |
| 210 | t.Fatalf("%s: rows %+v", file, rows) |
| 211 | } |
| 212 | got = append(got, [4]int64{get(rows[0].InputTokens), get(rows[0].OutputTokens), get(rows[0].CachedInputTokens), get(rows[0].CacheWriteTokens)}) |
| 213 | } |
| 214 | if len(got) != len(want) { |
| 215 | t.Fatalf("%s: %v, want %v", file, got, want) |
| 216 | } |
| 217 | for i := range want { |
| 218 | if got[i] != want[i] { |
| 219 | t.Fatalf("%s result %d: %v, want %v", file, i, got[i], want[i]) |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // The recorded app-server's notice carries the thread's running total |
| 226 | // (and the last request's figures). A tally's row is per turn, never |
| 227 | // that running total: the recorded turn replayed as a second turn of |
| 228 | // the same thread (its totals continuing from the first's, as the |
| 229 | // app-server reports them) gives the same figures again, verified and |
| 230 | // complete; replayed in a process that resumed the thread (no base), it |
| 231 | // is the sum of the turn's own requests it saw, never complete. |
| 232 | func TestCodexTallyRecordedPerTurn(t *testing.T) { |
| 233 | raw, err := os.ReadFile("../provider/codex/testdata/probe.jsonl") |
| 234 | if err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | var notices []json.RawMessage |
| 238 | for _, line := range strings.Split(string(raw), "\n") { |
| 239 | var m struct { |
| 240 | Method string `json:"method"` |
| 241 | Params json.RawMessage `json:"params"` |
| 242 | } |
| 243 | if json.Unmarshal([]byte(line), &m) == nil && m.Method == "thread/tokenUsage/updated" { |
| 244 | notices = append(notices, m.Params) |
| 245 | } |
| 246 | } |
| 247 | if len(notices) != 2 { |
| 248 | t.Fatalf("%d notices", len(notices)) |
| 249 | } |
| 250 | // turn replays the recorded notices as turn id, its totals offset by |
| 251 | // what the thread had used before it. |
| 252 | turn := func(tally *CodexTally, id string, base, baseOut int64) { |
| 253 | tally.Begin(id) |
| 254 | for _, p := range notices { |
| 255 | thread, _, total, last, ok := CodexNotice(p) |
| 256 | if !ok { |
| 257 | t.Fatal("notice") |
| 258 | } |
| 259 | in, out := *total.Input+base, *total.Output+baseOut |
| 260 | total.Input, total.Output = &in, &out |
| 261 | tally.Notice(thread, id, total, last) |
| 262 | } |
| 263 | tally.End() |
| 264 | } |
| 265 | same := NewCodexTally("thread-1", true) |
| 266 | turn(same, "turn-1", 0, 0) |
| 267 | first := same.Row() |
| 268 | turn(same, "turn-2", 28254, 142) |
| 269 | second := same.Row() |
| 270 | if get(first.InputTokens) != 28254 || get(second.InputTokens) != 28254 || get(second.OutputTokens) != 142 || !second.Complete || get(second.Turns) != 2 { |
| 271 | t.Fatalf("per turn in one process: first %+v second %+v", first, second) |
| 272 | } |
| 273 | resumed := NewCodexTally("thread-1", false) |
| 274 | turn(resumed, "turn-3", 56508, 284) |
| 275 | if r := resumed.Row(); get(r.InputTokens) != 14200 || r.Complete || get(r.Turns) != 2 { |
| 276 | t.Fatalf("resumed: %+v", r) |
| 277 | } |
| 278 | } |
| 279 | |