@langwatch/server 3.1.0-beta.7 → 3.1.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/package.json +1 -6
  2. package/packages/server/dist/cli.cjs +23 -17
  3. package/cmd/service/main.go +0 -68
  4. package/go.mod +0 -117
  5. package/go.sum +0 -299
  6. package/pkg/breaker/breaker.go +0 -157
  7. package/pkg/breaker/breaker_test.go +0 -131
  8. package/pkg/clog/LICENSE +0 -26
  9. package/pkg/clog/clog.go +0 -90
  10. package/pkg/clog/clog_test.go +0 -56
  11. package/pkg/clog/panic.go +0 -39
  12. package/pkg/config/LICENSE +0 -26
  13. package/pkg/config/config.go +0 -86
  14. package/pkg/config/config_test.go +0 -70
  15. package/pkg/config/otel.go +0 -50
  16. package/pkg/config/server.go +0 -61
  17. package/pkg/config/validate.go +0 -80
  18. package/pkg/config/validate_test.go +0 -74
  19. package/pkg/contexts/contexts_test.go +0 -34
  20. package/pkg/contexts/request_id.go +0 -1
  21. package/pkg/contexts/service_info.go +0 -33
  22. package/pkg/errfuncs/errfuncs.go +0 -9
  23. package/pkg/errfuncs/errfuncs_test.go +0 -28
  24. package/pkg/forkedcontext/forkedcontext.go +0 -57
  25. package/pkg/health/health.go +0 -123
  26. package/pkg/health/health_test.go +0 -84
  27. package/pkg/herr/LICENSE +0 -26
  28. package/pkg/herr/code.go +0 -14
  29. package/pkg/herr/herr.go +0 -112
  30. package/pkg/herr/herr_test.go +0 -78
  31. package/pkg/herr/http.go +0 -133
  32. package/pkg/herr/http_test.go +0 -103
  33. package/pkg/herr/validate.go +0 -72
  34. package/pkg/herr/validate_test.go +0 -75
  35. package/pkg/httpmiddleware/bearer.go +0 -47
  36. package/pkg/httpmiddleware/httputil_test.go +0 -167
  37. package/pkg/httpmiddleware/inflight.go +0 -23
  38. package/pkg/httpmiddleware/maxbody.go +0 -30
  39. package/pkg/httpmiddleware/recover.go +0 -38
  40. package/pkg/httpmiddleware/requestid.go +0 -40
  41. package/pkg/httpmiddleware/telemetry.go +0 -96
  42. package/pkg/httpmiddleware/version.go +0 -16
  43. package/pkg/jwtverify/verifier.go +0 -72
  44. package/pkg/jwtverify/verifier_test.go +0 -134
  45. package/pkg/ksuid/LICENSE +0 -26
  46. package/pkg/ksuid/ksuid.go +0 -157
  47. package/pkg/ksuid/ksuid_test.go +0 -107
  48. package/pkg/ksuid/resources.go +0 -13
  49. package/pkg/lifecycle/group.go +0 -175
  50. package/pkg/lifecycle/group_test.go +0 -236
  51. package/pkg/lifecycle/service.go +0 -112
  52. package/pkg/netprobe/netprobe.go +0 -89
  53. package/pkg/netprobe/netprobe_test.go +0 -55
  54. package/pkg/otelsetup/otelsetup.go +0 -226
  55. package/pkg/otelsetup/otelsetup_test.go +0 -130
  56. package/pkg/ptr/LICENSE +0 -26
  57. package/pkg/ptr/ptr.go +0 -34
  58. package/pkg/ptr/ptr_test.go +0 -66
  59. package/pkg/retry/bench_test.go +0 -67
  60. package/pkg/retry/retry.go +0 -188
  61. package/pkg/retry/retry_test.go +0 -222
  62. package/pkg/slicefuncs/LICENSE +0 -26
  63. package/pkg/slicefuncs/slicefuncs.go +0 -10
  64. package/pkg/slicefuncs/slicefuncs_test.go +0 -29
  65. package/pkg/stacktrace/LICENSE +0 -26
  66. package/pkg/stacktrace/frames.go +0 -77
  67. package/pkg/stacktrace/frames_test.go +0 -73
  68. package/services/aigateway/BENCHMARKS.md +0 -110
  69. package/services/aigateway/README.md +0 -156
  70. package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
  71. package/services/aigateway/adapters/authresolver/redis.go +0 -61
  72. package/services/aigateway/adapters/authresolver/service.go +0 -442
  73. package/services/aigateway/adapters/authresolver/service_test.go +0 -435
  74. package/services/aigateway/adapters/budget/bench_test.go +0 -50
  75. package/services/aigateway/adapters/budget/budget.go +0 -59
  76. package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
  77. package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
  78. package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
  79. package/services/aigateway/adapters/controlplane/client.go +0 -213
  80. package/services/aigateway/adapters/controlplane/client_test.go +0 -73
  81. package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
  82. package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
  83. package/services/aigateway/adapters/controlplane/signer.go +0 -95
  84. package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
  85. package/services/aigateway/adapters/customertracebridge/context.go +0 -48
  86. package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
  87. package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
  88. package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
  89. package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
  90. package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
  91. package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
  92. package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
  93. package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
  94. package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
  95. package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
  96. package/services/aigateway/adapters/httpapi/middleware.go +0 -123
  97. package/services/aigateway/adapters/httpapi/router.go +0 -635
  98. package/services/aigateway/adapters/httpapi/router_test.go +0 -633
  99. package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
  100. package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
  101. package/services/aigateway/adapters/policy/matcher.go +0 -250
  102. package/services/aigateway/adapters/policy/matcher_test.go +0 -124
  103. package/services/aigateway/adapters/providers/bifrost.go +0 -798
  104. package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
  105. package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
  106. package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
  107. package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
  108. package/services/aigateway/app/app.go +0 -104
  109. package/services/aigateway/app/dispatch.go +0 -89
  110. package/services/aigateway/app/dispatch_test.go +0 -475
  111. package/services/aigateway/app/handlers.go +0 -79
  112. package/services/aigateway/app/peek_bench_test.go +0 -21
  113. package/services/aigateway/app/pipeline/bench_test.go +0 -34
  114. package/services/aigateway/app/pipeline/budget.go +0 -55
  115. package/services/aigateway/app/pipeline/cache.go +0 -34
  116. package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
  117. package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
  118. package/services/aigateway/app/pipeline/guardrail.go +0 -121
  119. package/services/aigateway/app/pipeline/pipeline.go +0 -159
  120. package/services/aigateway/app/pipeline/policy.go +0 -23
  121. package/services/aigateway/app/pipeline/ratelimit.go +0 -21
  122. package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
  123. package/services/aigateway/app/pipeline/resolve.go +0 -44
  124. package/services/aigateway/app/pipeline/trace.go +0 -129
  125. package/services/aigateway/app/ports.go +0 -61
  126. package/services/aigateway/cmd/root.go +0 -42
  127. package/services/aigateway/config.go +0 -86
  128. package/services/aigateway/deps.go +0 -177
  129. package/services/aigateway/domain/bundle.go +0 -203
  130. package/services/aigateway/domain/errors.go +0 -23
  131. package/services/aigateway/domain/model.go +0 -24
  132. package/services/aigateway/domain/provider.go +0 -38
  133. package/services/aigateway/domain/request.go +0 -65
  134. package/services/aigateway/domain/response.go +0 -56
  135. package/services/aigateway/domain/verdict.go +0 -55
  136. package/services/aigateway/serve.go +0 -45
  137. package/services/aigateway/tests/matrix/README.md +0 -71
  138. package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
  139. package/services/aigateway/tests/matrix/azure_test.go +0 -52
  140. package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
  141. package/services/aigateway/tests/matrix/gemini_test.go +0 -117
  142. package/services/aigateway/tests/matrix/matrix_test.go +0 -601
  143. package/services/aigateway/tests/matrix/openai_test.go +0 -66
  144. package/services/aigateway/tests/matrix/vertex_test.go +0 -160
@@ -1,601 +0,0 @@
1
- //go:build live_openai || live_anthropic || live_gemini || live_bedrock || live_azure || live_vertex
2
-
3
- // Package matrix runs the provider × scenario coverage matrix against a live
4
- // gateway + control plane + real provider credentials. Build-tagged per
5
- // provider (live_openai, live_anthropic, …) so CI's default `go test ./...`
6
- // never triggers real provider spend.
7
- //
8
- // Pre-requisites (env vars; missing = t.Skip):
9
- //
10
- // GATEWAY_URL http://localhost:5563
11
- // LW_PROJECT_API_KEY sk-lw-... (for /api/trace/:id readback)
12
- // LW_BASE_URL http://localhost:5560 (optional, defaults to this)
13
- //
14
- // Per-provider VK env vars (a VK with the provider's credentials bound):
15
- //
16
- // TEST_VK_OPENAI lw_vk_live_...
17
- // TEST_VK_ANTHROPIC lw_vk_live_...
18
- // TEST_VK_GEMINI lw_vk_live_...
19
- // TEST_VK_BEDROCK lw_vk_live_...
20
- // TEST_VK_AZURE lw_vk_live_...
21
- // TEST_VK_VERTEX lw_vk_live_...
22
- //
23
- // Each cell asserts four invariants:
24
- // 1. Gateway returns HTTP 200.
25
- // 2. Response has a valid X-LangWatch-Trace-Id header.
26
- // 3. Response body has non-zero usage.prompt_tokens + usage.completion_tokens.
27
- // 4. Within 30s the LangWatch ingest pipeline has the trace with
28
- // metrics.total_cost > 0 (verifying the full gateway → OTLP → ingest →
29
- // cost-calc chain, not just provider passthrough).
30
- package matrix
31
-
32
- import (
33
- "bytes"
34
- "encoding/json"
35
- "io"
36
- "net/http"
37
- "os"
38
- "strings"
39
- "testing"
40
- "time"
41
- )
42
-
43
- // cell is one row of the matrix: a {provider, scenario, request body} tuple.
44
- type cell struct {
45
- provider string // "openai" | "anthropic" | "gemini" | "bedrock" | "azure" | "vertex"
46
- scenario string // "simple" | "streamed" | "tool_calling" | "structured_outputs"
47
- body func(model string) []byte
48
- }
49
-
50
- // resolvedCell pairs a cell with the VK + model resolved from env vars so each
51
- // test can run standalone without a shared fixture.
52
- type resolvedCell struct {
53
- cell
54
- vk string // "lw_vk_live_..."
55
- model string // e.g. "gpt-5-mini"
56
- streaming bool
57
- // endpoint is the gateway path to hit. Defaults to /v1/chat/completions
58
- // when empty. Anthropic/Bedrock cache cells use /v1/messages so
59
- // cache_control markers + cache_*_input_tokens round-trip intact via
60
- // raw-forward (chat-completions translates the response shape and
61
- // drops Anthropic's cache usage fields).
62
- endpoint string
63
- }
64
-
65
- // gatewayURL resolves the gateway base URL from env, defaulting to localhost.
66
- func gatewayURL() string {
67
- if v := os.Getenv("GATEWAY_URL"); v != "" {
68
- return strings.TrimRight(v, "/")
69
- }
70
- return "http://localhost:5563"
71
- }
72
-
73
- // lwBaseURL resolves the control-plane base URL for trace readback.
74
- func lwBaseURL() string {
75
- if v := os.Getenv("LW_BASE_URL"); v != "" {
76
- return strings.TrimRight(v, "/")
77
- }
78
- return "http://localhost:5560"
79
- }
80
-
81
- // requireEnv returns the env var value or calls t.Skip if unset.
82
- // Reserves t.Fatal for bugs, never for missing config — a missing key is
83
- // "this cell can't run here", not a failure.
84
- func requireEnv(t *testing.T, key string) string {
85
- t.Helper()
86
- v := os.Getenv(key)
87
- if v == "" {
88
- t.Skipf("%s not set — skipping live provider test", key)
89
- }
90
- return v
91
- }
92
-
93
- // maxTokensKey returns the right response-length parameter name for a model:
94
- // OpenAI's gpt-5* + o* series reject `max_tokens` and require
95
- // `max_completion_tokens`; everyone else accepts `max_tokens`. Bifrost does
96
- // NOT currently translate this — the gateway forwards whatever the client
97
- // sends, so the matrix tests have to pick correctly per model family.
98
- func maxTokensKey(model string) string {
99
- if strings.HasPrefix(model, "gpt-5") ||
100
- strings.HasPrefix(model, "o1") || strings.HasPrefix(model, "o3") ||
101
- strings.HasPrefix(model, "o4") {
102
- return "max_completion_tokens"
103
- }
104
- return "max_tokens"
105
- }
106
-
107
- // chatBody_Simple builds a minimal /v1/chat/completions request.
108
- func chatBody_Simple(model string) []byte {
109
- body := map[string]any{
110
- "model": model,
111
- "messages": []map[string]any{
112
- {"role": "user", "content": "Respond with exactly one word: ok"},
113
- },
114
- maxTokensKey(model): 16,
115
- }
116
- return mustJSON(body)
117
- }
118
-
119
- // chatBody_Streamed is identical but with stream=true + usage opt-in.
120
- func chatBody_Streamed(model string) []byte {
121
- return mustJSON(map[string]any{
122
- "model": model,
123
- "messages": []map[string]any{
124
- {"role": "user", "content": "Count from 1 to 5, one number per line."},
125
- },
126
- maxTokensKey(model): 48,
127
- "stream": true,
128
- "stream_options": map[string]any{"include_usage": true},
129
- })
130
- }
131
-
132
- // chatBody_StreamedNoUsageOption exercises the stream_options.include_usage
133
- // auto-injection path (specs/ai-gateway/streaming.feature → "Streaming
134
- // usage capture"). OpenAI only emits the final usage SSE chunk when that
135
- // flag is set on the request body. Most real callers (vanilla OpenAI SDK
136
- // without opt-in, coding CLIs, LangChain default) DON'T set it — which
137
- // leaves the gateway trace with tokens=0 + a success_no_usage warning and
138
- // starves cost-enrichment. The gateway injects the flag for OpenAI-shape
139
- // providers on the DispatchStream path so cost + budget accounting keep
140
- // working regardless of caller hygiene. This body intentionally omits
141
- // stream_options to prove the injection.
142
- func chatBody_StreamedNoUsageOption(model string) []byte {
143
- return mustJSON(map[string]any{
144
- "model": model,
145
- "messages": []map[string]any{
146
- {"role": "user", "content": "Count from 1 to 5, one number per line."},
147
- },
148
- maxTokensKey(model): 48,
149
- "stream": true,
150
- })
151
- }
152
-
153
- // chatBody_ToolCalling exercises OpenAI-compatible function/tool calling.
154
- func chatBody_ToolCalling(model string) []byte {
155
- return mustJSON(map[string]any{
156
- "model": model,
157
- "messages": []map[string]any{
158
- {"role": "user", "content": "What's the weather in Berlin? Use the tool."},
159
- },
160
- "tools": []map[string]any{
161
- {
162
- "type": "function",
163
- "function": map[string]any{
164
- "name": "get_weather",
165
- "description": "Get the current weather for a city.",
166
- "parameters": map[string]any{
167
- "type": "object",
168
- "properties": map[string]any{
169
- "city": map[string]any{"type": "string"},
170
- },
171
- "required": []string{"city"},
172
- },
173
- },
174
- },
175
- },
176
- maxTokensKey(model): 64,
177
- })
178
- }
179
-
180
- // chatBody_StructuredOutputs asks for a JSON-shaped response.
181
- func chatBody_StructuredOutputs(model string) []byte {
182
- return mustJSON(map[string]any{
183
- "model": model,
184
- "messages": []map[string]any{
185
- {"role": "system", "content": "Reply ONLY with a compact JSON object {\"city\": string, \"country\": string}."},
186
- {"role": "user", "content": "Paris"},
187
- },
188
- "response_format": map[string]any{"type": "json_object"},
189
- maxTokensKey(model): 64,
190
- })
191
- }
192
-
193
- // cacheablePrefix is long enough to trigger every provider's prompt cache.
194
- // Thresholds per provider:
195
- // - OpenAI: ≥1024 tokens of shared prefix
196
- // - Anthropic Sonnet/Opus: ≥1024 tokens in the cached block
197
- // - Anthropic Haiku: **≥2048 tokens** (higher bar than Sonnet/Opus —
198
- // surprise from docs; a 1700-token prefix returns cache_*_tokens=0
199
- // on claude-haiku-4-5)
200
- // - Gemini / Vertex: automatic caching on shared context, comparable
201
- // thresholds
202
- //
203
- // 48× the paragraph lands us well above 2048 tokens — safe for all
204
- // providers. Trade-off: ~$0.002 extra per cache cell run (one prime +
205
- // one read).
206
- var cacheablePrefix = strings.Repeat(
207
- "You are a senior SRE specialising in Kubernetes, observability, and cost "+
208
- "optimisation for large-scale LLM gateway deployments. You answer in "+
209
- "crisp, technically precise paragraphs, citing specific CPU, memory, "+
210
- "and network characteristics where relevant. Your audience is other "+
211
- "engineers, not executives. Avoid marketing language entirely. ",
212
- 48,
213
- )
214
-
215
- // anthropicNativeCache_Prime + _Read produce /v1/messages wire-shape bodies
216
- // (top-level `system` array + `max_tokens`) for the anthropic/bedrock cache
217
- // cells. Going through /v1/chat/completions toward an Anthropic-family
218
- // provider strips the cache_*_input_tokens fields from the response when
219
- // the gateway translates to OpenAI-shape; the native endpoint raw-forwards
220
- // the cache_control marker AND returns the provider's native usage intact.
221
- func anthropicNativeCache_Prime(model string) []byte {
222
- return anthropicNativeCacheBody(model, "What's the first thing you check when a gateway pod's /readyz starts flapping?")
223
- }
224
-
225
- func anthropicNativeCache_Read(model string) []byte {
226
- return anthropicNativeCacheBody(model, "Follow-up: same situation but the gateway is at 90% memory. What changes?")
227
- }
228
-
229
- func anthropicNativeCacheBody(model, userTurn string) []byte {
230
- return mustJSON(map[string]any{
231
- "model": model,
232
- "max_tokens": 16,
233
- "system": []map[string]any{{
234
- "type": "text",
235
- "text": cacheablePrefix,
236
- "cache_control": map[string]any{"type": "ephemeral"},
237
- }},
238
- "messages": []map[string]any{
239
- {"role": "user", "content": userTurn + " Reply with exactly one word: ok."},
240
- },
241
- })
242
- }
243
-
244
- // chatBody_Cache_Prime builds a request designed to create a cache entry.
245
- // For Anthropic-family providers (anthropic / bedrock), the system block
246
- // carries `cache_control: {type: "ephemeral"}` to explicitly request caching.
247
- // For auto-cache providers (openai / gemini / azure / vertex), the prefix is
248
- // simply long + stable — the second identical call triggers cache_read on
249
- // the provider side. Both paths surface as gen_ai.usage.cache_read.input_tokens
250
- // in the span.
251
- func chatBody_Cache_Prime(model string) []byte {
252
- return cacheBodyFor(model, "What's the first thing you check when a gateway pod's /readyz starts flapping?")
253
- }
254
-
255
- // chatBody_Cache_Read is the second call — identical prefix, different user
256
- // turn — so the provider's cache can hit on the shared prefix while the
257
- // cache-key (or cache_read attribute) surfaces on the response.
258
- func chatBody_Cache_Read(model string) []byte {
259
- return cacheBodyFor(model, "Follow-up: same situation but the gateway is at 90% memory. What changes?")
260
- }
261
-
262
- func cacheBodyFor(model, userTurn string) []byte {
263
- // Heuristic: anthropic-family models carry cache_control on the system
264
- // block; others rely on provider-side automatic caching of the shared
265
- // prefix. The gateway transparently forwards cache_control bytes to
266
- // Anthropic (and Anthropic-on-Bedrock); for other providers, the flag
267
- // is a harmless no-op at the cost of ~20 bytes extra payload.
268
- anthropicFamily := strings.HasPrefix(model, "claude-") ||
269
- strings.Contains(model, "anthropic.claude-")
270
-
271
- var systemBlock any
272
- if anthropicFamily {
273
- systemBlock = []map[string]any{
274
- {
275
- "type": "text",
276
- "text": cacheablePrefix,
277
- "cache_control": map[string]any{"type": "ephemeral"},
278
- },
279
- }
280
- } else {
281
- systemBlock = cacheablePrefix
282
- }
283
- return mustJSON(map[string]any{
284
- "model": model,
285
- "messages": []map[string]any{
286
- {"role": "system", "content": systemBlock},
287
- {"role": "user", "content": userTurn},
288
- },
289
- maxTokensKey(model): 64,
290
- })
291
- }
292
-
293
- func mustJSON(v any) []byte {
294
- b, err := json.Marshal(v)
295
- if err != nil {
296
- panic(err) // test-time panic is acceptable — input is constant
297
- }
298
- return b
299
- }
300
-
301
- // fireAndAssert runs one resolved cell against the live gateway and asserts
302
- // the four invariants. Returns the trace id for downstream cost verification.
303
- func fireAndAssert(t *testing.T, rc resolvedCell) string {
304
- t.Helper()
305
-
306
- body := rc.body(rc.model)
307
- req, err := http.NewRequest(http.MethodPost, gatewayURL()+"/v1/chat/completions", bytes.NewReader(body))
308
- if err != nil {
309
- t.Fatalf("build request: %v", err)
310
- }
311
- req.Header.Set("Authorization", "Bearer "+rc.vk)
312
- req.Header.Set("Content-Type", "application/json")
313
- if rc.streaming {
314
- req.Header.Set("Accept", "text/event-stream")
315
- }
316
-
317
- client := &http.Client{Timeout: 90 * time.Second}
318
- resp, err := client.Do(req)
319
- if err != nil {
320
- t.Fatalf("gateway POST: %v", err)
321
- }
322
- defer resp.Body.Close()
323
-
324
- raw, _ := io.ReadAll(resp.Body)
325
- if resp.StatusCode != http.StatusOK {
326
- t.Fatalf("want 200, got %d\nbody: %s", resp.StatusCode, raw)
327
- }
328
-
329
- traceID := extractTraceID(resp.Header)
330
- if traceID == "" {
331
- t.Fatalf("no trace id on response: traceparent=%q", resp.Header.Get("Traceparent"))
332
- }
333
-
334
- // For non-streaming, the body is a single JSON envelope with `usage`.
335
- // For streaming, the final SSE chunk carries usage when `include_usage`
336
- // was requested — for this smoke we accept either and let the
337
- // platform-side trace readback verify token counts.
338
- if !rc.streaming {
339
- var parsed struct {
340
- Usage struct {
341
- PromptTokens int `json:"prompt_tokens"`
342
- CompletionTokens int `json:"completion_tokens"`
343
- } `json:"usage"`
344
- }
345
- if err := json.Unmarshal(raw, &parsed); err != nil {
346
- t.Fatalf("decode completion body: %v\nbody: %s", err, raw)
347
- }
348
- if parsed.Usage.PromptTokens == 0 {
349
- t.Errorf("usage.prompt_tokens == 0 (expected >0); body: %s", raw)
350
- }
351
- if parsed.Usage.CompletionTokens == 0 {
352
- t.Errorf("usage.completion_tokens == 0 (expected >0); body: %s", raw)
353
- }
354
- }
355
-
356
- return traceID
357
- }
358
-
359
- // assertTraceCaptured polls the LangWatch trace endpoint until the trace lands
360
- // with metrics.total_cost > 0 or the budget expires. Uses the project API
361
- // key so this hits the same ingest path a customer would read.
362
- func assertTraceCaptured(t *testing.T, traceID string) float64 {
363
- t.Helper()
364
- apiKey := requireEnv(t, "LW_PROJECT_API_KEY")
365
-
366
- deadline := time.Now().Add(30 * time.Second)
367
- backoff := 500 * time.Millisecond
368
- url := lwBaseURL() + "/api/trace/" + traceID
369
-
370
- for {
371
- req, _ := http.NewRequest(http.MethodGet, url, nil)
372
- req.Header.Set("X-Auth-Token", apiKey)
373
- client := &http.Client{Timeout: 10 * time.Second}
374
- resp, err := client.Do(req)
375
- if err == nil && resp.StatusCode == http.StatusOK {
376
- body, _ := io.ReadAll(resp.Body)
377
- resp.Body.Close()
378
- // /api/trace/:id returns a flat trace envelope; metrics sits at
379
- // the top level (trace.metrics.{total_cost, prompt_tokens,
380
- // completion_tokens, ...}). `total_tokens` isn't a field name —
381
- // sum of prompt+completion is how the UI derives it.
382
- var parsed struct {
383
- Metrics struct {
384
- TotalCost float64 `json:"total_cost"`
385
- PromptTokens int `json:"prompt_tokens"`
386
- CompletionTokens int `json:"completion_tokens"`
387
- } `json:"metrics"`
388
- }
389
- if err := json.Unmarshal(body, &parsed); err == nil {
390
- totalTokens := parsed.Metrics.PromptTokens + parsed.Metrics.CompletionTokens
391
- if totalTokens > 0 && parsed.Metrics.TotalCost > 0 {
392
- return parsed.Metrics.TotalCost
393
- }
394
- }
395
- }
396
- if resp != nil {
397
- resp.Body.Close()
398
- }
399
- if time.Now().After(deadline) {
400
- t.Fatalf("trace %s did not land with total_cost > 0 within 30s", traceID)
401
- }
402
- time.Sleep(backoff)
403
- if backoff < 4*time.Second {
404
- backoff *= 2
405
- }
406
- }
407
- }
408
-
409
- // runCell is the common end-to-end runner: fire → assert HTTP → wait for trace
410
- // with cost. Each provider's test file composes a resolvedCell + calls this.
411
- func runCell(t *testing.T, rc resolvedCell) float64 {
412
- t.Helper()
413
- start := time.Now()
414
- traceID := fireAndAssert(t, rc)
415
- cost := assertTraceCaptured(t, traceID)
416
- t.Logf("cell %s/%s: trace=%s duration=%s captured_cost=$%.6f",
417
- rc.provider, rc.scenario, traceID, time.Since(start), cost)
418
- return cost
419
- }
420
-
421
- // cacheReadFromResponse extracts the provider-reported cache-read tokens
422
- // from a non-streaming /v1/chat/completions body. Handles both shapes:
423
- //
424
- // - OpenAI family: usage.prompt_tokens_details.cached_tokens
425
- // - Anthropic family: usage.cache_read_input_tokens (also in the
426
- // Anthropic-via-Bedrock normalised shape)
427
- //
428
- // Returns 0 if the field is missing, which is valid for the prime call.
429
- func cacheReadFromResponse(body []byte) int {
430
- var parsed struct {
431
- Usage struct {
432
- CacheReadInputTokens int `json:"cache_read_input_tokens"`
433
- PromptTokensDetails struct {
434
- CachedTokens int `json:"cached_tokens"`
435
- } `json:"prompt_tokens_details"`
436
- } `json:"usage"`
437
- }
438
- _ = json.Unmarshal(body, &parsed)
439
- if parsed.Usage.CacheReadInputTokens > 0 {
440
- return parsed.Usage.CacheReadInputTokens
441
- }
442
- return parsed.Usage.PromptTokensDetails.CachedTokens
443
- }
444
-
445
- // extractTraceID pulls the 32-hex trace_id out of the standard W3C
446
- // `traceparent` header (format: `00-{trace-id}-{span-id}-{flags}`). The
447
- // aigateway restructure dropped the legacy `X-LangWatch-Trace-Id` header
448
- // in favor of W3C-only propagation, so tests read from traceparent.
449
- // Returns "" when the header is absent or malformed.
450
- func extractTraceID(h http.Header) string {
451
- tp := h.Get("Traceparent")
452
- if tp == "" {
453
- return ""
454
- }
455
- parts := strings.Split(tp, "-")
456
- if len(parts) < 3 || len(parts[1]) != 32 {
457
- return ""
458
- }
459
- return parts[1]
460
- }
461
-
462
- // fireForBody posts a request to the gateway and returns the response body +
463
- // trace id + status. Unlike fireAndAssert this does NOT fatal on 4xx, so the
464
- // caller can handle prime/read retry logic (e.g. cache propagation delay).
465
- func fireForBody(t *testing.T, rc resolvedCell, body []byte) (int, []byte, string) {
466
- t.Helper()
467
- endpoint := rc.endpoint
468
- if endpoint == "" {
469
- endpoint = "/v1/chat/completions"
470
- }
471
- req, err := http.NewRequest(http.MethodPost, gatewayURL()+endpoint, bytes.NewReader(body))
472
- if err != nil {
473
- t.Fatalf("build request: %v", err)
474
- }
475
- req.Header.Set("Authorization", "Bearer "+rc.vk)
476
- req.Header.Set("Content-Type", "application/json")
477
- if endpoint == "/v1/messages" {
478
- req.Header.Set("anthropic-version", "2023-06-01")
479
- }
480
- client := &http.Client{Timeout: 120 * time.Second}
481
- resp, err := client.Do(req)
482
- if err != nil {
483
- t.Fatalf("gateway POST: %v", err)
484
- }
485
- defer resp.Body.Close()
486
- raw, _ := io.ReadAll(resp.Body)
487
- return resp.StatusCode, raw, extractTraceID(resp.Header)
488
- }
489
-
490
- // runCacheCell fires a prime call, waits 2s for the provider to register the
491
- // cache entry, then fires the read call. Asserts the read response carries
492
- // cache_read_input_tokens > 0 AND that both traces land with cost > 0.
493
- // Returns the captured cost on the read trace.
494
- func runCacheCell(t *testing.T, rc resolvedCell) float64 {
495
- return runCacheCellWith(t, rc, chatBody_Cache_Prime, chatBody_Cache_Read)
496
- }
497
-
498
- // runCachedContentCacheCell is the gemini/vertex variant: the provider's
499
- // implicit prompt cache isn't available on every account tier, but the
500
- // explicit `cachedContents` REST API does work end-to-end. The cell:
501
- //
502
- // 1. Calls `setupCachedContent` (direct API, bypasses gateway) to create a
503
- // cached content resource holding the long prefix. Returns the resource
504
- // name, e.g. "cachedContents/abc123" (Gemini-API) or
505
- // "projects/N/locations/R/cachedContents/123" (Vertex).
506
- // 2. Fires ONE chat-completions call through the gateway with
507
- // `cached_content: <name>` in the body. The gateway parser lifts the
508
- // extension key onto Bifrost's ChatParameters.ExtraParams; Bifrost's
509
- // gemini chat translator (shared with vertex) reads it off ExtraParams
510
- // and sets the geminiReq.CachedContent field on the outbound request.
511
- // 3. Asserts the response carries cached_read_tokens > 0 + the trace lands
512
- // on the platform with cost > 0.
513
- //
514
- // Returns the captured cost on the read trace.
515
- func runCachedContentCacheCell(
516
- t *testing.T,
517
- rc resolvedCell,
518
- setupCachedContent func(t *testing.T) string,
519
- ) float64 {
520
- t.Helper()
521
- start := time.Now()
522
-
523
- cachedName := setupCachedContent(t)
524
- if cachedName == "" {
525
- t.Fatal("setupCachedContent returned empty name — verify TTL / quota")
526
- }
527
-
528
- body, err := json.Marshal(map[string]any{
529
- "model": rc.model,
530
- "max_tokens": 16,
531
- "messages": []map[string]any{
532
- {"role": "user", "content": "Reply with exactly one word: ok."},
533
- },
534
- "cached_content": cachedName,
535
- })
536
- if err != nil {
537
- t.Fatalf("marshal cached read body: %v", err)
538
- }
539
-
540
- status, readBody, readTraceID := fireForBody(t, rc, body)
541
- if status != 200 {
542
- t.Fatalf("read: want 200, got %d\nbody: %s", status, readBody)
543
- }
544
- if readTraceID == "" {
545
- t.Fatal("read: missing X-LangWatch-Trace-Id")
546
- }
547
-
548
- cacheRead := cacheReadFromResponse(readBody)
549
- if cacheRead == 0 {
550
- t.Errorf("%s/cache: want cache_read > 0 on cachedContent reference; got 0\nread body: %s", rc.provider, readBody)
551
- }
552
-
553
- cost := assertTraceCaptured(t, readTraceID)
554
- t.Logf("cell %s/cache: cached=%s read_trace=%s cache_read_tokens=%d duration=%s captured_cost=$%.6f",
555
- rc.provider, cachedName, readTraceID, cacheRead, time.Since(start), cost)
556
- return cost
557
- }
558
-
559
- // runCacheCellWith is the prime+read driver parameterised on body-builders so
560
- // callers can use provider-native bodies (e.g. Anthropic /v1/messages shape)
561
- // instead of the OpenAI-compat chat-completions default.
562
- func runCacheCellWith(t *testing.T, rc resolvedCell, primeFn, readFn func(string) []byte) float64 {
563
- t.Helper()
564
- start := time.Now()
565
-
566
- status, primeBody, primeTraceID := fireForBody(t, rc, primeFn(rc.model))
567
- if status != 200 {
568
- t.Fatalf("prime: want 200, got %d\nbody: %s", status, primeBody)
569
- }
570
- if primeTraceID == "" {
571
- t.Fatal("prime: missing X-LangWatch-Trace-Id")
572
- }
573
-
574
- // Wait for the provider's cache to register. Empirically: Anthropic's
575
- // ephemeral cache needs ~5-10s to be readable in test environments,
576
- // OpenAI's automatic cache similarly takes a few seconds. Gemini / Vertex
577
- // automatic context caching can be slower still. 8s gives all four a
578
- // comfortable margin without making the test suite too slow.
579
- time.Sleep(8 * time.Second)
580
-
581
- // 2. Read — identical prefix should trip the cache-hit path.
582
- status, readBody, readTraceID := fireForBody(t, rc, readFn(rc.model))
583
- if status != 200 {
584
- t.Fatalf("read: want 200, got %d\nbody: %s", status, readBody)
585
- }
586
- if readTraceID == "" {
587
- t.Fatal("read: missing X-LangWatch-Trace-Id")
588
- }
589
-
590
- cacheRead := cacheReadFromResponse(readBody)
591
- if cacheRead == 0 {
592
- t.Errorf("%s/cache: want cache_read > 0 on 2nd call; got 0\nread body: %s", rc.provider, readBody)
593
- }
594
-
595
- // Verify the read trace lands on the platform with cost > 0 — the cache
596
- // hit still costs a small amount even though it's discounted.
597
- cost := assertTraceCaptured(t, readTraceID)
598
- t.Logf("cell %s/cache: prime_trace=%s read_trace=%s cache_read_tokens=%d duration=%s captured_cost=$%.6f",
599
- rc.provider, primeTraceID, readTraceID, cacheRead, time.Since(start), cost)
600
- return cost
601
- }
@@ -1,66 +0,0 @@
1
- //go:build live_openai
2
-
3
- package matrix
4
-
5
- import (
6
- "os"
7
- "testing"
8
- )
9
-
10
- // openaiCell builds a resolved cell for the openai provider using TEST_VK_OPENAI
11
- // + OPENAI_MODEL (defaults to gpt-5-mini).
12
- func openaiCell(t *testing.T, scenario string, body func(string) []byte, streaming bool) resolvedCell {
13
- t.Helper()
14
- vk := requireEnv(t, "TEST_VK_OPENAI")
15
- model := os.Getenv("OPENAI_MODEL")
16
- if model == "" {
17
- model = "gpt-5-mini"
18
- }
19
- return resolvedCell{
20
- cell: cell{provider: "openai", scenario: scenario, body: body},
21
- vk: vk,
22
- model: model,
23
- streaming: streaming,
24
- }
25
- }
26
-
27
- func TestOpenAI_SimpleCompletion(t *testing.T) {
28
- runCell(t, openaiCell(t, "simple", chatBody_Simple, false))
29
- }
30
-
31
- func TestOpenAI_StreamedCompletion(t *testing.T) {
32
- runCell(t, openaiCell(t, "streamed", chatBody_Streamed, true))
33
- }
34
-
35
- // TestOpenAI_StreamedAutoIncludeUsage exercises the auto-injection path:
36
- // the request body carries stream=true WITHOUT stream_options, the gateway
37
- // must inject stream_options.include_usage=true before forwarding so the
38
- // upstream's final SSE chunk carries real token counts. The runCell
39
- // assertion fails unless the trace lands with total_cost > 0 AND
40
- // prompt+completion tokens > 0 — which requires the injection to work.
41
- func TestOpenAI_StreamedAutoIncludeUsage(t *testing.T) {
42
- runCell(t, openaiCell(t, "streamed_auto_include_usage", chatBody_StreamedNoUsageOption, true))
43
- }
44
-
45
- func TestOpenAI_ToolCalling(t *testing.T) {
46
- runCell(t, openaiCell(t, "tool_calling", chatBody_ToolCalling, false))
47
- }
48
-
49
- func TestOpenAI_StructuredOutputs(t *testing.T) {
50
- runCell(t, openaiCell(t, "structured_outputs", chatBody_StructuredOutputs, false))
51
- }
52
-
53
- func TestOpenAI_Cache(t *testing.T) {
54
- // gpt-5-mini (and other reasoning models) don't return
55
- // `prompt_tokens_details.cached_tokens` > 0 on this account — verified
56
- // with direct-to-api.openai.com calls. gpt-4o-mini caches reliably with
57
- // the same prefix. Override via OPENAI_CACHE_MODEL when testing a
58
- // different OpenAI model family's cache behaviour.
59
- cell := openaiCell(t, "cache", chatBody_Cache_Prime, false)
60
- if override := os.Getenv("OPENAI_CACHE_MODEL"); override != "" {
61
- cell.model = override
62
- } else {
63
- cell.model = "gpt-4o-mini"
64
- }
65
- runCacheCell(t, cell)
66
- }