@langwatch/server 3.1.0-beta.8 → 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 +19 -16
  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,435 +0,0 @@
1
- // Tests for stale-while-error auth cache resilience.
2
- // Spec: specs/ai-gateway/auth-cache.feature, Rule "Cached JWT serves
3
- // stale-while-error past natural expiry on transport failure".
4
- //
5
- // Each scenario in the failure taxonomy maps to a test case here:
6
- // - AuthRejection (ErrInvalidAPIKey, ErrKeyRevoked) -> evict + reject
7
- // - TransportFailure (everything else, incl. ErrAuthUpstream, raw
8
- // network errors, JWT verify failures) -> serve stale + bump soft
9
- // - HardCapExceeded -> evict + reject
10
- package authresolver
11
-
12
- import (
13
- "context"
14
- "errors"
15
- "fmt"
16
- "net"
17
- "sync"
18
- "sync/atomic"
19
- "testing"
20
- "time"
21
-
22
- "go.uber.org/zap"
23
- "go.uber.org/zap/zaptest/observer"
24
-
25
- "github.com/langwatch/langwatch/pkg/herr"
26
- "github.com/langwatch/langwatch/services/aigateway/domain"
27
- )
28
-
29
- // fakeResolver is a programmable upstream resolver/configfetcher pair.
30
- // Each Resolve call returns the next item from the returns slice; if
31
- // the slice is exhausted it returns the last item indefinitely.
32
- type fakeResolver struct {
33
- mu sync.Mutex
34
- calls atomic.Int64
35
- returns []resolverReturn
36
- }
37
-
38
- type resolverReturn struct {
39
- bundle *domain.Bundle
40
- err error
41
- }
42
-
43
- func (f *fakeResolver) ResolveKey(_ context.Context, _ string) (*domain.Bundle, error) {
44
- f.calls.Add(1)
45
- f.mu.Lock()
46
- defer f.mu.Unlock()
47
- if len(f.returns) == 0 {
48
- return nil, errors.New("fakeResolver: no returns programmed")
49
- }
50
- r := f.returns[0]
51
- if len(f.returns) > 1 {
52
- f.returns = f.returns[1:]
53
- }
54
- return r.bundle, r.err
55
- }
56
-
57
- func (f *fakeResolver) FetchConfig(_ context.Context, _ string) (domain.BundleConfig, error) {
58
- return domain.BundleConfig{}, nil
59
- }
60
-
61
- func newService(t *testing.T, opts Options) (*Service, *observer.ObservedLogs) {
62
- t.Helper()
63
- core, logs := observer.New(zap.WarnLevel)
64
- if opts.Logger == nil {
65
- opts.Logger = zap.New(core)
66
- }
67
- if opts.SoftBump == 0 {
68
- opts.SoftBump = 5 * time.Minute
69
- }
70
- // Don't default HardGrace here — let New() apply its 30m default.
71
- svc, err := New(opts)
72
- if err != nil {
73
- t.Fatalf("New: %v", err)
74
- }
75
- return svc, logs
76
- }
77
-
78
- func freshBundle(vkID string, exp time.Time) *domain.Bundle {
79
- return &domain.Bundle{VirtualKeyID: vkID, ExpiresAt: exp}
80
- }
81
-
82
- // seedExpiredEntry primes L1 with a vk whose JWT exp is `staleness` in the
83
- // past (i.e. soft-expired). HardExpiresAt is set per the service's config.
84
- func seedExpiredEntry(t *testing.T, svc *Service, rawKey, vkID string, staleness time.Duration) {
85
- t.Helper()
86
- originalExp := time.Now().Add(-staleness)
87
- svc.storeL1(hashKey(rawKey), freshBundle(vkID, originalExp))
88
- }
89
-
90
- // --- AuthRejection class -----------------------------------------------------
91
-
92
- func TestResolve_StaleEntry_AuthRejection_401_EvictsAndRejects(t *testing.T) {
93
- resolver := &fakeResolver{returns: []resolverReturn{
94
- {err: herr.New(context.Background(), domain.ErrInvalidAPIKey, nil)},
95
- }}
96
- svc, _ := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver})
97
- rawKey := "lw_vk_live_test_001"
98
- seedExpiredEntry(t, svc, rawKey, "vk_001", 30*time.Second)
99
-
100
- _, err := svc.Resolve(context.Background(), rawKey)
101
- if err == nil {
102
- t.Fatal("expected error from auth-rejection path")
103
- }
104
- if !errors.Is(err, domain.ErrInvalidAPIKey) {
105
- t.Fatalf("expected ErrInvalidAPIKey, got %v", err)
106
- }
107
- if _, ok := svc.l1.Get(hashKey(rawKey)); ok {
108
- t.Fatal("entry should have been evicted")
109
- }
110
- }
111
-
112
- func TestResolve_StaleEntry_AuthRejection_403Revoked_EvictsAndRejects(t *testing.T) {
113
- resolver := &fakeResolver{returns: []resolverReturn{
114
- {err: herr.New(context.Background(), domain.ErrKeyRevoked, nil)},
115
- }}
116
- svc, _ := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver})
117
- rawKey := "lw_vk_live_test_002"
118
- seedExpiredEntry(t, svc, rawKey, "vk_002", 30*time.Second)
119
-
120
- _, err := svc.Resolve(context.Background(), rawKey)
121
- if !errors.Is(err, domain.ErrKeyRevoked) {
122
- t.Fatalf("expected ErrKeyRevoked, got %v", err)
123
- }
124
- if _, ok := svc.l1.Get(hashKey(rawKey)); ok {
125
- t.Fatal("entry should have been evicted on revoked")
126
- }
127
- }
128
-
129
- // --- TransportFailure class --------------------------------------------------
130
-
131
- func TestResolve_StaleEntry_TransportFailure_ServesStaleAndBumpsSoft(t *testing.T) {
132
- cases := []struct {
133
- name string
134
- err error
135
- }{
136
- {"ErrAuthUpstream", herr.New(context.Background(), domain.ErrAuthUpstream, nil)},
137
- {"raw net.OpError (connection refused)", &net.OpError{Op: "dial", Err: errors.New("connection refused")}},
138
- {"context.DeadlineExceeded", context.DeadlineExceeded},
139
- {"unknown error type", errors.New("unparseable JWT response body")},
140
- {"wrapped 5xx via herr ErrAuthUpstream", herr.New(context.Background(), domain.ErrAuthUpstream, nil, errors.New("control plane returned 503"))},
141
- }
142
- for _, tc := range cases {
143
- t.Run(tc.name, func(t *testing.T) {
144
- resolver := &fakeResolver{returns: []resolverReturn{{err: tc.err}}}
145
- svc, logs := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver})
146
- rawKey := "lw_vk_live_" + tc.name
147
- vkID := "vk_" + tc.name
148
- seedExpiredEntry(t, svc, rawKey, vkID, 30*time.Second)
149
-
150
- beforeSoft := func() time.Time {
151
- e, _ := svc.l1.Get(hashKey(rawKey))
152
- _, soft, _ := e.snapshot()
153
- return soft
154
- }()
155
-
156
- bundle, err := svc.Resolve(context.Background(), rawKey)
157
- if err != nil {
158
- t.Fatalf("expected stale-serve, got error: %v", err)
159
- }
160
- if bundle == nil || bundle.VirtualKeyID != vkID {
161
- t.Fatalf("expected stale bundle for %s, got %+v", vkID, bundle)
162
- }
163
-
164
- e, ok := svc.l1.Get(hashKey(rawKey))
165
- if !ok {
166
- t.Fatal("entry should still be present after transport-class failure")
167
- }
168
- _, newSoft, _ := e.snapshot()
169
- if !newSoft.After(beforeSoft) {
170
- t.Fatalf("expected soft expiry to advance, was %v -> %v", beforeSoft, newSoft)
171
- }
172
- if d := time.Until(newSoft); d < 4*time.Minute || d > 6*time.Minute {
173
- t.Fatalf("expected new soft expiry ~5m from now, got %v", d)
174
- }
175
-
176
- // Verify the warn log line fired with the right name.
177
- found := false
178
- for _, entry := range logs.All() {
179
- if entry.Message == "auth_cache_refresh_transport_failure" {
180
- found = true
181
- break
182
- }
183
- }
184
- if !found {
185
- t.Fatalf("expected auth_cache_refresh_transport_failure log, got %d entries", logs.Len())
186
- }
187
- })
188
- }
189
- }
190
-
191
- // --- Hard cap stops the chain ------------------------------------------------
192
-
193
- func TestResolve_StaleEntry_HardCapExceeded_EvictsAndRejects(t *testing.T) {
194
- transportErr := herr.New(context.Background(), domain.ErrAuthUpstream, nil)
195
- resolver := &fakeResolver{returns: []resolverReturn{{err: transportErr}}}
196
- // Use a small HardGrace so we can drive the entry past the cap quickly.
197
- svc, logs := newService(t, Options{
198
- Resolver: resolver,
199
- ConfigFetcher: resolver,
200
- SoftBump: 1 * time.Second,
201
- HardGrace: 2 * time.Second,
202
- })
203
- rawKey := "lw_vk_live_hardcap"
204
- // Seed an entry whose original JWT exp is already past the hard cap
205
- // (staleness > HardGrace).
206
- seedExpiredEntry(t, svc, rawKey, "vk_hardcap", 10*time.Second)
207
-
208
- _, err := svc.Resolve(context.Background(), rawKey)
209
- if err == nil {
210
- t.Fatal("expected hard-cap eviction to reject the request")
211
- }
212
- if !errors.Is(err, domain.ErrAuthUpstream) {
213
- t.Fatalf("expected the upstream transport error to surface, got %v", err)
214
- }
215
- if _, ok := svc.l1.Get(hashKey(rawKey)); ok {
216
- t.Fatal("entry should have been evicted at hard cap")
217
- }
218
-
219
- found := false
220
- for _, entry := range logs.All() {
221
- if entry.Message == "auth_cache_hard_evict" {
222
- found = true
223
- break
224
- }
225
- }
226
- if !found {
227
- t.Fatal("expected auth_cache_hard_evict log line")
228
- }
229
- }
230
-
231
- // --- Successful refresh resets soft expiry -----------------------------------
232
-
233
- func TestResolve_StaleEntry_RecoveryReplacesEntryWithFreshBundle(t *testing.T) {
234
- freshExp := time.Now().Add(15 * time.Minute)
235
- resolver := &fakeResolver{returns: []resolverReturn{
236
- {bundle: freshBundle("vk_recovered", freshExp)},
237
- }}
238
- svc, _ := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver})
239
- rawKey := "lw_vk_live_recover"
240
- seedExpiredEntry(t, svc, rawKey, "vk_recovered", 30*time.Second)
241
-
242
- bundle, err := svc.Resolve(context.Background(), rawKey)
243
- if err != nil {
244
- t.Fatalf("expected recovery to succeed, got %v", err)
245
- }
246
- if bundle.VirtualKeyID != "vk_recovered" {
247
- t.Fatalf("expected fresh bundle, got %+v", bundle)
248
- }
249
-
250
- e, ok := svc.l1.Get(hashKey(rawKey))
251
- if !ok {
252
- t.Fatal("entry should be present after recovery")
253
- }
254
- _, soft, hard := e.snapshot()
255
- if !soft.Equal(freshExp) {
256
- t.Fatalf("soft expiry should track fresh JWT exp; got %v want %v", soft, freshExp)
257
- }
258
- expectedHard := freshExp.Add(svc.hardGrace)
259
- if !hard.Equal(expectedHard) {
260
- t.Fatalf("hard cap should be fresh exp + hardGrace; got %v want %v", hard, expectedHard)
261
- }
262
- }
263
-
264
- // --- Background refresh classification --------------------------------------
265
-
266
- func TestRefreshBackground_TransportFailure_BumpsSoft(t *testing.T) {
267
- transportErr := herr.New(context.Background(), domain.ErrAuthUpstream, nil)
268
- resolver := &fakeResolver{returns: []resolverReturn{{err: transportErr}}}
269
- svc, logs := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver, SoftBump: 5 * time.Minute})
270
- rawKey := "lw_vk_live_bgtransport"
271
- // Seed an entry near soft expiry but not past it (so background path is invoked).
272
- originalExp := time.Now().Add(30 * time.Second)
273
- svc.storeL1(hashKey(rawKey), freshBundle("vk_bgtransport", originalExp))
274
-
275
- beforeE, _ := svc.l1.Get(hashKey(rawKey))
276
- _, beforeSoft, _ := beforeE.snapshot()
277
-
278
- svc.refreshBackground(rawKey, hashKey(rawKey))
279
-
280
- afterE, ok := svc.l1.Get(hashKey(rawKey))
281
- if !ok {
282
- t.Fatal("entry should remain on background transport failure")
283
- }
284
- _, afterSoft, _ := afterE.snapshot()
285
- if !afterSoft.After(beforeSoft) {
286
- t.Fatalf("expected background transport failure to bump soft; %v -> %v", beforeSoft, afterSoft)
287
- }
288
-
289
- found := false
290
- for _, entry := range logs.All() {
291
- if entry.Message == "auth_cache_refresh_transport_failure" {
292
- found = true
293
- break
294
- }
295
- }
296
- if !found {
297
- t.Fatal("expected warn log on background transport failure")
298
- }
299
- }
300
-
301
- func TestRefreshBackground_AuthRejection_EvictsEntry(t *testing.T) {
302
- resolver := &fakeResolver{returns: []resolverReturn{
303
- {err: herr.New(context.Background(), domain.ErrKeyRevoked, nil)},
304
- }}
305
- svc, _ := newService(t, Options{Resolver: resolver, ConfigFetcher: resolver})
306
- rawKey := "lw_vk_live_bgrevoked"
307
- originalExp := time.Now().Add(30 * time.Second)
308
- svc.storeL1(hashKey(rawKey), freshBundle("vk_bgrevoked", originalExp))
309
-
310
- svc.refreshBackground(rawKey, hashKey(rawKey))
311
-
312
- if _, ok := svc.l1.Get(hashKey(rawKey)); ok {
313
- t.Fatal("entry should be evicted on background auth-rejection")
314
- }
315
- }
316
-
317
- // --- Classifier ---------------------------------------------------------------
318
-
319
- func TestClassifyRefreshError(t *testing.T) {
320
- cases := []struct {
321
- name string
322
- err error
323
- want refreshErrorClass
324
- }{
325
- {"nil", nil, classNone},
326
- {"ErrInvalidAPIKey direct", domain.ErrInvalidAPIKey, classAuthRejection},
327
- {"ErrKeyRevoked direct", domain.ErrKeyRevoked, classAuthRejection},
328
- {"ErrInvalidAPIKey via herr", herr.New(context.Background(), domain.ErrInvalidAPIKey, nil), classAuthRejection},
329
- {"ErrKeyRevoked via herr", herr.New(context.Background(), domain.ErrKeyRevoked, nil), classAuthRejection},
330
- {"ErrAuthUpstream", herr.New(context.Background(), domain.ErrAuthUpstream, nil), classTransportFailure},
331
- {"raw network error", &net.OpError{Op: "dial", Err: errors.New("connection refused")}, classTransportFailure},
332
- {"context deadline exceeded", context.DeadlineExceeded, classTransportFailure},
333
- {"unknown error", errors.New("something we have not anticipated"), classTransportFailure},
334
- }
335
- for _, tc := range cases {
336
- t.Run(tc.name, func(t *testing.T) {
337
- got := classifyRefreshError(tc.err)
338
- if got != tc.want {
339
- t.Fatalf("classifyRefreshError(%v) = %v, want %v", tc.err, got, tc.want)
340
- }
341
- })
342
- }
343
- }
344
-
345
- // --- HardGrace=0 disables stale-while-error (legacy mode) -------------------
346
-
347
- func TestResolve_StaleEntry_HardGraceZero_DisablesStaleWhileError(t *testing.T) {
348
- transportErr := herr.New(context.Background(), domain.ErrAuthUpstream, nil)
349
- // Two returns: first call (foreground) fails, second (re-resolve after evict) also fails.
350
- resolver := &fakeResolver{returns: []resolverReturn{{err: transportErr}, {err: transportErr}}}
351
-
352
- // HardGrace explicitly set to a tiny non-zero value via a separate
353
- // service to verify the contract: any entry stored with bundle.ExpiresAt
354
- // already in the past will be hard-expired immediately, falling through
355
- // to the cold-path L3 (which fails). This documents the legacy-mode
356
- // behavior — operators can opt out of stale-while-error by setting
357
- // HardGrace to a tiny duration.
358
- svc, _ := newService(t, Options{
359
- Resolver: resolver,
360
- ConfigFetcher: resolver,
361
- HardGrace: 1 * time.Nanosecond,
362
- })
363
- rawKey := "lw_vk_live_legacy"
364
- seedExpiredEntry(t, svc, rawKey, "vk_legacy", 30*time.Second)
365
-
366
- _, err := svc.Resolve(context.Background(), rawKey)
367
- if err == nil {
368
- t.Fatal("legacy-mode (no grace) should hard-fail when CP is down")
369
- }
370
- if !errors.Is(err, domain.ErrAuthUpstream) {
371
- t.Fatalf("expected upstream error, got %v", err)
372
- }
373
- }
374
-
375
- // --- Single soft-bump never exceeds hard cap --------------------------------
376
-
377
- func TestEntry_BumpSoft_RespectsHardCap(t *testing.T) {
378
- now := time.Now()
379
- e := &entry{
380
- bundle: freshBundle("vk_x", now.Add(-1*time.Second)),
381
- softExpiresAt: now.Add(-1 * time.Second),
382
- hardExpiresAt: now.Add(2 * time.Second),
383
- }
384
-
385
- newSoft, bumped := e.bumpSoft(10 * time.Second)
386
- if !bumped {
387
- t.Fatal("expected first bump to apply")
388
- }
389
- if newSoft.After(e.hardExpiresAt) {
390
- t.Fatalf("bumpSoft must not exceed hard cap; got %v > %v", newSoft, e.hardExpiresAt)
391
- }
392
- if !newSoft.Equal(e.hardExpiresAt) {
393
- t.Fatalf("bumpSoft should clamp to hard cap when amount overshoots; got %v want %v", newSoft, e.hardExpiresAt)
394
- }
395
-
396
- // Subsequent bump at the cap should be a no-op.
397
- _, bumped2 := e.bumpSoft(10 * time.Second)
398
- if bumped2 {
399
- t.Fatal("expected second bump to be a no-op once at cap")
400
- }
401
- }
402
-
403
- // --- Concurrent stale-bump is race-free -------------------------------------
404
-
405
- func TestEntry_BumpSoft_ConcurrentSafe(t *testing.T) {
406
- now := time.Now()
407
- e := &entry{
408
- bundle: freshBundle("vk_x", now.Add(-1*time.Second)),
409
- softExpiresAt: now.Add(-1 * time.Second),
410
- hardExpiresAt: now.Add(1 * time.Hour),
411
- }
412
-
413
- var wg sync.WaitGroup
414
- for i := 0; i < 100; i++ {
415
- wg.Add(1)
416
- go func() {
417
- defer wg.Done()
418
- _, _ = e.bumpSoft(1 * time.Second)
419
- }()
420
- }
421
- wg.Wait()
422
- // If the test ran without a -race trigger we're good; the only
423
- // behavioral assertion is that softExpiresAt advanced from before.
424
- _, soft, _ := e.snapshot()
425
- if !soft.After(now) {
426
- t.Fatal("expected soft to be in the future after concurrent bumps")
427
- }
428
- }
429
-
430
- // --- Print helper for clearer test output -----------------------------------
431
-
432
- func init() {
433
- // Force errors.Is on string comparisons to surface as comparable in test failures.
434
- _ = fmt.Sprintf
435
- }
@@ -1,50 +0,0 @@
1
- package budget
2
-
3
- import (
4
- "context"
5
- "testing"
6
-
7
- "github.com/langwatch/langwatch/services/aigateway/domain"
8
- )
9
-
10
- // BenchmarkPrecheck measures the cached precheck path — runs on every
11
- // inbound /v1 request before dispatch. Must be nanosecond-level.
12
- func BenchmarkPrecheck(b *testing.B) {
13
- checker := NewChecker(CheckerOptions{Logger: nil})
14
- bundle := &domain.Bundle{
15
- Config: domain.BundleConfig{
16
- Budget: domain.BudgetConfig{
17
- Scopes: []domain.BudgetScope{
18
- {Scope: "virtual_key", Window: "day", LimitMicroUSD: 25_000_000, SpentMicroUSD: 12_500_000, OnBreach: "block"},
19
- {Scope: "project", Window: "month", LimitMicroUSD: 1_000_000_000, SpentMicroUSD: 437_550_000, OnBreach: "block"},
20
- {Scope: "team", Window: "month", LimitMicroUSD: 5_000_000_000, SpentMicroUSD: 3_210_000_000, OnBreach: "warn"},
21
- },
22
- },
23
- },
24
- }
25
- ctx := context.Background()
26
- b.ReportAllocs()
27
- for i := 0; i < b.N; i++ {
28
- _, _ = checker.Precheck(ctx, bundle)
29
- }
30
- }
31
-
32
- // BenchmarkPrecheck_HardStop measures the short-circuit case (any
33
- // hard-cap scope breached).
34
- func BenchmarkPrecheck_HardStop(b *testing.B) {
35
- checker := NewChecker(CheckerOptions{Logger: nil})
36
- bundle := &domain.Bundle{
37
- Config: domain.BundleConfig{
38
- Budget: domain.BudgetConfig{
39
- Scopes: []domain.BudgetScope{
40
- {Scope: "virtual_key", Window: "day", LimitMicroUSD: 25_000_000, SpentMicroUSD: 25_010_000, OnBreach: "block"},
41
- },
42
- },
43
- },
44
- }
45
- ctx := context.Background()
46
- b.ReportAllocs()
47
- for i := 0; i < b.N; i++ {
48
- _, _ = checker.Precheck(ctx, bundle)
49
- }
50
- }
@@ -1,59 +0,0 @@
1
- // Package budget implements budget precheck on the gateway hot path.
2
- //
3
- // Debits are NOT sent from the gateway. Cost is captured on the OTel span
4
- // emitted by the trace bridge; the control plane's trace-fold reactor
5
- // (langwatch/src/server/event-sourcing/pipelines/trace-processing/reactors/
6
- // gatewayBudgetSync.reactor.ts) writes ClickHouse ledger rows from the
7
- // span attributes. Single source of truth, no PG dual-write.
8
- package budget
9
-
10
- import (
11
- "context"
12
-
13
- "go.uber.org/zap"
14
-
15
- "github.com/langwatch/langwatch/services/aigateway/domain"
16
- )
17
-
18
- // Checker implements BudgetChecker with a cached precheck path.
19
- type Checker struct {
20
- logger *zap.Logger
21
- }
22
-
23
- // CheckerOptions configures the budget checker.
24
- type CheckerOptions struct {
25
- Logger *zap.Logger
26
- }
27
-
28
- // NewChecker creates a budget checker.
29
- func NewChecker(opts CheckerOptions) *Checker {
30
- return &Checker{logger: opts.Logger}
31
- }
32
-
33
- // Precheck evaluates cached budget snapshots. Never calls control plane on hot path.
34
- // Permissive by default: stale data allows the request through, debit reconciles later.
35
- func (c *Checker) Precheck(_ context.Context, bundle *domain.Bundle) (domain.BudgetVerdict, error) {
36
- if len(bundle.Config.Budget.Scopes) == 0 {
37
- return domain.BudgetAllow, nil
38
- }
39
-
40
- for _, scope := range bundle.Config.Budget.Scopes {
41
- if scope.LimitMicroUSD <= 0 {
42
- continue
43
- }
44
- remaining := scope.LimitMicroUSD - scope.SpentMicroUSD
45
- switch scope.OnBreach {
46
- case "block":
47
- if remaining <= 0 {
48
- return domain.BudgetBlock, nil
49
- }
50
- case "warn":
51
- pctUsed := (scope.SpentMicroUSD * 100) / scope.LimitMicroUSD
52
- if remaining <= 0 || pctUsed >= 90 {
53
- return domain.BudgetWarn, nil
54
- }
55
- }
56
- }
57
-
58
- return domain.BudgetAllow, nil
59
- }
@@ -1,134 +0,0 @@
1
- // Package cacherules evaluates cache control rules against requests.
2
- package cacherules
3
-
4
- import (
5
- "context"
6
- "path"
7
- "sort"
8
- "strings"
9
-
10
- "github.com/langwatch/langwatch/services/aigateway/domain"
11
- )
12
-
13
- // Evaluator evaluates priority-ordered cache rules.
14
- type Evaluator struct{}
15
-
16
- // NewEvaluator creates a cache rule evaluator.
17
- func NewEvaluator() *Evaluator {
18
- return &Evaluator{}
19
- }
20
-
21
- // Evaluate returns the first matching cache rule's action, or nil if no rule matches.
22
- func (e *Evaluator) Evaluate(_ context.Context, rules []domain.CacheRule, eval domain.CacheEvalContext) *domain.CacheDecision {
23
- if len(rules) == 0 {
24
- return nil
25
- }
26
-
27
- // Sort by priority (lower = higher priority)
28
- sorted := make([]domain.CacheRule, len(rules))
29
- copy(sorted, rules)
30
- sort.Slice(sorted, func(i, j int) bool {
31
- return sorted[i].Priority < sorted[j].Priority
32
- })
33
-
34
- for i := range sorted {
35
- rule := &sorted[i]
36
- if matchesRule(rule.Match, eval) {
37
- return &domain.CacheDecision{
38
- Action: rule.Action,
39
- RuleID: rule.ID,
40
- }
41
- }
42
- }
43
-
44
- return nil
45
- }
46
-
47
- // matchesRule reports whether the rule's matchers ALL match the request /
48
- // VK context (AND across matcher kinds; OR within a matcher's value list).
49
- // An empty matcher kind contributes "true" (no filter) — kept so an
50
- // operator-defined org-wide rule with no matchers still matches every VK.
51
- //
52
- // Each non-empty matcher MUST resolve to a positive match against the eval
53
- // context. Missing eval-context data (e.g. no VKDisplayPrefix wired) when
54
- // the rule expects it counts as "doesn't match" — fail-safe so wiring gaps
55
- // don't accidentally apply rules to traffic the operator didn't intend.
56
- func matchesRule(match domain.CacheRuleMatch, eval domain.CacheEvalContext) bool {
57
- if !matchesAnyGlob(match.Models, eval.Model) {
58
- return false
59
- }
60
- if !matchesAnyExact(match.Principals, eval.PrincipalID) {
61
- return false
62
- }
63
- if !matchesAnyExact(match.VKIDs, eval.VKID) {
64
- return false
65
- }
66
- if !matchesAnyPrefix(match.VKPrefixes, eval.VKDisplayPrefix) {
67
- return false
68
- }
69
- if !matchesAllTags(match.VKTags, eval.VKTags) {
70
- return false
71
- }
72
- return true
73
- }
74
-
75
- // matchesAnyGlob: empty patterns ⇒ no filter (true). Otherwise at least one
76
- // path-glob pattern must match the value.
77
- func matchesAnyGlob(patterns []string, value string) bool {
78
- if len(patterns) == 0 {
79
- return true
80
- }
81
- for _, pattern := range patterns {
82
- if matched, _ := path.Match(pattern, value); matched {
83
- return true
84
- }
85
- }
86
- return false
87
- }
88
-
89
- func matchesAnyExact(allowed []string, value string) bool {
90
- if len(allowed) == 0 {
91
- return true
92
- }
93
- for _, v := range allowed {
94
- if v == value {
95
- return true
96
- }
97
- }
98
- return false
99
- }
100
-
101
- func matchesAnyPrefix(prefixes []string, value string) bool {
102
- if len(prefixes) == 0 {
103
- return true
104
- }
105
- if value == "" {
106
- return false
107
- }
108
- for _, p := range prefixes {
109
- if strings.HasPrefix(value, p) {
110
- return true
111
- }
112
- }
113
- return false
114
- }
115
-
116
- // matchesAllTags requires every matcher tag to be present on the VK's tag
117
- // set. Empty matcher tags ⇒ no filter. Empty VK tags + non-empty matcher
118
- // tags ⇒ doesn't match (AND semantics, the operator gated on a tag the VK
119
- // lacks).
120
- func matchesAllTags(required, vkTags []string) bool {
121
- if len(required) == 0 {
122
- return true
123
- }
124
- tagSet := make(map[string]struct{}, len(vkTags))
125
- for _, t := range vkTags {
126
- tagSet[t] = struct{}{}
127
- }
128
- for _, want := range required {
129
- if _, ok := tagSet[want]; !ok {
130
- return false
131
- }
132
- }
133
- return true
134
- }