-
Notifications
You must be signed in to change notification settings - Fork 40
fix(proxy): consume UsageBypass on OpenAI chat completions #776
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rohith500
wants to merge
3
commits into
workweave:main
Choose a base branch
from
rohith500:fix/openai-usage-bypass-consumer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| package proxy_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "workweave/router/internal/billing" | ||
| "workweave/router/internal/providers" | ||
| "workweave/router/internal/proxy" | ||
| "workweave/router/internal/proxy/usage" | ||
| "workweave/router/internal/router" | ||
|
|
||
| "github.com/google/uuid" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func oaiBypassBody() []byte { | ||
| return []byte(`{"model":"` + bypassRequestedMdl + `","messages":[{"role":"user","content":"hi"}]}`) | ||
| } | ||
|
|
||
| // TestProxyOpenAI_UsageBypass_BelowThreshold_SkipsScorer: gate on + headroom skips scorer on OpenAI wire. | ||
| func TestProxyOpenAI_UsageBypass_BelowThreshold_SkipsScorer(t *testing.T) { | ||
| svc, fr, p := bypassFixture(t, 0.20) | ||
| rec := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("")) | ||
|
|
||
| require.NoError(t, svc.ProxyOpenAIChatCompletion(bypassCtx(0.80), oaiBypassBody(), rec, req)) | ||
|
|
||
| assert.Equal(t, 0, fr.routeCalls, "scorer must not run while subscription has headroom") | ||
| require.Len(t, p.proxyBodies, 1) | ||
| assert.Contains(t, string(p.proxyBodies[0]), `"`+bypassRequestedMdl+`"`) | ||
| assert.Equal(t, "usage_bypass", rec.Header().Get(proxy.HeaderRouterDecision)) | ||
| assert.Equal(t, bypassRequestedMdl, rec.Header().Get(proxy.HeaderRouterModel)) | ||
| assert.Contains(t, rec.Body.String(), `"object":"chat.completion"`) | ||
| } | ||
|
|
||
| // TestProxyOpenAI_UsageBypass_WeeklyLimit_FallsBackToRoutedDispatch: bypass 429 must reroute via routeFor. | ||
| func TestProxyOpenAI_UsageBypass_WeeklyLimit_FallsBackToRoutedDispatch(t *testing.T) { | ||
| bypassResp := &providers.UpstreamErrorResponse{ | ||
| Status: http.StatusTooManyRequests, | ||
| Headers: http.Header{ | ||
| "anthropic-ratelimit-unified-weekly-limit": []string{"100000"}, | ||
| "anthropic-ratelimit-unified-weekly-reset": []string{"2025-12-31T00:00:00Z"}, | ||
| "anthropic-ratelimit-unified-weekly-remaining": []string{"0"}, | ||
| }, | ||
| Body: []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"weekly limit exceeded"}}`), | ||
| } | ||
| routedResp := func(w http.ResponseWriter) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","role":"assistant","model":"` + bypassScorerPickMdl + `","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)) | ||
| } | ||
| inner := &fakeProvider{proxyResponse: routedResp} | ||
| wrappedP := &swapErrProvider{first: bypassResp, second: nil, inner: inner} | ||
| fr := &fakeRouter{decision: router.Decision{Provider: providers.ProviderAnthropic, Model: bypassScorerPickMdl, Reason: "cluster:v0.2"}} | ||
| obs := usage.NewObserver([]byte("salt"), 10*time.Minute, time.Now) | ||
| obs.Record(obs.Key([]byte(bypassSubToken)), usage.Snapshot{ | ||
| Primary: usage.Window{UsedPercent: 0.20, WindowMinutes: 300}, | ||
| }) | ||
| svc := proxy.NewService(fr, map[string]providers.Client{providers.ProviderAnthropic: wrappedP}, nil, false, nil, nil, false, providers.ProviderAnthropic, bypassScorerPickMdl, nil). | ||
| WithSubscriptionAwareRouting(obs, 0.05, 2.0) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("")) | ||
| ctx := bypassCtx(0.80) | ||
| ctx = context.WithValue(ctx, proxy.ExternalIDContextKey{}, "org-oai-bypass-reroute") | ||
| ctx = context.WithValue(ctx, proxy.InstallationIDContextKey{}, uuid.New().String()) | ||
|
|
||
| require.NoError(t, svc.ProxyOpenAIChatCompletion(ctx, oaiBypassBody(), rec, req)) | ||
|
|
||
| assert.Equal(t, 1, fr.routeCalls, "scorer must run once on the reroute after bypass 429") | ||
| assert.NotEqual(t, http.StatusTooManyRequests, rec.Code, "the 429 must not be flushed to the client") | ||
| assert.Equal(t, bypassScorerPickMdl, rec.Header().Get(proxy.HeaderRouterModel)) | ||
| assert.Equal(t, "cluster:v0.2", rec.Header().Get(proxy.HeaderRouterDecision)) | ||
| assert.Contains(t, rec.Body.String(), `"object":"chat.completion"`) | ||
| } | ||
|
|
||
| // TestSubscriptionOnly_OpenAI_BypassRetryable_Refuses402: subscription-only refuses retryable bypass failure. | ||
| func TestSubscriptionOnly_OpenAI_BypassRetryable_Refuses402(t *testing.T) { | ||
| bypassResp := &providers.UpstreamErrorResponse{ | ||
| Status: http.StatusTooManyRequests, | ||
| Body: []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"weekly limit exceeded"}}`), | ||
| } | ||
| p := &fakeProvider{proxyErr: bypassResp} | ||
| wrappedP := &swapErrProvider{first: bypassResp, second: nil, inner: p} | ||
| fr := &fakeRouter{decision: router.Decision{Provider: providers.ProviderAnthropic, Model: bypassScorerPickMdl, Reason: "cluster:v0.2"}} | ||
| obs := usage.NewObserver([]byte("salt"), 10*time.Minute, time.Now) | ||
| obs.Record(obs.Key([]byte(bypassSubToken)), usage.Snapshot{ | ||
| Primary: usage.Window{UsedPercent: 0.20, WindowMinutes: 300}, | ||
| }) | ||
| svc := proxy.NewService(fr, map[string]providers.Client{providers.ProviderAnthropic: wrappedP}, nil, false, nil, nil, false, providers.ProviderAnthropic, bypassScorerPickMdl, nil). | ||
| WithSubscriptionAwareRouting(obs, 0.05, 2.0) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("")) | ||
| err := svc.ProxyOpenAIChatCompletion(billing.WithSubscriptionOnly(bypassCtx(0.80)), oaiBypassBody(), rec, req) | ||
| require.Error(t, err) | ||
| assert.True(t, errors.Is(err, proxy.ErrCreditsExhaustedSubscriptionUnavailable)) | ||
| assert.Equal(t, 0, fr.routeCalls) | ||
| assert.Equal(t, 1, wrappedP.calls) | ||
| } | ||
|
|
||
| // TestSubscriptionOnly_OpenAI_BypassRetryable_Stream_NoPartialCommit: streaming Prelude stays buffered until Discard on 402. | ||
| func TestSubscriptionOnly_OpenAI_BypassRetryable_Stream_NoPartialCommit(t *testing.T) { | ||
| bypassResp := &providers.UpstreamErrorResponse{ | ||
| Status: http.StatusTooManyRequests, | ||
| Body: []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"weekly limit exceeded"}}`), | ||
| } | ||
| p := &fakeProvider{proxyErr: bypassResp} | ||
| wrappedP := &swapErrProvider{first: bypassResp, second: nil, inner: p} | ||
| fr := &fakeRouter{decision: router.Decision{Provider: providers.ProviderAnthropic, Model: bypassScorerPickMdl, Reason: "cluster:v0.2"}} | ||
| obs := usage.NewObserver([]byte("salt"), 10*time.Minute, time.Now) | ||
| obs.Record(obs.Key([]byte(bypassSubToken)), usage.Snapshot{ | ||
| Primary: usage.Window{UsedPercent: 0.20, WindowMinutes: 300}, | ||
| }) | ||
| svc := proxy.NewService(fr, map[string]providers.Client{providers.ProviderAnthropic: wrappedP}, nil, false, nil, nil, false, providers.ProviderAnthropic, bypassScorerPickMdl, nil). | ||
| WithSubscriptionAwareRouting(obs, 0.05, 2.0) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader("")) | ||
| body := []byte(`{"model":"` + bypassRequestedMdl + `","stream":true,"messages":[{"role":"user","content":"hi"}]}`) | ||
| err := svc.ProxyOpenAIChatCompletion(billing.WithSubscriptionOnly(bypassCtx(0.80)), body, rec, req) | ||
| require.Error(t, err) | ||
| assert.True(t, errors.Is(err, proxy.ErrCreditsExhaustedSubscriptionUnavailable)) | ||
| assert.Equal(t, 0, fr.routeCalls) | ||
| assert.Equal(t, 1, wrappedP.calls) | ||
| assert.Empty(t, rec.Body.String(), "retryable bypass must Discard buffered Prelude; client must see no SSE bytes") | ||
| assert.False(t, rec.Flushed, "HTTP status must not be committed before the 402 mapping") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.