Files
CLIProxyAPI/internal/runtime/executor/antigravity_policy_errors_test.go

1800 lines
79 KiB
Go

package executor
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
log "github.com/sirupsen/logrus"
)
type safetySignalLogHook struct {
mu sync.Mutex
entries []*log.Entry
}
func (h *safetySignalLogHook) Levels() []log.Level {
return []log.Level{log.WarnLevel}
}
func (h *safetySignalLogHook) Fire(entry *log.Entry) error {
h.mu.Lock()
h.entries = append(h.entries, entry)
h.mu.Unlock()
return nil
}
func (h *safetySignalLogHook) messages() []string {
h.mu.Lock()
defer h.mu.Unlock()
out := make([]string, 0, len(h.entries))
for _, e := range h.entries {
out = append(out, e.Message)
}
return out
}
func TestAntigravityStopReasonTextIsNotAPolicyDenial(t *testing.T) {
const text = "Describe StopReason == 0xb and finishReason == 11."
const requestBody = `{"request":{"contents":[{"role":"user","parts":[{"text":"` + text + `"}]}]}}`
const responseBody = `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"` + text + `"}]},"finishReason":"STOP"}]}}`
for _, mode := range []string{"unary", "stream"} {
t.Run(mode, func(t *testing.T) {
stream := mode == "stream"
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
body, errRead := io.ReadAll(r.Body)
if errRead != nil || !bytes.Contains(body, []byte(text)) {
http.Error(w, "mock did not receive the ordinary user text", http.StatusBadRequest)
return
}
if stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = fmt.Fprint(w, "data: "+responseBody+"\n\n")
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, responseBody)
}))
t.Cleanup(server.Close)
auth := newIssue7882Auth(t.Name(), server.URL)
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
exec := NewAntigravityExecutor(&config.Config{})
req := cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: []byte(requestBody)}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var out strings.Builder
if stream {
res, errStream := exec.ExecuteStream(t.Context(), auth, req, opts)
if errStream != nil {
t.Fatalf("ordinary text caused a stream error: %v", errStream)
}
for chunk := range res.Chunks {
if chunk.Err != nil {
t.Fatalf("ordinary text caused a chunk error: %v", chunk.Err)
}
out.Write(chunk.Payload)
}
} else {
res, errExec := exec.Execute(t.Context(), auth, req, opts)
if errExec != nil {
t.Fatalf("ordinary text caused a unary error: %v", errExec)
}
out.Write(res.Payload)
}
if calls.Load() != 1 || !strings.Contains(out.String(), text) {
t.Fatalf("got %d upstream calls and payload %q, want one call preserving ordinary text", calls.Load(), out.String())
}
})
}
}
func TestAntigravityTerminalBillingAndPolicyCodes(t *testing.T) {
t.Run("decideAntigravity429WithHeaders classifies all 4 new quota codes in object and array forms", func(t *testing.T) {
quotaReasons := []string{
"QUOTA_EXHAUSTED",
"QUOTA_ENDPOINT_EXHAUSTED",
"QUOTA_PRODUCT_EXHAUSTED",
"QUOTA_RECIPE_EXHAUSTED",
"GEMINI_ENTERPRISE_USER_QUOTA_EXHAUSTED",
"INSUFFICIENT_G1_CREDITS_BALANCE",
}
for _, reason := range quotaReasons {
for _, wrapped := range []bool{false, true} {
raw := fmt.Sprintf(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"limit reached","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"120s"}]}}`, reason)
if wrapped {
raw = "[" + raw + "]"
}
decision := decideAntigravity429WithHeaders([]byte(raw), nil)
if decision.kind != antigravity429DecisionFullQuotaExhausted {
t.Fatalf("reason=%s wrapped=%v: kind = %q, want %q", reason, wrapped, decision.kind, antigravity429DecisionFullQuotaExhausted)
}
if decision.reason != reason {
t.Fatalf("reason=%s wrapped=%v: decision.reason = %q, want %q", reason, wrapped, decision.reason, reason)
}
}
}
})
t.Run("decideAntigravity429WithHeaders classifies MODEL_CAPACITY_EXHAUSTED by retryAfter threshold", func(t *testing.T) {
shortObj := []byte(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"MODEL_CAPACITY_EXHAUSTED"},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"1s"}]}}`)
shortArr := append([]byte("["), append(shortObj, ']')...)
for _, body := range [][]byte{shortObj, shortArr} {
d := decideAntigravity429WithHeaders(body, nil)
if d.kind != antigravity429DecisionInstantRetrySameAuth {
t.Fatalf("MODEL_CAPACITY_EXHAUSTED(1s) kind = %q, want %q", d.kind, antigravity429DecisionInstantRetrySameAuth)
}
}
longObj := []byte(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"MODEL_CAPACITY_EXHAUSTED"},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"15s"}]}}`)
if d := decideAntigravity429WithHeaders(longObj, nil); d.kind != antigravity429DecisionShortCooldownSwitchAuth {
t.Fatalf("MODEL_CAPACITY_EXHAUSTED(15s) kind = %q, want %q", d.kind, antigravity429DecisionShortCooldownSwitchAuth)
}
noDelayObj := []byte(`[{"error":{"code":429,"status":"UNAVAILABLE","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"MODEL_CAPACITY_EXHAUSTED"}]}}]`)
if d := decideAntigravity429WithHeaders(noDelayObj, nil); d.kind != antigravity429DecisionShortCooldownSwitchAuth {
t.Fatalf("MODEL_CAPACITY_EXHAUSTED(nil) kind = %q, want %q", d.kind, antigravity429DecisionShortCooldownSwitchAuth)
}
})
t.Run("credential-terminal codes set credentialScoped without same-auth retry loops", func(t *testing.T) {
credReasons := []string{
"MONETIZATION_DENIED",
"GEMINI_ENTERPRISE_LICENSE_NOT_VALID",
"GEMINI_ENTERPRISE_LICENSE_REQUIRED",
"INELIGIBLE_ACCOUNT",
"INELIGIBLE_BYOM_DOWNGRADE",
}
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
for _, reason := range credReasons {
t.Run(reason, func(t *testing.T) {
body := []byte(fmt.Sprintf(`[{"error":{"code":403,"status":"PERMISSION_DENIED","message":"blocked","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q}]}}]`, reason))
gotReason, credTerm, reqTerm := helps.ParseAntigravityPolicyError(body)
if gotReason != reason || !credTerm || reqTerm {
t.Fatalf("ParseAntigravityPolicyError(%s) = (%q, %v, %v), want (%q, true, false)", reason, gotReason, credTerm, reqTerm, reason)
}
sErr := newAntigravityStatusErrWithHeaders(http.StatusForbidden, nil, body)
if !sErr.IsCredentialScoped() {
t.Fatalf("%s: IsCredentialScoped() = false, want true", reason)
}
if sErr.IsRequestStop() {
t.Fatalf("%s: IsRequestStop() = true, want false", reason)
}
// Verify Execute performs ZERO same-auth micro-retries even if status is 429 or 503.
sleeps := installFakeTPUSleeper(t, nil)
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
attempts.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write(body)
}))
defer server.Close()
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("policy-cred-"+reason, server.URL)
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
_, errExec := exec.Execute(context.Background(), auth, cliproxyexecutor.Request{
Model: "gemini-4-argon",
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
var gotErr statusErr
if !errors.As(errExec, &gotErr) || !gotErr.IsCredentialScoped() || gotErr.IsRequestStop() {
t.Fatalf("Execute(%s) err = %#v, want credentialScoped=true requestStop=false", reason, errExec)
}
if attempts.Load() != 1 || len(*sleeps) != 0 {
t.Fatalf("Execute(%s) attempts=%d sleeps=%v, want 1 attempt and 0 sleeps", reason, attempts.Load(), *sleeps)
}
})
}
})
t.Run("request/pool-terminal policy codes stop conductor without fanning out to healthy sibling Auth B", func(t *testing.T) {
reqReasons := []string{
"UNSUPPORTED_CLIENT",
"AI_POLICY_REQUIRED",
"AI_POLICY_SOFT_BLOCK_BANNER",
"AI_POLICY_SOFT_BLOCK_CLI",
"TOS_VIOLATION",
}
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
for _, reason := range reqReasons {
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run(reason+"/"+mode, func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
body := fmt.Sprintf(`[{"error":{"code":403,"status":"PERMISSION_DENIED","message":"denied by %s","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q}]}}]`, reason, reason)
gotReason, credTerm, reqTerm := helps.ParseAntigravityPolicyError([]byte(body))
wantCredTerm := reason == "TOS_VIOLATION"
if gotReason != reason || credTerm != wantCredTerm || !reqTerm {
t.Fatalf("ParseAntigravityPolicyError(%s) = (%q, %v, %v), want (%q, %v, true)", reason, gotReason, credTerm, reqTerm, reason, wantCredTerm)
}
var upstreamHits atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
upstreamHits.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(body))
}))
defer server.Close()
model := fmt.Sprintf("gemini-4-argon-policy-%s-%s", strings.ToLower(reason), mode)
cfg := &config.Config{}
exec := &countingAntigravityExecutor{
AntigravityExecutor: NewAntigravityExecutor(cfg),
}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newIssue7882Auth("policy-auth-a-"+reason+"-"+mode, server.URL)
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("policy-auth-b-"+reason+"-"+mode, server.URL)
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, opts)
} else {
_, errRun = manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, opts)
}
if errRun == nil {
t.Fatalf("%s/%s error = nil, want 403 policy stop error", reason, mode)
}
calls := exec.recordedCalls()
if len(calls) != 1 || upstreamHits.Load() != 1 {
t.Fatalf("%s/%s calls=%v upstreamHits=%d, want 1 call (MUST NOT fan out to healthy sibling Auth B)", reason, mode, calls, upstreamHits.Load())
}
siblingID := authB.ID
if calls[0] == authB.ID {
siblingID = authA.ID
}
sibling, ok := manager.GetByID(siblingID)
if !ok || sibling == nil || sibling.Status != cliproxyauth.StatusActive || sibling.Unavailable || sibling.Failed != 0 {
t.Fatalf("healthy sibling %s was unexpectedly touched: %+v", siblingID, sibling)
}
firstAuth, _ := manager.GetByID(calls[0])
if reason == "TOS_VIOLATION" {
if !firstAuth.Disabled || firstAuth.Status != cliproxyauth.StatusDisabled {
t.Fatalf("TOS_VIOLATION auth %s was not disabled: status=%q disabled=%v", firstAuth.ID, firstAuth.Status, firstAuth.Disabled)
}
} else {
if firstAuth.Disabled || firstAuth.Unavailable || firstAuth.Status != cliproxyauth.StatusActive {
t.Fatalf("request-terminal %s needlessly disabled/cooled auth %s: status=%q disabled=%v unavailable=%v", reason, firstAuth.ID, firstAuth.Status, firstAuth.Disabled, firstAuth.Unavailable)
}
}
})
}
}
})
t.Run("credential-terminal policy codes fail over from Auth A to healthy sibling Auth B in conductor", func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
credFailoverReasons := []string{
"MONETIZATION_DENIED",
"GEMINI_ENTERPRISE_LICENSE_NOT_VALID",
"GEMINI_ENTERPRISE_LICENSE_REQUIRED",
"INELIGIBLE_ACCOUNT",
"INELIGIBLE_BYOM_DOWNGRADE",
}
for _, reason := range credFailoverReasons {
t.Run(reason, func(t *testing.T) {
body403 := fmt.Sprintf(`[{"error":{"code":403,"status":"PERMISSION_DENIED","message":"blocked by %s","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q}]}}]`, reason, reason)
successBody := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok-from-sibling"}]}}]}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.Header.Get("Authorization"), "cred-failover-a-") {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(body403))
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(successBody))
}))
defer server.Close()
model := "gemini-4-argon-credfailover-" + strings.ToLower(reason)
cfg := &config.Config{}
exec := &countingAntigravityExecutor{
AntigravityExecutor: NewAntigravityExecutor(cfg),
}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newIssue7882Auth("cred-failover-a-"+reason, server.URL)
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("cred-failover-b-"+reason, server.URL)
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
resp, errRun := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
if errRun != nil {
t.Fatalf("Execute(%s) error = %v, want failover success on healthy sibling Auth B", reason, errRun)
}
if !strings.Contains(string(resp.Payload), "ok-from-sibling") {
t.Fatalf("Execute(%s) payload = %s, want ok-from-sibling", reason, string(resp.Payload))
}
calls := exec.recordedCalls()
if len(calls) != 2 || calls[0] != authA.ID || calls[1] != authB.ID {
t.Fatalf("Execute(%s) calls = %v, want [%s %s]", reason, calls, authA.ID, authB.ID)
}
})
}
})
t.Run("SafetySignals VIOLATIVE logs at Warn level without mutating response payload", func(t *testing.T) {
hook := &safetySignalLogHook{}
log.AddHook(hook)
t.Cleanup(func() {
hooks := log.StandardLogger().Hooks
for _, level := range hook.Levels() {
filtered := hooks[level][:0]
for _, existing := range hooks[level] {
if existing != hook {
filtered = append(filtered, existing)
}
}
hooks[level] = filtered
}
})
violativeUnary := []byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hello"}]}}],"metadata":{"safetySignals":{"sybillVerdicts":{"verdict":"VIOLATIVE"},"introspectionVerdicts":{"verdict":"VIOLATIVE"}}}},"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}`)
origCopy := bytes.Clone(violativeUnary)
helps.ObserveAntigravitySafetySignals("auth-safety-1", violativeUnary)
if !bytes.Equal(violativeUnary, origCopy) {
t.Fatal("ObserveAntigravitySafetySignals mutated input payload")
}
// Top-level metadata path too.
topLevelViolative := []byte(`{"metadata":{"safetySignals":{"sybillVerdicts":{"verdict":"VIOLATIVE"}}}}`)
helps.ObserveAntigravitySafetySignals("auth-safety-2", topLevelViolative)
// NON_VIOLATIVE must not emit a warning.
nonViolative := []byte(`{"response":{"metadata":{"safetySignals":{"sybillVerdicts":{"verdict":"NON_VIOLATIVE"},"introspectionVerdicts":{"verdict":"NON_VIOLATIVE"}}}}}`)
helps.ObserveAntigravitySafetySignals("auth-safety-non", nonViolative)
msgs := hook.messages()
var sawSybill1, sawIntro1, sawSybill2, sawNon bool
for _, m := range msgs {
if strings.Contains(m, "auth-safety-1") && strings.Contains(m, "sybillVerdicts") && strings.Contains(m, "VIOLATIVE") {
sawSybill1 = true
}
if strings.Contains(m, "auth-safety-1") && strings.Contains(m, "introspectionVerdicts") && strings.Contains(m, "VIOLATIVE") {
sawIntro1 = true
}
if strings.Contains(m, "auth-safety-2") && strings.Contains(m, "sybillVerdicts") && strings.Contains(m, "VIOLATIVE") {
sawSybill2 = true
}
if strings.Contains(m, "auth-safety-non") {
sawNon = true
}
}
if !sawSybill1 || !sawIntro1 || !sawSybill2 {
t.Fatalf("missing expected SafetySignals Warn logs; got=%v", msgs)
}
if sawNon {
t.Fatalf("unexpected Warn log for NON_VIOLATIVE safetySignals; got=%v", msgs)
}
// Verify ExecuteStream observes SafetySignals without mutating emitted payload.
sseBody := "data: " + string(violativeUnary) + "\n\n"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(sseBody))
}))
defer server.Close()
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("auth-safety-stream", server.URL)
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
streamRes, errStream := exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{
Model: "gemini-4-argon",
Payload: []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`),
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: true,
})
if errStream != nil {
t.Fatalf("ExecuteStream() err = %v", errStream)
}
var out strings.Builder
for ch := range streamRes.Chunks {
if ch.Err != nil {
t.Fatalf("unexpected chunk err = %v", ch.Err)
}
out.Write(ch.Payload)
}
if !strings.Contains(out.String(), `"sybillVerdicts":{"verdict":"VIOLATIVE"}`) {
t.Fatalf("stream payload lost safetySignals metadata: %s", out.String())
}
var sawStreamWarn bool
for _, m := range hook.messages() {
if strings.Contains(m, "auth-safety-stream") && strings.Contains(m, "VIOLATIVE") {
sawStreamWarn = true
}
}
if !sawStreamWarn {
t.Fatalf("expected Warn log during ExecuteStream for auth-safety-stream, got=%v", hook.messages())
}
})
t.Run("loadCodeAssist 403 TOS_VIOLATION stops Execute and ExecuteStream with zero calls to healthy sibling Auth B", func(t *testing.T) {
const tosBody = `{"error":{"code":403,"message":"Violation of Terms of Service","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"TOS_VIOLATION","domain":"cloudcode-pa.googleapis.com"}]}}`
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run(mode, func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
var loadCalls atomic.Int32
var siblingCalls atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
if r.Body != nil {
_, _ = io.ReadAll(r.Body)
}
if strings.HasSuffix(r.URL.Path, ":loadCodeAssist") {
loadCalls.Add(1)
return &http.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(tosBody)),
}, nil
}
siblingCalls.Add(1)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"should-not-run"}]}}]}}`)),
}, nil
})
// Pool pause explicitly disabled (empty TOSPauseWindow).
cfg := &config.Config{}
cfg.Antigravity.TOSPauseWindow = ""
exec := NewAntigravityExecutor(cfg)
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRoundTripperProvider(issue7751StaticRTProvider{rt: rt})
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
model := "gemini-4-argon-prep-tos-" + mode
authA := newIssue7882Auth("prep-tos-a-"+mode, "https://example.invalid")
delete(authA.Metadata, "project_id")
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("prep-tos-b-"+mode, "https://example.invalid")
authB.Status = cliproxyauth.StatusActive
reg := registry.GetGlobalRegistry()
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
ctx := cliproxyauth.WithSkipPersist(context.Background())
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
} else {
_, errRun = manager.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("%s error = nil, want 403 TOS_VIOLATION stop", mode)
}
if loadCalls.Load() != 1 {
t.Fatalf("%s loadCodeAssist calls = %d, want 1", mode, loadCalls.Load())
}
if siblingCalls.Load() != 0 {
t.Fatalf("%s sibling Auth B calls = %d, want 0", mode, siblingCalls.Load())
}
snapA, _ := manager.GetByID(authA.ID)
if !snapA.Disabled || snapA.Status != cliproxyauth.StatusDisabled {
t.Fatalf("Auth A was not disabled: status=%q disabled=%v", snapA.Status, snapA.Disabled)
}
snapB, _ := manager.GetByID(authB.ID)
if snapB.Disabled || snapB.Unavailable || snapB.Status != cliproxyauth.StatusActive {
t.Fatalf("healthy sibling Auth B was unexpectedly mutated: %+v", snapB)
}
})
}
})
t.Run("loadCodeAssist 403 UNSUPPORTED_CLIENT under continue-and-cooldown stops without cooling healthy Auth A", func(t *testing.T) {
const unsupportedBody = `[{"error":{"code":403,"message":"Unsupported client","status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"UNSUPPORTED_CLIENT","domain":"cloudcode-pa.googleapis.com"}]}}]`
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run(mode, func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
var loadCalls atomic.Int32
var siblingCalls atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
if r.Body != nil {
_, _ = io.ReadAll(r.Body)
}
if strings.HasSuffix(r.URL.Path, ":loadCodeAssist") {
loadCalls.Add(1)
return &http.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(unsupportedBody)),
}, nil
}
siblingCalls.Add(1)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"should-not-run"}]}}]}}`)),
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusForbidden, Match: []string{"UNSUPPORTED_CLIENT"}, Action: cliproxyauth.RequestScopedActionContinueAndCooldown}},
},
}
exec := NewAntigravityExecutor(cfg)
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetConfig(cfg)
manager.SetRoundTripperProvider(issue7751StaticRTProvider{rt: rt})
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
model := "gemini-4-argon-prep-unsupported-" + mode
authA := newIssue7882Auth("prep-unsupported-a-"+mode, "https://example.invalid")
delete(authA.Metadata, "project_id")
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("prep-unsupported-b-"+mode, "https://example.invalid")
authB.Status = cliproxyauth.StatusActive
reg := registry.GetGlobalRegistry()
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
ctx := cliproxyauth.WithSkipPersist(context.Background())
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
} else {
_, errRun = manager.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("%s error = nil, want 403 UNSUPPORTED_CLIENT stop", mode)
}
if loadCalls.Load() != 1 {
t.Fatalf("%s loadCodeAssist calls = %d, want 1", mode, loadCalls.Load())
}
if siblingCalls.Load() != 0 {
t.Fatalf("%s sibling Auth B calls = %d, want 0", mode, siblingCalls.Load())
}
snapA, _ := manager.GetByID(authA.ID)
if snapA.Disabled || snapA.Unavailable || snapA.Status != cliproxyauth.StatusActive || !snapA.NextRetryAfter.IsZero() {
t.Fatalf("healthy Auth A was cooled/disabled under continue-and-cooldown: status=%q disabled=%v unavailable=%v nextRetry=%v lastErr=%+v", snapA.Status, snapA.Disabled, snapA.Unavailable, snapA.NextRetryAfter, snapA.LastError)
}
if snapA.LastError != nil && snapA.LastError.Code == cliproxyauth.ErrorCodeForceCooldown {
t.Fatalf("healthy Auth A received ForceCooldown: %+v", snapA.LastError)
}
if ms := snapA.ModelStates[model]; ms != nil && (ms.Unavailable || !ms.NextRetryAfter.IsZero() || (ms.LastError != nil && ms.LastError.Code == cliproxyauth.ErrorCodeForceCooldown)) {
t.Fatalf("healthy Auth A model state was cooled: %+v", ms)
}
snapB, _ := manager.GetByID(authB.ID)
if snapB.Disabled || snapB.Unavailable || snapB.Status != cliproxyauth.StatusActive {
t.Fatalf("healthy sibling Auth B was unexpectedly mutated: %+v", snapB)
}
})
}
})
t.Run("401 AI_POLICY_REQUIRED stops without cooling Auth A and clears credentialScoped", func(t *testing.T) {
body401 := `[{"error":{"code":401,"status":"UNAUTHENTICATED","message":"AI policy required","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"AI_POLICY_REQUIRED"}]}}]`
sErr := newAntigravityStatusErrWithHeaders(http.StatusUnauthorized, nil, []byte(body401))
if sErr.IsCredentialScoped() {
t.Fatal("401 AI_POLICY_REQUIRED IsCredentialScoped() = true, want false")
}
if !sErr.IsRequestScoped() || !sErr.IsRequestStop() {
t.Fatalf("401 AI_POLICY_REQUIRED flags: requestScoped=%v requestStop=%v, want true/true", sErr.IsRequestScoped(), sErr.IsRequestStop())
}
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run(mode, func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
var upstreamHits atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
upstreamHits.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(body401))
}))
defer server.Close()
model := "gemini-4-argon-401-policy-" + mode
exec := &countingAntigravityExecutor{AntigravityExecutor: NewAntigravityExecutor(&config.Config{})}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newIssue7882Auth("policy-401-a-"+mode, server.URL)
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("policy-401-b-"+mode, server.URL)
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
} else {
_, errRun = manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("%s error = nil, want 401 AI_POLICY_REQUIRED stop", mode)
}
calls := exec.recordedCalls()
if len(calls) != 1 || upstreamHits.Load() != 1 {
t.Fatalf("%s calls=%v upstreamHits=%d, want 1", mode, calls, upstreamHits.Load())
}
snapA, _ := manager.GetByID(calls[0])
if snapA.Disabled || snapA.Unavailable || snapA.Status != cliproxyauth.StatusActive {
t.Fatalf("401 AI_POLICY_REQUIRED needlessly cooled/disabled auth %s: status=%q disabled=%v unavailable=%v", snapA.ID, snapA.Status, snapA.Disabled, snapA.Unavailable)
}
})
}
})
t.Run("400 INELIGIBLE_ACCOUNT and MONETIZATION_DENIED fail over cleanly to healthy sibling Auth B", func(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
successBody := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok-from-sibling-400"}]}}]}}`
successSSE := "data: " + successBody + "\n\n"
for _, reason := range []string{"INELIGIBLE_ACCOUNT", "MONETIZATION_DENIED"} {
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run(reason+"/"+mode, func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
body400 := fmt.Sprintf(`[{"error":{"code":400,"status":"FAILED_PRECONDITION","message":"blocked by %s","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q}]}}]`, reason, reason)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
if strings.Contains(r.Header.Get("Authorization"), "cred-400-a-") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(body400))
return
}
if stream {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(successSSE))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(successBody))
}))
defer server.Close()
model := fmt.Sprintf("gemini-4-argon-400-%s-%s", strings.ToLower(reason), mode)
exec := &countingAntigravityExecutor{AntigravityExecutor: NewAntigravityExecutor(&config.Config{})}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newIssue7882Auth("cred-400-a-"+reason+"-"+mode, server.URL)
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("cred-400-b-"+reason+"-"+mode, server.URL)
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var out string
if stream {
streamRes, errRun := manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
if errRun != nil {
t.Fatalf("ExecuteStream(400 %s) error = %v, want failover to Auth B", reason, errRun)
}
for ch := range streamRes.Chunks {
if ch.Err != nil {
t.Fatalf("ExecuteStream(400 %s) chunk error = %v", reason, ch.Err)
}
out += string(ch.Payload)
}
} else {
resp, errRun := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
if errRun != nil {
t.Fatalf("Execute(400 %s) error = %v, want failover to Auth B", reason, errRun)
}
out = string(resp.Payload)
}
if !strings.Contains(out, "ok-from-sibling-400") {
t.Fatalf("%s/%s payload = %q, want ok-from-sibling-400", reason, mode, out)
}
calls := exec.recordedCalls()
if len(calls) != 2 || calls[0] != authA.ID || calls[1] != authB.ID {
t.Fatalf("%s/%s calls = %v, want [%s %s]", reason, mode, calls, authA.ID, authB.ID)
}
})
}
}
})
t.Run("operator request-scoped-errors stop rules block executor TPU micro-retry", func(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
err503 := `{"error":{"code":503,"status":"UNAVAILABLE","message":"PREFILL_QUEUE_OVERLOADED"}}`
for _, action := range []string{cliproxyauth.RequestScopedActionStop, cliproxyauth.RequestScopedActionStopAndCooldown} {
for _, mode := range []string{"Execute", "executeClaudeNonStream", "ExecuteStream"} {
t.Run(action+"/"+mode, func(t *testing.T) {
sleeps := installFakeTPUSleeper(t, nil)
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
attempts.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(err503))
}))
defer server.Close()
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: action}},
},
}
exec := NewAntigravityExecutor(cfg)
auth := newIssue7882Auth("stop-blocks-tpu-"+action+"-"+mode, server.URL)
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: mode == "ExecuteStream",
}
var errRun error
switch mode {
case "Execute":
_, errRun = exec.Execute(context.Background(), auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
case "executeClaudeNonStream":
_, errRun = exec.executeClaudeNonStream(context.Background(), auth, cliproxyexecutor.Request{Model: "claude-sonnet-4-6", Payload: reqPayload}, opts)
case "ExecuteStream":
_, errRun = exec.ExecuteStream(context.Background(), auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("%s/%s error = nil, want 503 error", action, mode)
}
if attempts.Load() != 1 || len(*sleeps) != 0 {
t.Fatalf("%s/%s attempts=%d sleeps=%v, want 1 attempt and 0 sleeps (stop rule MUST block TPU micro-retry)", action, mode, attempts.Load(), *sleeps)
}
})
}
}
})
t.Run("partial 503 body matching stop rule with TPU read error stops without retry or conductor failover", func(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
partial503 := `{"error":{"code":503,"status":"UNAVAILABLE","message":"PREFILL_QUEUE_OVERLOADED"`
readErr := errors.New("incomplete envelope: unexpected EOF")
for _, action := range []string{cliproxyauth.RequestScopedActionStop, cliproxyauth.RequestScopedActionStopAndCooldown} {
for _, mode := range []string{"Execute", "executeClaudeNonStream", "ExecuteStream", "ExecuteStreamReconnect"} {
t.Run("executor/"+action+"/"+mode, func(t *testing.T) {
sleeps := installFakeTPUSleeper(t, nil)
var attempts atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
_, _ = io.ReadAll(r.Body)
n := attempts.Add(1)
if mode == "ExecuteStreamReconnect" && n == 1 {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(`data: [{"error":{"code":14,"status":"UNAVAILABLE","message":"DECODE_PREEMPTED"}}]` + "\n\n")),
}, nil
}
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &failingBodyReadCloser{
prefix: []byte(partial503),
err: readErr,
},
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: action}},
},
}
exec := NewAntigravityExecutor(cfg)
auth := newIssue7882Auth("partial-read-stop-"+action+"-"+mode, "https://example.invalid")
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", rt)
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: mode == "ExecuteStream" || mode == "ExecuteStreamReconnect",
}
var gotErr error
switch mode {
case "Execute":
_, gotErr = exec.Execute(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
case "executeClaudeNonStream":
_, gotErr = exec.executeClaudeNonStream(ctx, auth, cliproxyexecutor.Request{Model: "claude-sonnet-4-6", Payload: reqPayload}, opts)
case "ExecuteStream":
_, gotErr = exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
case "ExecuteStreamReconnect":
streamRes, errStart := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
if errStart != nil {
gotErr = errStart
} else {
for ch := range streamRes.Chunks {
if ch.Err != nil {
gotErr = ch.Err
}
}
}
}
var sErr statusErr
if !errors.As(gotErr, &sErr) || sErr.StatusCode() != http.StatusServiceUnavailable {
t.Fatalf("%s/%s err = %#v, want preserved 503 statusErr", action, mode, gotErr)
}
if !cliproxyauth.IsRequestStopError(gotErr) {
t.Fatalf("%s/%s IsRequestStopError() = false, want true", action, mode)
}
if !strings.Contains(gotErr.Error(), "PREFILL_QUEUE_OVERLOADED") {
t.Fatalf("%s/%s err = %q, want partial 503 body preserved", action, mode, gotErr.Error())
}
wantAttempts := int32(1)
wantSleeps := 0
if mode == "ExecuteStreamReconnect" {
wantAttempts = 2
wantSleeps = 1
}
if attempts.Load() != wantAttempts || len(*sleeps) != wantSleeps {
t.Fatalf("%s/%s attempts=%d sleeps=%v, want %d attempts and %d sleeps", action, mode, attempts.Load(), *sleeps, wantAttempts, wantSleeps)
}
})
}
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run("conductor/"+action+"/"+mode, func(t *testing.T) {
sleeps := installFakeTPUSleeper(t, nil)
var hits atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
_, _ = io.ReadAll(r.Body)
hits.Add(1)
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &failingBodyReadCloser{
prefix: []byte(partial503),
err: readErr,
},
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: action}},
},
}
exec := &countingAntigravityExecutor{AntigravityExecutor: NewAntigravityExecutor(cfg)}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetConfig(cfg)
manager.SetRoundTripperProvider(issue7751StaticRTProvider{rt: rt})
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
model := "gemini-4-argon-partial-stop-" + action + "-" + mode
authA := newIssue7882Auth("partial-stop-a-"+action+"-"+mode, "https://example.invalid")
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("partial-stop-b-"+action+"-"+mode, "https://example.invalid")
authB.Status = cliproxyauth.StatusActive
reg := registry.GetGlobalRegistry()
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
} else {
_, errRun = manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("conductor %s/%s error = nil, want 503 stop error", action, mode)
}
if calls := exec.recordedCalls(); len(calls) != 1 || calls[0] != authA.ID || hits.Load() != 1 || len(*sleeps) != 0 {
t.Fatalf("conductor %s/%s calls=%v hits=%d sleeps=%v, want [%s], 1 hit, 0 sleeps", action, mode, calls, hits.Load(), *sleeps, authA.ID)
}
snapA, _ := manager.GetByID(authA.ID)
if action == cliproxyauth.RequestScopedActionStop {
if snapA.Unavailable || !snapA.NextRetryAfter.IsZero() {
t.Fatalf("stop rule unexpectedly cooled Auth A: unavailable=%v nextRetry=%v", snapA.Unavailable, snapA.NextRetryAfter)
}
} else {
ms := snapA.ModelStates[model]
if ms == nil || !ms.Unavailable || ms.LastError == nil || ms.LastError.Code != cliproxyauth.ErrorCodeForceCooldown {
t.Fatalf("stop-and-cooldown rule did not force-cool Auth A model state: %+v", ms)
}
}
})
}
}
})
t.Run("active ctx with partial 503 body and read timeout stops without retry or failover to Auth B", func(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
partial503 := `{"error":{"code":503,"status":"UNAVAILABLE","message":"PREFILL_QUEUE_OVERLOADED"`
readErrors := []struct {
name string
err error
}{
{name: "deadline_exceeded", err: context.DeadlineExceeded},
{name: "upstream_canceled", err: context.Canceled},
}
for _, re := range readErrors {
for _, mode := range []string{"Execute", "executeClaudeNonStream", "ExecuteStream", "ExecuteStreamReconnect"} {
t.Run(re.name+"/"+mode, func(t *testing.T) {
sleeps := installFakeTPUSleeper(t, nil)
var attempts atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
_, _ = io.ReadAll(r.Body)
n := attempts.Add(1)
if mode == "ExecuteStreamReconnect" && n == 1 {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(strings.NewReader(`data: [{"error":{"code":14,"status":"UNAVAILABLE","message":"DECODE_PREEMPTED"}}]` + "\n\n")),
}, nil
}
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &failingBodyReadCloser{
prefix: []byte(partial503),
err: re.err,
},
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: cliproxyauth.RequestScopedActionStop}},
},
}
exec := NewAntigravityExecutor(cfg)
auth := newIssue7882Auth("partial-timeout-stop-"+re.name+"-"+mode, "https://example.invalid")
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", rt)
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: mode == "ExecuteStream" || mode == "ExecuteStreamReconnect",
}
var gotErr error
switch mode {
case "Execute":
_, gotErr = exec.Execute(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
case "executeClaudeNonStream":
_, gotErr = exec.executeClaudeNonStream(ctx, auth, cliproxyexecutor.Request{Model: "claude-sonnet-4-6", Payload: reqPayload}, opts)
case "ExecuteStream":
_, gotErr = exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
case "ExecuteStreamReconnect":
streamRes, errStart := exec.ExecuteStream(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
if errStart != nil {
gotErr = errStart
} else {
for ch := range streamRes.Chunks {
if ch.Err != nil {
gotErr = ch.Err
}
}
}
}
var sErr statusErr
if !errors.As(gotErr, &sErr) || sErr.StatusCode() != http.StatusServiceUnavailable {
t.Fatalf("%s/%s err = %#v, want preserved 503 statusErr", re.name, mode, gotErr)
}
if !cliproxyauth.IsRequestStopError(gotErr) {
t.Fatalf("%s/%s IsRequestStopError() = false, want true", re.name, mode)
}
if !strings.Contains(gotErr.Error(), "PREFILL_QUEUE_OVERLOADED") {
t.Fatalf("%s/%s err = %q, want partial 503 body preserved", re.name, mode, gotErr.Error())
}
wantAttempts := int32(1)
wantSleeps := 0
if mode == "ExecuteStreamReconnect" {
wantAttempts = 2
wantSleeps = 1
}
if attempts.Load() != wantAttempts || len(*sleeps) != wantSleeps {
t.Fatalf("%s/%s attempts=%d sleeps=%v, want %d attempts and %d sleeps", re.name, mode, attempts.Load(), *sleeps, wantAttempts, wantSleeps)
}
})
}
for _, stream := range []bool{false, true} {
mode := "execute"
if stream {
mode = "stream"
}
t.Run("conductor/"+re.name+"/"+mode, func(t *testing.T) {
sleeps := installFakeTPUSleeper(t, nil)
var hits atomic.Int32
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
_, _ = io.ReadAll(r.Body)
hits.Add(1)
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &failingBodyReadCloser{
prefix: []byte(partial503),
err: re.err,
},
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: cliproxyauth.RequestScopedActionStop}},
},
}
exec := &countingAntigravityExecutor{AntigravityExecutor: NewAntigravityExecutor(cfg)}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetConfig(cfg)
manager.SetRoundTripperProvider(issue7751StaticRTProvider{rt: rt})
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
model := "gemini-4-argon-partial-timeout-" + re.name + "-" + mode
authA := newIssue7882Auth("partial-timeout-a-"+re.name+"-"+mode, "https://example.invalid")
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("partial-timeout-b-"+re.name+"-"+mode, "https://example.invalid")
authB.Status = cliproxyauth.StatusActive
reg := registry.GetGlobalRegistry()
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
Stream: stream,
}
var errRun error
if stream {
_, errRun = manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
} else {
_, errRun = manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model, Payload: reqPayload}, opts)
}
if errRun == nil {
t.Fatalf("conductor %s/%s error = nil, want 503 stop error", re.name, mode)
}
if calls := exec.recordedCalls(); len(calls) != 1 || calls[0] != authA.ID || hits.Load() != 1 || len(*sleeps) != 0 {
t.Fatalf("conductor %s/%s calls=%v hits=%d sleeps=%v, want [%s] (Auth B 0 calls), 1 hit, 0 sleeps", re.name, mode, calls, hits.Load(), *sleeps, authA.ID)
}
})
}
}
// Verify that true caller cancellation (ctx.Err() != nil) still skips partial-body stop matching.
t.Run("caller_ctx_canceled_skips_partial_stop_rule", func(t *testing.T) {
parentCtx, cancel := context.WithCancel(context.Background())
defer cancel()
rt := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
_, _ = io.ReadAll(r.Body)
cancel()
return &http.Response{
StatusCode: http.StatusServiceUnavailable,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &failingBodyReadCloser{
prefix: []byte(partial503),
err: context.Canceled,
},
}, nil
})
cfg := &config.Config{
OAuthRequestScopedErrors: map[string][]config.RequestScopedErrorRule{
"antigravity": {{Status: http.StatusServiceUnavailable, Match: []string{"PREFILL_QUEUE_OVERLOADED"}, Action: cliproxyauth.RequestScopedActionStopAndCooldown}},
},
}
exec := NewAntigravityExecutor(cfg)
auth := newIssue7882Auth("partial-caller-canceled", "https://example.invalid")
t.Cleanup(func() { closeAntigravityAuthIdleTransports(auth) })
ctx := context.WithValue(parentCtx, "cliproxy.roundtripper", rt)
opts := cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
}
_, errExec := exec.Execute(ctx, auth, cliproxyexecutor.Request{Model: "gemini-4-argon", Payload: reqPayload}, opts)
if !errors.Is(errExec, context.Canceled) {
t.Fatalf("Execute() err = %#v, want context.Canceled", errExec)
}
if cliproxyauth.IsRequestStopError(errExec) {
t.Fatalf("caller-canceled Execute() unexpectedly returned requestStop error: %#v", errExec)
}
})
})
}
func TestAntigravityHub2360HardBilling402AndDiagnostics(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
t.Run("all 7 hard-billing codes and 4 hard-quota substrings + 12 Gemini markers classify as FullQuotaExhausted and never retry", func(t *testing.T) {
hardBillingReasons := []string{
"MONETIZATION_DENIED",
"USER_SPEND_CAP_EXCEEDED",
"PREPAID_BALANCE_EXHAUSTED",
"PROJECT_SPEND_CAP_EXHAUSTED",
"INSUFFICIENT_G1_CREDITS_BALANCE",
"BILLING_ACCOUNT_SPEND_LIMIT_EXHAUSTED",
"GEMINI_ENTERPRISE_USER_QUOTA_EXHAUSTED",
}
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("hard-billing-check", "https://example.invalid")
for _, reason := range hardBillingReasons {
for _, wrapped := range []bool{false, true} {
raw := fmt.Sprintf(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"PREFILL_QUEUE_OVERLOADED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":%q},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"0.5s"}]}}`, reason)
if wrapped {
raw = "[" + raw + "]"
}
decision := decideAntigravity429WithHeaders([]byte(raw), nil)
if decision.kind != antigravity429DecisionFullQuotaExhausted {
t.Fatalf("reason=%s wrapped=%v: kind = %q, want %q", reason, wrapped, decision.kind, antigravity429DecisionFullQuotaExhausted)
}
if retryable, _ := exec.shouldAntigravitySameAuthMicroRetry(context.Background(), auth, http.StatusTooManyRequests, nil, []byte(raw)); retryable {
t.Fatalf("shouldAntigravitySameAuthMicroRetry(%s wrapped=%v) = true, want false", reason, wrapped)
}
}
}
hardQuotaMsgs := []string{
"Limit exceeded per day",
"Your daily quota has been reached",
"Please update your billing account",
"Individual quota reached",
"Exceeded generate_content_tokens_per_model_per_user",
"Upgrade at https://one.google.com/ai",
"See https://aistudio.google.com/docs/billing#project-spend-caps",
"See https://aistudio.google.com/docs/billing#tier-spend-caps",
"See https://aistudio.google.com/docs/billing#prepay",
"See https://ai.google.dev/gemini-api/docs/billing#project-spend-caps",
"See https://ai.google.dev/gemini-api/docs/billing#tier-spend-caps",
"See https://ai.google.dev/gemini-api/docs/billing#prepay",
"Visit https://ai.studio/spend",
"Visit https://ai.studio/billing",
"Visit https://ai.studio/projects",
}
for _, msg := range hardQuotaMsgs {
raw := fmt.Sprintf(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":%q,"details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED"},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"0.5s"}]}}`, msg)
decision := decideAntigravity429WithHeaders([]byte(raw), nil)
if decision.kind != antigravity429DecisionFullQuotaExhausted {
t.Fatalf("msg=%q: kind = %q, want %q", msg, decision.kind, antigravity429DecisionFullQuotaExhausted)
}
if retryable, _ := exec.shouldAntigravitySameAuthMicroRetry(context.Background(), auth, http.StatusTooManyRequests, nil, []byte(raw)); retryable {
t.Fatalf("shouldAntigravitySameAuthMicroRetry(msg=%q) = true, want false", msg)
}
}
})
t.Run("PREPAID_BALANCE_EXHAUSTED permanently disables credits just like INSUFFICIENT_G1_CREDITS_BALANCE", func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
body := []byte(`[{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"Prepaid wallet empty","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"PREPAID_BALANCE_EXHAUSTED"}]}}]`)
if !antigravityHasExplicitCreditsBalanceExhaustedReason(body) {
t.Fatal("antigravityHasExplicitCreditsBalanceExhaustedReason(PREPAID_BALANCE_EXHAUSTED) = false, want true")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write(body)
}))
defer server.Close()
cfg := newIssue7882PooledConfig("", true)
exec := NewAntigravityExecutor(cfg)
auth := newIssue7882Auth("prepaid-exhausted-credits", server.URL)
t.Cleanup(func() {
closeAntigravityAuthIdleTransports(auth)
cliproxyauth.SetAntigravityCreditsHintForAuth(auth, cliproxyauth.AntigravityCreditsHint{})
})
_, errExec := exec.Execute(cliproxyauth.WithAntigravityCredits(context.Background()), auth, cliproxyexecutor.Request{
Model: "gemini-4-argon",
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
var sErr statusErr
if !errors.As(errExec, &sErr) || sErr.StatusCode() != http.StatusTooManyRequests || !sErr.IsCredentialScoped() {
t.Fatalf("Execute(PREPAID_BALANCE_EXHAUSTED) err = %#v, want 429 credentialScoped=true", errExec)
}
if _, loaded := antigravityCreditsFailureByAuth.Load(antigravityCreditsTestCacheKey(auth)); !loaded {
t.Fatal("expected PREPAID_BALANCE_EXHAUSTED under credits mode to permanently disable credits")
}
})
t.Run("HTTP 402 Payment Required is non-retryable, credentialScoped, disables credits, and fails over to Auth B", func(t *testing.T) {
resetAntigravityCreditsRetryState()
t.Cleanup(resetAntigravityCreditsRetryState)
sleeps := installFakeTPUSleeper(t, nil)
body402 := `{"error":{"code":402,"status":"FAILED_PRECONDITION","message":"PREFILL_QUEUE_OVERLOADED payment required"}}`
var attemptsA atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/v1internal:loadCodeAssist" {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
return
}
if strings.Contains(r.Header.Get("Authorization"), "pay402-a") {
attemptsA.Add(1)
w.WriteHeader(http.StatusPaymentRequired)
_, _ = w.Write([]byte(body402))
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok-after-402"}]},"finishReason":"STOP"}]}}`))
}))
defer server.Close()
// Direct executor check: 1 attempt, 0 sleeps, credentialScoped=true, requestStop=false, credits disabled.
cfg := newIssue7882PooledConfig("", true)
exec := NewAntigravityExecutor(cfg)
authDirect := newIssue7882Auth("pay402-a-direct", server.URL)
t.Cleanup(func() {
closeAntigravityAuthIdleTransports(authDirect)
cliproxyauth.SetAntigravityCreditsHintForAuth(authDirect, cliproxyauth.AntigravityCreditsHint{})
})
_, errDirect := exec.Execute(cliproxyauth.WithAntigravityCredits(context.Background()), authDirect, cliproxyexecutor.Request{
Model: "gemini-4-argon",
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
var sErr statusErr
if !errors.As(errDirect, &sErr) || sErr.StatusCode() != http.StatusPaymentRequired || !sErr.IsCredentialScoped() || sErr.IsRequestStop() {
t.Fatalf("Execute(402) err = %#v, want 402 credentialScoped=true requestStop=false", errDirect)
}
if attemptsA.Load() != 1 || len(*sleeps) != 0 {
t.Fatalf("Execute(402) attempts=%d sleeps=%v, want 1 attempt and 0 sleeps", attemptsA.Load(), *sleeps)
}
if _, loaded := antigravityCreditsFailureByAuth.Load(antigravityCreditsTestCacheKey(authDirect)); !loaded {
t.Fatal("expected HTTP 402 under credits mode to permanently disable credits")
}
// Conductor check: Auth A 402 fails over to healthy sibling Auth B.
model := "gemini-4-argon-402-failover"
countingExec := &countingAntigravityExecutor{AntigravityExecutor: NewAntigravityExecutor(&config.Config{})}
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(countingExec)
reg := registry.GetGlobalRegistry()
authA := newIssue7882Auth("pay402-a-mgr", server.URL)
authA.Status = cliproxyauth.StatusActive
authB := newIssue7882Auth("pay402-b-mgr", server.URL)
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
resp, errMgr := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
if errMgr != nil || !strings.Contains(string(resp.Payload), "ok-after-402") {
t.Fatalf("Manager.Execute(402 failover) = (%q, %v), want ok-after-402", string(resp.Payload), errMgr)
}
calls := countingExec.recordedCalls()
if len(calls) != 2 || calls[0] != authA.ID || calls[1] != authB.ID {
t.Fatalf("Manager.Execute(402 failover) calls = %v, want [%s %s]", calls, authA.ID, authB.ID)
}
})
t.Run("LOCATION_NOT_ELIGIBLE is never TOS or credential-terminal and 401 ACCESS_TOKEN_EXPIRED still refreshes once", func(t *testing.T) {
locBody := []byte(`[{"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"LOCATION_NOT_ELIGIBLE","metadata":{"detected_location":"CN"}}]}}]`)
sErr := newAntigravityStatusErrWithHeaders(http.StatusForbidden, nil, locBody)
if sErr.IsTerminalTOSViolation() || sErr.IsCredentialScoped() || sErr.IsRequestStop() {
t.Fatalf("LOCATION_NOT_ELIGIBLE statusErr = (tos=%v cred=%v stop=%v), want all false", sErr.IsTerminalTOSViolation(), sErr.IsCredentialScoped(), sErr.IsRequestStop())
}
// 401 ACCESS_TOKEN_EXPIRED must still be eligible for Task 1's 1x OAuth refresh retry.
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("auth-expired-401", "https://example.invalid")
expiredBody := []byte(`{"error":{"code":401,"status":"UNAUTHENTICATED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_EXPIRED"}]}}`)
if !exec.shouldAttemptAntigravity401RefreshRetry(context.Background(), auth, "application/json", expiredBody, false) {
t.Fatal("shouldAttemptAntigravity401RefreshRetry(ACCESS_TOKEN_EXPIRED) = false, want true")
}
// Non-refreshable credential-terminal codes like API_KEY_INVALID must NOT trigger OAuth refresh.
invalidKeyBody := []byte(`{"error":{"code":401,"status":"UNAUTHENTICATED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID"}]}}`)
if exec.shouldAttemptAntigravity401RefreshRetry(context.Background(), auth, "application/json", invalidKeyBody, false) {
t.Fatal("shouldAttemptAntigravity401RefreshRetry(API_KEY_INVALID) = true, want false")
}
})
t.Run("applyAntigravityUpstreamError logs Sherlog, Trace-Id, and AI_POLICY_REQUIRED pa_id as structured logrus fields without secrets", func(t *testing.T) {
hook := &safetySignalLogHook{}
log.AddHook(hook)
t.Cleanup(func() {
hooks := log.StandardLogger().Hooks
for _, level := range hook.Levels() {
filtered := hooks[level][:0]
for _, existing := range hooks[level] {
if existing != hook {
filtered = append(filtered, existing)
}
}
hooks[level] = filtered
}
})
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("diag-auth-1", "https://example.invalid")
auth.Metadata["access_token"] = "secret-bearer-token-never-log"
headers := http.Header{
"X-Goog-Sherlog-Link": []string{"https://sherlog.corp.google.com/trace-abc"},
"X-Cloudaicompanion-Trace-Id": []string{"0xdeadbeef1234"},
}
body := []byte(`[{"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"AI_POLICY_REQUIRED","metadata":{"pa_id":"pa-2360-block"}}]}}]`)
_ = exec.applyAntigravityUpstreamError(context.Background(), auth, "gemini-4-argon", false, antigravityReasoningReplayScope{}, http.StatusForbidden, headers, body)
hook.mu.Lock()
entries := append([]*log.Entry(nil), hook.entries...)
hook.mu.Unlock()
var matched *log.Entry
for _, entry := range entries {
if entry.Data["pa_id"] == "pa-2360-block" {
matched = entry
break
}
}
if matched == nil {
t.Fatalf("missing structured diagnostic Warn log with pa_id; entries=%d", len(entries))
}
if matched.Data["sherlog_link"] != "https://sherlog.corp.google.com/trace-abc" {
t.Fatalf("sherlog_link = %v, want https://sherlog.corp.google.com/trace-abc", matched.Data["sherlog_link"])
}
if matched.Data["trace_id"] != "0xdeadbeef1234" {
t.Fatalf("trace_id = %v, want 0xdeadbeef1234", matched.Data["trace_id"])
}
for k, v := range matched.Data {
if strings.Contains(fmt.Sprint(v), "secret-bearer-token-never-log") {
t.Fatalf("secret token leaked in log field %q", k)
}
}
})
}
func TestAntigravityHub2360ReviewRemediationPolicy401AndParity(t *testing.T) {
reqPayload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`)
t.Run("Finding 1: canonical PROJECT_SPEND_CAP_EXCEEDED and BILLING_ACCOUNT_SPEND_LIMIT_EXCEEDED classify as FullQuotaExhausted and never retry", func(t *testing.T) {
exec := NewAntigravityExecutor(&config.Config{})
auth := newIssue7882Auth("spendcap-canonical", "https://example.invalid")
for _, reason := range []string{"PROJECT_SPEND_CAP_EXCEEDED", "BILLING_ACCOUNT_SPEND_LIMIT_EXCEEDED"} {
body := []byte(`{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"PREFILL_QUEUE_OVERLOADED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"` + reason + `"}]}}`)
dec := decideAntigravity429WithHeaders(body, nil)
if dec.kind != antigravity429DecisionFullQuotaExhausted {
t.Fatalf("decideAntigravity429WithHeaders(%s).kind = %q, want %q", reason, dec.kind, antigravity429DecisionFullQuotaExhausted)
}
if retryable, _ := exec.shouldAntigravitySameAuthMicroRetry(context.Background(), auth, http.StatusTooManyRequests, nil, body); retryable {
t.Fatalf("shouldAntigravitySameAuthMicroRetry(%s) = true, want false", reason)
}
}
})
t.Run("Finding 4: real Manager.Execute skips OAuth refresh on 401 API_KEY_INVALID and BILLING_DISABLED and immediately fails over to Auth B", func(t *testing.T) {
for _, denialReason := range []string{"API_KEY_INVALID", "BILLING_DISABLED"} {
t.Run(denialReason, func(t *testing.T) {
var oauthCalls atomic.Int32
var attemptsA atomic.Int32
var attemptsB atomic.Int32
rt := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.String() == "https://oauth2.googleapis.com/token" {
oauthCalls.Add(1)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"access_token":"should-not-mint","expires_in":3600}`)),
}, nil
}
if strings.Contains(req.Header.Get("Authorization"), "token-deny-a") {
attemptsA.Add(1)
body := `{"error":{"code":401,"status":"UNAUTHENTICATED","message":"denied","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"` + denialReason + `"}]}}`
return &http.Response{
StatusCode: http.StatusUnauthorized,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
}, nil
}
attemptsB.Add(1)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok-from-b"}]},"finishReason":"STOP"}]}}`)),
}, nil
})
model := "gemini-4-argon-401-deny-" + strings.ToLower(denialReason)
exec := NewAntigravityExecutor(&config.Config{})
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newAntigravity401TestAuth("deny-a-"+denialReason, "https://ag-401-deny.test", "token-deny-a", "rt-deny-a")
authA.Status = cliproxyauth.StatusActive
authB := newAntigravity401TestAuth("deny-b-"+denialReason, "https://ag-401-deny.test", "token-deny-b", "rt-deny-b")
authB.Status = cliproxyauth.StatusActive
for _, a := range []*cliproxyauth.Auth{authA, authB} {
reg.RegisterClient(a.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
id := a.ID
authRef := a
t.Cleanup(func() {
reg.UnregisterClient(id)
closeAntigravityAuthIdleTransports(authRef)
})
if _, errReg := manager.Register(context.Background(), a); errReg != nil {
t.Fatalf("Register(%s) error = %v", a.ID, errReg)
}
}
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(rt))
resp, errMgr := manager.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
if errMgr != nil || !strings.Contains(string(resp.Payload), "ok-from-b") {
t.Fatalf("Manager.Execute(%s) = (%q, %v), want failover success on Auth B", denialReason, string(resp.Payload), errMgr)
}
if oauthCalls.Load() != 0 {
t.Fatalf("%s oauthCalls = %d, want 0 (non-refreshable 401 must not trigger Manager OAuth refresh)", denialReason, oauthCalls.Load())
}
if attemptsA.Load() != 1 {
t.Fatalf("%s attemptsA = %d, want 1 (must not retry rejected Auth A)", denialReason, attemptsA.Load())
}
if attemptsB.Load() != 1 {
t.Fatalf("%s attemptsB = %d, want 1", denialReason, attemptsB.Load())
}
})
}
// Contrast: 401 ACCESS_TOKEN_EXPIRED still performs its 1 executor refresh retry on Account A.
t.Run("ACCESS_TOKEN_EXPIRED_still_refreshes_once", func(t *testing.T) {
var oauthCalls atomic.Int32
var attemptsA atomic.Int32
rt := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if req.URL.String() == "https://oauth2.googleapis.com/token" {
oauthCalls.Add(1)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"access_token":"fresh-expired-token","expires_in":3600}`)),
}, nil
}
attemptsA.Add(1)
if req.Header.Get("Authorization") == "Bearer stale-expired-token" {
return &http.Response{
StatusCode: http.StatusUnauthorized,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"code":401,"status":"UNAUTHENTICATED","message":"expired","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_EXPIRED"}]}}`)),
}, nil
}
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"recovered-after-expired-refresh"}]},"finishReason":"STOP"}]}}`)),
}, nil
})
model := "gemini-4-argon-401-expired-ok"
exec := NewAntigravityExecutor(&config.Config{})
manager := cliproxyauth.NewManager(nil, &cliproxyauth.FillFirstSelector{}, nil)
manager.SetRetryConfig(2, 0, 0)
manager.RegisterExecutor(exec)
reg := registry.GetGlobalRegistry()
authA := newAntigravity401TestAuth("expired-a", "https://ag-401-exp.test", "stale-expired-token", "rt-expired-a")
authA.Status = cliproxyauth.StatusActive
reg.RegisterClient(authA.ID, "antigravity", []*registry.ModelInfo{{ID: model}})
t.Cleanup(func() {
reg.UnregisterClient(authA.ID)
closeAntigravityAuthIdleTransports(authA)
})
if _, errReg := manager.Register(context.Background(), authA); errReg != nil {
t.Fatalf("Register error = %v", errReg)
}
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(rt))
resp, errMgr := manager.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{
Model: model,
Payload: reqPayload,
}, cliproxyexecutor.Options{
SourceFormat: sdktranslator.FormatAntigravity,
ResponseFormat: sdktranslator.FormatAntigravity,
})
if errMgr != nil || !strings.Contains(string(resp.Payload), "recovered-after-expired-refresh") {
t.Fatalf("Manager.Execute(ACCESS_TOKEN_EXPIRED) = (%q, %v), want refresh recovery", string(resp.Payload), errMgr)
}
if oauthCalls.Load() != 1 || attemptsA.Load() != 2 {
t.Fatalf("oauthCalls=%d attemptsA=%d, want 1 refresh and 2 attempts", oauthCalls.Load(), attemptsA.Load())
}
})
})
t.Run("Finding 7: executor hard-quota classification parity table", func(t *testing.T) {
cases := []struct {
name string
body string
wantHard bool
}{
{
name: "plain text requests per day",
body: "Quota exceeded: 100 requests per day",
wantHard: true,
},
{
name: "LocalizedMessage hard quota",
body: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"Resource exhausted","details":[{"@type":"type.googleapis.com/google.rpc.LocalizedMessage","locale":"en-US","message":"Individual quota reached"}]}}`,
wantHard: true,
},
{
name: "ErrorInfo metadata quota_metric",
body: `{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","message":"Resource exhausted","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"RATE_LIMIT_EXCEEDED","metadata":{"quota_metric":"generativelanguage.googleapis.com/generate_content_tokens_per_model_per_user"}}]}}`,
wantHard: true,
},
{
name: "short-term requests per minute",
body: "Quota exceeded: 100 requests per minute",
wantHard: false,
},
{
name: "daily hostname in plain text",
body: "HTTP 502 from daily-cloudcode-pa.googleapis.com",
wantHard: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := helps.IsAntigravityHardQuotaExhaustedMessage([]byte(tc.body))
if got != tc.wantHard {
t.Fatalf("IsAntigravityHardQuotaExhaustedMessage(%q) = %v, want %v", tc.body, got, tc.wantHard)
}
})
}
})
}
func TestAntigravityPolicyErrorPrefersRequestDenialAcrossDetails(t *testing.T) {
const credential = `{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCOUNT_SUSPENDED"}`
const request = `{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"AI_POLICY_REQUIRED"}`
const tos = `{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"TOS_VIOLATION"}`
for _, tc := range []struct{ details, reason string }{
{credential + "," + request, "AI_POLICY_REQUIRED"},
{request + "," + credential, "AI_POLICY_REQUIRED"},
{credential + "," + request + "," + tos, "TOS_VIOLATION"},
} {
body := []byte(`{"error":{"code":403,"details":[` + tc.details + `]}}`)
reason, credentialTerminal, requestTerminal := helps.ParseAntigravityPolicyError(body)
if reason != tc.reason || !credentialTerminal || !requestTerminal {
t.Errorf("ParseAntigravityPolicyError = (%q, %t, %t), want (%q, true, true)", reason, credentialTerminal, requestTerminal, tc.reason)
}
}
}