| 1 | package pi |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | ) |
| 13 | |
| 14 | func replay(t *testing.T, name string) (*Decoder, []provider.Event) { |
| 15 | t.Helper() |
| 16 | f, err := os.Open("testdata/" + name + ".jsonl") |
| 17 | if err != nil { |
| 18 | t.Fatal(err) |
| 19 | } |
| 20 | defer f.Close() |
| 21 | d := &Decoder{} |
| 22 | var out []provider.Event |
| 23 | s := bufio.NewScanner(f) |
| 24 | s.Buffer(make([]byte, 0, 1<<20), 1<<22) |
| 25 | for s.Scan() { |
| 26 | evs, err := d.Decode(s.Bytes()) |
| 27 | if err != nil { |
| 28 | t.Fatalf("%s: %v", s.Bytes(), err) |
| 29 | } |
| 30 | out = append(out, evs...) |
| 31 | } |
| 32 | return d, out |
| 33 | } |
| 34 | |
| 35 | func kinds(evs []provider.Event) []string { |
| 36 | var out []string |
| 37 | for _, e := range evs { |
| 38 | out = append(out, e.Kind) |
| 39 | } |
| 40 | return out |
| 41 | } |
| 42 | |
| 43 | // Pi's RPC events map to Equipo's kinds (connectors spec §3, "Mapping"): |
| 44 | // text deltas, tool calls and results by their call id, the extension's |
| 45 | // question as an ask, each assistant message's usage, and done once Pi |
| 46 | // will not retry. Command responses are not events. |
| 47 | func TestDecodeRecordedRuns(t *testing.T) { |
| 48 | _, evs := replay(t, "text") |
| 49 | if got := kinds(evs); !slices.Equal(got, []string{KindDelta, KindDelta, KindUsage, KindDone}) { |
| 50 | t.Fatalf("text run: %v", got) |
| 51 | } |
| 52 | var delta struct{ Text string } |
| 53 | json.Unmarshal(evs[0].Payload, &delta) |
| 54 | if delta.Text != "ok " { |
| 55 | t.Fatalf("delta %s", evs[0].Payload) |
| 56 | } |
| 57 | var done Done |
| 58 | json.Unmarshal(evs[3].Payload, &done) |
| 59 | if done.Status != StatusCompleted || done.Failure != "" { |
| 60 | t.Fatalf("done %+v", done) |
| 61 | } |
| 62 | |
| 63 | _, evs = replay(t, "mcp-tool") |
| 64 | if got := kinds(evs); !slices.Equal(got, []string{KindUsage, KindToolCall, KindToolResult, KindDelta, KindDelta, KindUsage, KindDone}) { |
| 65 | t.Fatalf("tool run: %v", got) |
| 66 | } |
| 67 | var call ToolCall |
| 68 | json.Unmarshal(evs[1].Payload, &call) |
| 69 | if call.ID != "call_1" || call.Tool != "mcp__equipo__submit_review" || string(call.Args) != `{"verdict":"approve"}` { |
| 70 | t.Fatalf("call %+v", call) |
| 71 | } |
| 72 | var result ToolResult |
| 73 | json.Unmarshal(evs[2].Payload, &result) |
| 74 | if result.ID != "call_1" || result.IsError { |
| 75 | t.Fatalf("result %+v", result) |
| 76 | } |
| 77 | |
| 78 | _, evs = replay(t, "blocked-tool") |
| 79 | i := slices.Index(kinds(evs), KindAsk) |
| 80 | if i < 0 { |
| 81 | t.Fatalf("no ask: %v", kinds(evs)) |
| 82 | } |
| 83 | var ask Ask |
| 84 | json.Unmarshal(evs[i].Payload, &ask) |
| 85 | if ask.ID == "" || ask.Method != "confirm" || ask.Call.Tool != "read" || ask.Call.ID != "call_1" { |
| 86 | t.Fatalf("ask %+v", ask) |
| 87 | } |
| 88 | json.Unmarshal(evs[i+1].Payload, &result) |
| 89 | if evs[i+1].Kind != KindToolResult || !result.IsError { |
| 90 | t.Fatalf("blocked result %s %s", evs[i+1].Kind, evs[i+1].Payload) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // How a run ends: aborted is interrupted; a refused key and an |
| 95 | // exhausted rate limit are failures of their classes, and a retry Pi |
| 96 | // will make is not an end. |
| 97 | func TestDecodeEndings(t *testing.T) { |
| 98 | for _, tc := range []struct { |
| 99 | name, status, failure string |
| 100 | }{ |
| 101 | {"abort", StatusInterrupted, ""}, |
| 102 | {"key-refused", StatusFailed, FailAuth}, |
| 103 | {"rate-limited", StatusFailed, FailQuota}, |
| 104 | } { |
| 105 | t.Run(tc.name, func(t *testing.T) { |
| 106 | _, evs := replay(t, tc.name) |
| 107 | var ends []Done |
| 108 | for _, e := range evs { |
| 109 | if e.Kind == KindDone { |
| 110 | var d Done |
| 111 | json.Unmarshal(e.Payload, &d) |
| 112 | ends = append(ends, d) |
| 113 | } |
| 114 | } |
| 115 | if len(ends) != 1 || ends[0].Status != tc.status || ends[0].Failure != tc.failure { |
| 116 | t.Fatalf("ends %+v", ends) |
| 117 | } |
| 118 | }) |
| 119 | } |
| 120 | d := &Decoder{} |
| 121 | evs, _ := d.Decode([]byte(`{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"Connection error.: connect ECONNREFUSED 127.0.0.1:18080","model":"m","usage":{"input":0,"output":0}}}`)) |
| 122 | evs2, _ := d.Decode([]byte(`{"type":"agent_end","willRetry":false}`)) |
| 123 | var done Done |
| 124 | json.Unmarshal(evs2[0].Payload, &done) |
| 125 | if len(evs) != 1 || done.Status != StatusFailed || done.Failure != FailProvider { |
| 126 | t.Fatalf("connection error: %v %+v", kinds(evs), done) |
| 127 | } |
| 128 | // §16.4: a model the provider does not have is the model's fault. |
| 129 | for msg, want := range map[string]string{`404: {"error":{"code":"model_not_found"}}`: FailModel, `400: {"error":{"code":"model_not_found"}}`: FailModel, `400: {"error":"bad request"}`: FailProvider, `500: model_not_found`: FailProvider} { |
| 130 | if got := failure(msg); got != want { |
| 131 | t.Fatalf("%s: %s, want %s", msg, got, want) |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // Unknown events are counted by type name and dropped: nothing else of |
| 137 | // them is kept. |
| 138 | func TestDecodeUnknownEvents(t *testing.T) { |
| 139 | d := &Decoder{} |
| 140 | for _, line := range []string{`{"type":"brand_new","secret":"tx-abc"}`, `{"type":"brand_new"}`, `{"type":"agent_start"}`, `{"type":"auto_retry_start","attempt":1}`, `{"type":"extension_ui_request","id":"x","method":"notify","message":"hi"}`} { |
| 141 | evs, err := d.Decode([]byte(line)) |
| 142 | if err != nil || len(evs) != 0 { |
| 143 | t.Fatalf("%s: %v %v", line, evs, err) |
| 144 | } |
| 145 | } |
| 146 | if len(d.Unknown) != 1 || d.Unknown["brand_new"] != 2 { |
| 147 | t.Fatalf("unknown %v", d.Unknown) |
| 148 | } |
| 149 | raw, _ := json.Marshal(d.Unknown) |
| 150 | if strings.Contains(string(raw), "tx-abc") { |
| 151 | t.Fatal("an unknown event's content was kept") |
| 152 | } |
| 153 | if _, err := d.Decode([]byte(`not json`)); err == nil { |
| 154 | t.Fatal("a broken record accepted") |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // An attempt's usage is the sum over its assistant messages' usage, with |
| 159 | // Pi's input already uncached; it is complete only once the run ended. |
| 160 | // Pi's own cost is the reported cost, in micro-units, when Pi priced it. |
| 161 | func TestTallyUsage(t *testing.T) { |
| 162 | tally := &Tally{} |
| 163 | _, evs := replay(t, "mcp-tool") |
| 164 | for i, e := range evs { |
| 165 | if e.Kind == KindDone { |
| 166 | if row := tally.Row(); row.Complete { |
| 167 | t.Fatal("complete before the end") |
| 168 | } |
| 169 | } |
| 170 | tally.Add(e) |
| 171 | _ = i |
| 172 | } |
| 173 | row := tally.Row() |
| 174 | if !row.Complete || row.Model != "z-ai/glm-5.3" || *row.InputTokens != 120 || *row.CachedInputTokens != 80 || *row.OutputTokens != 14 || *row.CacheWriteTokens != 0 || row.CostReportedMicros != nil { |
| 175 | t.Fatalf("row %+v", row) |
| 176 | } |
| 177 | if *row.Turns != 2 { |
| 178 | t.Fatalf("turns %d", *row.Turns) |
| 179 | } |
| 180 | priced := &Tally{} |
| 181 | priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0123456,"priced":true}`)}) |
| 182 | priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0000001,"priced":true}`)}) |
| 183 | priced.Add(provider.Event{Kind: KindDone, Payload: json.RawMessage(`{"status":"completed"}`)}) |
| 184 | if r := priced.Row(); r.CostReportedMicros == nil || *r.CostReportedMicros != 12346 { |
| 185 | t.Fatalf("reported %v", r.CostReportedMicros) |
| 186 | } |
| 187 | // A run that ended without its end seen is incomplete. |
| 188 | cut := &Tally{} |
| 189 | cut.Add(evs[0]) |
| 190 | if cut.Row().Complete { |
| 191 | t.Fatal("complete without an end") |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func TestFamilyFromModel(t *testing.T) { |
| 196 | for model, want := range map[string]string{"z-ai/glm-5.3": "glm", "z-ai/glm-5.3-flash": "glm", "moonshotai/kimi-k3.1-pro": "kimi", "deepseek/deepseek-v4-pro-0813": "deepseek", "minimax/minimax-m3.1-flash": "minimax", "qwen/qwen3.8-27b": "qwen", "other/thing": "other", "": ""} { |
| 197 | if got := Family(model); got != want { |
| 198 | t.Errorf("%s: %q want %q", model, got, want) |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // Usage Pi did not give, or gave in a shape that cannot be counted, |
| 204 | // stays unknown even when the run ends properly: no message's usage at |
| 205 | // all, a message without its usage or without input or output, a |
| 206 | // negative figure, a sum that overflows. Unknown is never zero. |
| 207 | func TestTallyUnknownUsage(t *testing.T) { |
| 208 | end := `{"type":"agent_end","willRetry":false}` |
| 209 | msg := func(usage string) string { |
| 210 | return `{"type":"message_end","message":{"role":"assistant","model":"m","stopReason":"stop"` + usage + `}}` |
| 211 | } |
| 212 | for _, tc := range []struct { |
| 213 | name string |
| 214 | lines []string |
| 215 | }{ |
| 216 | {"no message at all", []string{end}}, |
| 217 | {"a message without usage", []string{msg(``), end}}, |
| 218 | {"usage without input", []string{msg(`,"usage":{"output":3}`), end}}, |
| 219 | {"usage without output", []string{msg(`,"usage":{"input":3}`), end}}, |
| 220 | {"a negative figure", []string{msg(`,"usage":{"input":-1,"output":3}`), end}}, |
| 221 | {"usage that is not an object", []string{msg(`,"usage":"lots"`), end}}, |
| 222 | {"one good message, one without usage", []string{msg(`,"usage":{"input":3,"output":3}`), msg(``), end}}, |
| 223 | {"a sum that overflows", []string{msg(`,"usage":{"input":9223372036854775807,"output":1}`), msg(`,"usage":{"input":1,"output":1}`), end}}, |
| 224 | } { |
| 225 | t.Run(tc.name, func(t *testing.T) { |
| 226 | d, tally := &Decoder{}, &Tally{} |
| 227 | for _, line := range tc.lines { |
| 228 | evs, err := d.Decode([]byte(line)) |
| 229 | if err != nil { |
| 230 | t.Fatal(err) |
| 231 | } |
| 232 | for _, e := range evs { |
| 233 | tally.Add(e) |
| 234 | } |
| 235 | } |
| 236 | row := tally.Row() |
| 237 | if row.InputTokens != nil || row.OutputTokens != nil { |
| 238 | t.Fatalf("unknown usage counted: in %v out %v complete %v", row.InputTokens, row.OutputTokens, row.Complete) |
| 239 | } |
| 240 | }) |
| 241 | } |
| 242 | // Zero usage Pi reported (a refused request) is a known zero. |
| 243 | d, tally := &Decoder{}, &Tally{} |
| 244 | for _, line := range []string{msg(`,"usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}`), end} { |
| 245 | evs, _ := d.Decode([]byte(line)) |
| 246 | for _, e := range evs { |
| 247 | tally.Add(e) |
| 248 | } |
| 249 | } |
| 250 | if row := tally.Row(); row.InputTokens == nil || *row.InputTokens != 0 || !row.Complete { |
| 251 | t.Fatalf("a reported zero: %+v", row) |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // Security round #1 (§16.5): an attempt whose requests were answered by |
| 256 | // more than one model reports one row per reported model, each with its |
| 257 | // own figures and reported cost; the request count rides the first row |
| 258 | // only; a message that cannot be counted leaves every row unknown. |
| 259 | func TestTallyRowsPerModel(t *testing.T) { |
| 260 | tally := &Tally{} |
| 261 | for _, raw := range []string{ |
| 262 | `{"valid":true,"model":"z-ai/glm-5.3","input":10,"output":2,"cache_read":4}`, |
| 263 | `{"valid":true,"model":"vendor/other","input":7,"output":3,"cost":0.5,"priced":true}`, |
| 264 | `{"valid":true,"model":"z-ai/glm-5.3","input":5,"output":1}`, |
| 265 | } { |
| 266 | tally.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(raw)}) |
| 267 | } |
| 268 | tally.Add(provider.Event{Kind: KindDone, Payload: json.RawMessage(`{"status":"completed"}`)}) |
| 269 | rows := tally.Rows() |
| 270 | if len(rows) != 2 || rows[0].Model != "z-ai/glm-5.3" || rows[1].Model != "vendor/other" { |
| 271 | t.Fatalf("rows %+v", rows) |
| 272 | } |
| 273 | a, b := rows[0], rows[1] |
| 274 | if *a.InputTokens != 15 || *a.OutputTokens != 3 || *a.CachedInputTokens != 4 || a.CostReportedMicros != nil || *a.Turns != 3 || !a.Complete { |
| 275 | t.Fatalf("first model %+v", a) |
| 276 | } |
| 277 | if *b.InputTokens != 7 || *b.OutputTokens != 3 || b.CostReportedMicros == nil || *b.CostReportedMicros != 500000 || b.Turns != nil || !b.Complete { |
| 278 | t.Fatalf("second model %+v", b) |
| 279 | } |
| 280 | if tally.Model() != "z-ai/glm-5.3" { |
| 281 | t.Fatalf("the model that ran first %q", tally.Model()) |
| 282 | } |
| 283 | bad := &Tally{} |
| 284 | bad.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"a","input":1,"output":1}`)}) |
| 285 | bad.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":false,"model":"b"}`)}) |
| 286 | for _, r := range bad.Rows() { |
| 287 | if r.InputTokens != nil || r.OutputTokens != nil { |
| 288 | t.Fatalf("an uncountable message left a row counted: %+v", r) |
| 289 | } |
| 290 | } |
| 291 | } |
| 292 | |