package traefikllmgateway import ( "bytes" "testing" "time" ) func TestCappedAccountingBuffer_KeepsBoundedRollingTailAfterCap(t *testing.T) { c := &cappedAccountingBuffer{} chunk := bytes.Repeat([]byte("x"), 32<<10) total := 0 for total <= maxAccountingTeeBytes+3*sseAccountingTailBytes { if n, err := c.Write(chunk); n != len(chunk) || err != nil { t.Fatalf("Write = %d, %v", n, err) } total += len(chunk) } end := []byte("END-MARKER") _, _ = c.Write(end) if c.buf.Len() != maxAccountingTeeBytes || !c.truncated { t.Fatalf("head len = %d truncated = %v, want cap and truncated", c.buf.Len(), c.truncated) } tail := c.tailBytes() if len(tail) == 0 || len(tail) > sseAccountingTailBytes { t.Fatalf("tail len = %d, want 1..%d", len(tail), sseAccountingTailBytes) } if !bytes.HasSuffix(tail, end) { t.Errorf("tail does not end with the last bytes written") } } func TestExtractTruncatedJSONUsage_PicksLastUsageKeyOutsideStrings(t *testing.T) { head := []byte(`{"model":"gpt-5","choices":[{"message":{"content":"text \"usage\": {\"prompt_tokens\": 9}"}}],"usage" : {"prompt_tokens":5,"completion_tokens":6}`) u, model := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, nil, true) if u.prompt != 5 || u.completion != 6 || model != "gpt-5" { t.Fatalf("usage = %+v model = %q, want 5/6 gpt-5", u, model) } if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", []byte(`{"a":"b"`), nil, true); u.total() != 0 { t.Errorf("usage without a usage key = %+v, want zero", u) } } func TestPassthroughSSE_TailBufferUnchanged(t *testing.T) { b := &sseAccountingBuffer{} chunk := bytes.Repeat([]byte("y"), 10<<10) for i := 0; i < 40; i++ { _, _ = b.Write(chunk) } _, _ = b.Write([]byte("LAST")) tail := b.tailBytes() if len(tail) != sseAccountingTailBytes || !bytes.HasSuffix(tail, []byte("LAST")) { t.Fatalf("tail len = %d suffix ok = %v, want %d bytes ending LAST", len(tail), bytes.HasSuffix(tail, []byte("LAST")), sseAccountingTailBytes) } if b.head.Len() != sseAccountingHeadBytes { t.Errorf("head len = %d, want %d", b.head.Len(), sseAccountingHeadBytes) } big := &sseAccountingBuffer{} _, _ = big.Write(bytes.Repeat([]byte("z"), 3*sseAccountingTailBytes)) if len(big.tailBytes()) != sseAccountingTailBytes { t.Errorf("single oversized write tail len = %d, want %d", len(big.tailBytes()), sseAccountingTailBytes) } } func TestExtractTruncatedJSONUsage_SkipsEchoedAndEmptyUsage(t *testing.T) { tail := []byte(`x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"metadata":{"usage":"x"},"schema":{"usage":{"type":"object"}},"z":{"usage":{}}}`) u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nil, tail, true) if u.prompt != 700 || u.completion != 30000 { t.Fatalf("usage = %+v, want 700/30000", u) } } func TestExtractTruncatedJSONUsage_NestedCandidatesAreBounded(t *testing.T) { head := bytes.Repeat([]byte(`"usage":{`), maxAccountingTeeBytes/len(`"usage":{`)) start := time.Now() u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, head[:sseAccountingTailBytes], true) if u.total() != 0 { t.Errorf("usage = %+v, want zero", u) } if d := time.Since(start); d > time.Second { t.Errorf("scan took %v, want under 1s", d) } } func TestCappedAccountingBuffer_ScanTailJoinsHeadWhenContiguous(t *testing.T) { c := &cappedAccountingBuffer{} _, _ = c.Write(bytes.Repeat([]byte("h"), maxAccountingTeeBytes-3)) _, _ = c.Write([]byte("ABCDEF")) if got := c.scanTail(); !bytes.HasSuffix(got, []byte("ABCDEF")) || !bytes.Contains(got, []byte("hhhABC")) { t.Errorf("scanTail does not join head and tail") } _, _ = c.Write(bytes.Repeat([]byte("t"), 3*sseAccountingTailBytes)) if got := c.scanTail(); bytes.Contains(got, []byte("h")) { t.Errorf("scanTail joined head across a gap") } } func TestExtractTruncatedJSONUsage_NestedObjectsNeverWinTail(t *testing.T) { cases := []struct { name, typ string tail string prompt int64 out int64 }{ {"schema object after real usage", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"tool":{"usage":{"prompt_tokens":1,"completion_tokens":9000000}}}`, 700, 30000}, {"usage inside usage", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000,"usage":{"prompt_tokens":1,"completion_tokens":0}}}`, 700, 30000}, {"anthropic tool_use input", providerTypeAnthropic, `x"},"usage":{"input_tokens":700,"output_tokens":30000},"z":{"type":"tool_use","input":{"usage":{"input_tokens":1,"output_tokens":0}}}}`, 700, 30000}, {"echo as last key, real one before", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"echo":{"usage":{"prompt_tokens":1}}}`, 700, 30000}, {"cut short after echo", providerTypeOpenAI, `x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}`, 0, 0}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { u, _ := extractTruncatedJSONUsage(c.typ, "up", nil, []byte(c.tail), true) if u.prompt != c.prompt || u.completion != c.out { t.Errorf("usage = %d/%d, want %d/%d", u.prompt, u.completion, c.prompt, c.out) } }) } } func TestExtractTruncatedJSONUsage_HeadTopLevelUsageOnly(t *testing.T) { head := []byte(`{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"` + string(bytes.Repeat([]byte("a"), 1<<10)) + `","echo":{"usage":{"prompt_tokens":1}`) u, model := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, nil, true) if u.prompt != 6 || u.completion != 10000 || model != "gpt-5" { t.Fatalf("usage = %+v model = %q, want 6/10000 gpt-5", u, model) } nested := []byte(`{"model":"gpt-5","echo":{"usage":{"prompt_tokens":1,"completion_tokens":2}},"c":"x`) if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nested, nil, true); u.total() != 0 { t.Errorf("nested head usage = %+v, want zero", u) } } func TestExtractTruncatedJSONUsage_AbortedCopyIgnoresClosedLookingTail(t *testing.T) { head := []byte(`{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"x`) tail := []byte(`x"},"echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}}`) if u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", head, tail, false); u.prompt != 6 || u.completion != 10000 { t.Errorf("aborted usage = %+v, want 6/10000 from the head", u) } } func TestExtractTruncatedJSONUsage_GeminiShapes(t *testing.T) { arrayHead := []byte(`[{"candidates":[{"content":{"parts":[{"text":"x`) objectHead := []byte(`{"candidates":[{"content":{"parts":[{"text":"x`) real := `"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"` forged := `{"functionCall":{"args":{"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":0}}}}` cases := []struct { name string tail string head []byte }{ {"array", `x"}]}}],` + real + `}]`, arrayHead}, {"array, forged args after real", `x"}]}}],` + real + `},{"candidates":[{"content":{"parts":[` + forged + `]}}]}]`, arrayHead}, {"array, real in an earlier element", `x"}]}}],` + real + `},{"candidates":[]}]`, arrayHead}, {"object, forged args after real", `x"}]}}],` + real + `,"extra":` + forged + `}`, objectHead}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { u, model := extractTruncatedJSONUsage(providerTypeGemini, "up", c.head, []byte(c.tail), true) if u.prompt != 700 || u.completion != 30000 || model != "gemini-x" { t.Errorf("usage = %d/%d model = %q, want 700/30000 gemini-x", u.prompt, u.completion, model) } }) } } func TestExtractTruncatedJSONUsage_GeminiArrayUsageInHead(t *testing.T) { head := []byte(`[{"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"},{"candidates":[{"content":{"parts":[{"text":"x`) u, model := extractTruncatedJSONUsage(providerTypeGemini, "up", head, nil, false) if u.prompt != 700 || u.completion != 30000 || model != "gemini-x" { t.Errorf("usage = %d/%d model = %q, want 700/30000 gemini-x", u.prompt, u.completion, model) } } func TestExtractTruncatedJSONUsage_UnrelatedTypeMismatchKeepsFigures(t *testing.T) { tail := []byte(`x"},"usage":{"prompt_tokens":700,"completion_tokens":30000},"response":"text"}`) u, _ := extractTruncatedJSONUsage(providerTypeOpenAI, "up", nil, tail, true) if u.prompt != 700 || u.completion != 30000 { t.Errorf("usage = %d/%d, want 700/30000", u.prompt, u.completion) } } func TestExtractTruncatedJSONUsage_GeminiModelVersionOnlyFromTopLevel(t *testing.T) { head := []byte(`{"usageMetadata":{"promptTokenCount":6,"candidatesTokenCount":9},"modelVersion":"gemini-real","c":{"args":{"modelVersion":"forged"}},"d":"x`) if _, model := extractTruncatedJSONUsage(providerTypeGemini, "up", head, nil, false); model != "gemini-real" { t.Errorf("aborted model = %q, want gemini-real", model) } tail := []byte(`x"},"usageMetadata":{"promptTokenCount":6,"candidatesTokenCount":9},"modelVersion":"gemini-real","c":{"args":{"modelVersion":"forged"}}}`) if _, model := extractTruncatedJSONUsage(providerTypeGemini, "up", []byte(`{"a":"x`), tail, true); model != "gemini-real" { t.Errorf("complete model = %q, want gemini-real", model) } }