Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions backend/internal/handler/openai_409_http_rebuild_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,18 @@ func TestOpenAI409HTTPTaskRebuild(t *testing.T) {
}
}

func TestOpenAI409HTTPRebuildOwnerCooldown(t *testing.T) {
for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} {
for _, stream := range []bool{false, true} {
for _, cooldown := range []string{"rate_limited", "overloaded"} {
t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, cooldown), func(t *testing.T) {
runHTTPRebuildFixture(t, accountType, stream, "intent", "completed", cooldown, "")
})
}
}
}
}

func TestOpenAI409HTTPControlNormalization(t *testing.T) {
for _, stream := range []bool{false, true} {
for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} {
Expand Down Expand Up @@ -456,6 +468,7 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
noOpaque := strings.HasSuffix(pointer, "_no_opaque")
pointer = strings.TrimSuffix(pointer, "_no_opaque")
mixed := strings.HasPrefix(boundary, "mixed/")
ownerCooldown := boundary == "rate_limited" || boundary == "overloaded"
clients := issue805Redis(t)
observer := clients()
patchCall := httpRebuildCall("apply_patch", "call_patch_once", map[string]any{"path": "sum.go", "source": httpRebuildSource})
Expand Down Expand Up @@ -660,9 +673,18 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
require.Len(t, ownersA, 1)
}
accounts[0].Schedulable = false
cooldownUntil := time.Now().Add(7 * 24 * time.Hour)
if ownerCooldown {
accounts[0].Schedulable = true
if boundary == "rate_limited" {
accounts[0].RateLimitResetAt = &cooldownUntil
} else {
accounts[0].OverloadUntil = &cooldownUntil
}
}
disabled, err := (openAIImagesFailoverAccountRepo{accounts: accounts}).GetByID(context.Background(), 1)
require.NoError(t, err)
require.False(t, disabled.Schedulable)
require.False(t, disabled.IsSchedulable())
switch boundary {
case "pointer_only":
history = nil
Expand All @@ -681,7 +703,7 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
accounts[1].Schedulable = false
}
status, answer = request(history, first)
if boundary != "" && !mixed {
if boundary != "" && !mixed && !ownerCooldown {
if boundary == "strict" {
require.Len(t, transport.snapshot(), 1, "HTTP_POINTER_STRICT_A_STATE_LEAK: disabled A pointer must never reach B under default strict policy; response=%s", answer)
}
Expand Down Expand Up @@ -808,7 +830,13 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
require.Equal(t, 1, tools.patches)
require.Equal(t, 1, tools.verifications)
require.Equal(t, []string{httpRebuildSession, httpRebuildSession, httpRebuildSession}, sessions)
require.False(t, accounts[0].Schedulable)
require.Equal(t, ownerCooldown, accounts[0].Schedulable, "continuation must not change the owner's scheduling flag")
if boundary == "rate_limited" {
require.Equal(t, cooldownUntil, *accounts[0].RateLimitResetAt)
}
if boundary == "overloaded" {
require.Equal(t, cooldownUntil, *accounts[0].OverloadUntil)
}
wires = transport.snapshot()
require.Len(t, wires, 3, "one A generation and exactly two B generations")
require.Equal(t, int64(2), wires[2].account)
Expand Down
47 changes: 41 additions & 6 deletions backend/internal/handler/openai_409_omit_history_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strings"
"sync"
"testing"
"time"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/repository"
Expand Down Expand Up @@ -39,11 +40,14 @@ func (s *omit409SettingsRepo) GetMultiple(_ context.Context, _ []string) (map[st

func TestOpenAI409OmitHistoryHTTP(t *testing.T) {
for _, stream := range []bool{false, true} {
for _, scenario := range []string{"off", "paused", "route_changed", "no_accounts", "current_task", "upstream_rejects"} {
for _, scenario := range []string{"off", "paused", "route_changed", "no_accounts", "current_task", "upstream_rejects",
"rate_limited", "rate_limited_off", "rate_limited_no_accounts", "rate_limited_current_task",
"overloaded", "overloaded_off", "overloaded_no_accounts", "overloaded_current_task"} {
t.Run(fmt.Sprintf("%s/stream=%t", scenario, stream), func(t *testing.T) {
clients := issue805Redis(t)
var mu sync.Mutex
var bodies [][]byte
var authorizations []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
Expand All @@ -52,6 +56,7 @@ func TestOpenAI409OmitHistoryHTTP(t *testing.T) {
}
mu.Lock()
bodies = append(bodies, body)
authorizations = append(authorizations, r.Header.Get("Authorization"))
n := len(bodies)
mu.Unlock()
if n > 1 && scenario == "upstream_rejects" {
Expand Down Expand Up @@ -92,33 +97,57 @@ func TestOpenAI409OmitHistoryHTTP(t *testing.T) {
originalOwners := issue805Owners(t, clients())
require.Len(t, originalOwners, 1)
accounts[0].Schedulable = false
cooldown := time.Now().Add(7 * 24 * time.Hour)
rateLimited := strings.HasPrefix(scenario, "rate_limited")
overloaded := strings.HasPrefix(scenario, "overloaded")
if rateLimited || overloaded {
accounts[0].Schedulable = true
if rateLimited {
accounts[0].RateLimitResetAt = &cooldown
} else {
accounts[0].OverloadUntil = &cooldown
}
}
if scenario == "route_changed" {
accounts[0].Schedulable = true
accounts[0].Credentials["api_key"] = "fixture-rotated"
}
if scenario == "no_accounts" {
if strings.HasSuffix(scenario, "no_accounts") {
accounts[1].Schedulable = false
}
followup := issue715Body(true, stream)
if scenario == "current_task" {
if strings.HasSuffix(scenario, "current_task") {
followup = fmt.Sprintf(`{"model":"gpt-5.1","stream":%t,"input":[%s]}`, stream, issue715Agent)
}
answer := issue758Request(t, newNode(scenario != "off"), followup)
answer := issue758Request(t, newNode(!strings.HasSuffix(scenario, "off")), followup)
mu.Lock()
defer mu.Unlock()
switch scenario {
case "off":
require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
require.Len(t, bodies, 1)
case "current_task":
case "rate_limited_off", "overloaded_off":
status, reason := http.StatusTooManyRequests, "owner_rate_limited"
if overloaded {
status, reason = http.StatusServiceUnavailable, "owner_overloaded"
}
require.Equal(t, status, answer.Code, answer.Body.String())
require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_"+reason)
require.NotEmpty(t, answer.Header().Get("Retry-After"))
require.Len(t, bodies, 1)
case "current_task", "rate_limited_current_task", "overloaded_current_task":
require.Equal(t, http.StatusUnprocessableEntity, answer.Code, answer.Body.String())
require.Contains(t, answer.Body.String(), "readable_intent_missing")
require.Len(t, bodies, 1)
case "no_accounts":
case "no_accounts", "rate_limited_no_accounts", "overloaded_no_accounts":
require.GreaterOrEqual(t, answer.Code, 400)
require.Len(t, bodies, 1)
default:
require.Len(t, bodies, 2, "one original request and exactly one sanitized continuation")
if rateLimited || overloaded {
require.Equal(t, []string{"Bearer fixture-omit-0", "Bearer fixture-omit-1"}, authorizations,
"continuation must use the eligible alternative, not the original owner")
}
require.NotContains(t, string(bodies[1]), "fixture-task-reference-715")
require.Contains(t, string(bodies[1]), "Historical encrypted content omitted")
for _, path := range []string{"input.1", "input.2", "input.3", "input.4"} {
Expand All @@ -131,6 +160,12 @@ func TestOpenAI409OmitHistoryHTTP(t *testing.T) {
require.Contains(t, answer.Body.String(), "continued from visible history")
}
}
if rateLimited {
require.Equal(t, cooldown, *accounts[0].RateLimitResetAt, "rebuild must preserve the owner's cooldown")
}
if overloaded {
require.Equal(t, cooldown, *accounts[0].OverloadUntil, "rebuild must preserve the owner's overload")
}
require.Equal(t, originalOwners, issue805Owners(t, clients()), "omission must not clear or rewrite the original owner")
})
}
Expand Down
4 changes: 4 additions & 0 deletions backend/internal/service/openai_409_omit_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c
}
r := openAIAgentRecoveryFromContext(ctx)
allowed := refusal.Reason == "owner_unavailable" || refusal.Reason == "route_changed" || refusal.Reason == "wire_changed" ||
refusal.Reason == "owner_rate_limited" || refusal.Reason == "owner_overloaded" ||
refusal.Reason == "http_previous_response_unsupported" || (refusal.Reason == "owner_conflict" && r != nil && r.mixedOwners)
// A known owner's cooldown is another pre-send availability failure. Under
// the explicit lossy policy, rebuild readable context for normal selection
// without clearing that cooldown or retrying a dispatched generation.
if !allowed || s == nil || r == nil || r.disallowLearning || r.omittedHistory || r.delivery != nil || s.settingService == nil ||
!s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) {
return ctx, body, false, nil
Expand Down
60 changes: 32 additions & 28 deletions backend/internal/service/openai_409_omit_history_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func TestOpenAI409OmissionSettingDefaultsOff(t *testing.T) {
func TestOpenAI409OmissionCannotClearRecoveryBarriers(t *testing.T) {
s := &OpenAIGatewayService{settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)}
body := []byte(`{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`)
for _, reason := range []string{"delivery_pending", "store_unavailable", "owner_conflict", "owner_rate_limited", "owner_overloaded", "http_previous_response_unsupported"} {
for _, reason := range []string{"delivery_pending", "store_unavailable", "owner_conflict", "http_previous_response_unsupported"} {
ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, &openAIAgentRecoveryRequest{owner: &openAIAgentRecoveryBinding{accountID: 1}})
_, clean, changed := s.TryOmitOpenAI409History(ctx, nil, body, "fixture", "gpt-5.1", &OpenAIAgentRecoveryError{Reason: reason})
require.False(t, changed, reason)
Expand Down Expand Up @@ -231,34 +231,38 @@ func TestOpenAI409ReadableReasoningRetainsUnknownShapesAsText(t *testing.T) {
}

func TestOpenAI409RebuildRechecksOriginalDeliveryBeforeSend(t *testing.T) {
for _, fence := range []string{"pending", "failed", "conflict"} {
t.Run(fence, func(t *testing.T) {
svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)}
issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody)
body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"role":"user","content":"complete the existing task"}]}`
c, _ := newTurnStateTestContext(t, 715, "fixture-session")
c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)})
ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra")
next, clean, changed, err := svc.TryRebuildOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable"))
require.NoError(t, err)
require.True(t, changed)
key := openAIAgentRecoveryFromContext(ctx).keys[0]
binding := svc.agentMessageRecovery.bindings[key]
switch fence {
case "pending":
binding.pending = "fixture-unconfirmed"
case "failed":
binding.failed = true
case "conflict":
binding.conflicted = true
for _, reason := range []string{"owner_unavailable", "owner_rate_limited", "owner_overloaded"} {
t.Run(reason, func(t *testing.T) {
for _, fence := range []string{"pending", "failed", "conflict"} {
t.Run(fence, func(t *testing.T) {
svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)}
issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody)
body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"role":"user","content":"complete the existing task"}]}`
c, _ := newTurnStateTestContext(t, 715, "fixture-session")
c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)})
ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra")
next, clean, changed, err := svc.TryRebuildOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError(reason))
require.NoError(t, err)
require.True(t, changed)
key := openAIAgentRecoveryFromContext(ctx).keys[0]
binding := svc.agentMessageRecovery.bindings[key]
switch fence {
case "pending":
binding.pending = "fixture-unconfirmed"
case "failed":
binding.failed = true
case "conflict":
binding.conflicted = true
}
svc.agentMessageRecovery.bindings[key] = binding
req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean))
require.NoError(t, err)
finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req)
defer finish(false)
require.Error(t, err, "sanitization must not erase a later delivery fence")
require.Equal(t, binding, svc.agentMessageRecovery.bindings[key])
})
}
svc.agentMessageRecovery.bindings[key] = binding
req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean))
require.NoError(t, err)
finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req)
defer finish(false)
require.Error(t, err, "sanitization must not erase a later delivery fence")
require.Equal(t, binding, svc.agentMessageRecovery.bindings[key])
})
}
}
Expand Down
4 changes: 3 additions & 1 deletion docs/encrypted-history-409-beta.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ HTTP `/v1/responses` 支持 JSON/SSE 有损续接。WebSocket 的 `http_bridge`

这是有损恢复。只要现存最新用户请求、原始指令或可信同任务摘要足够,旧不可读 agent 历史可以省略;不要求恢复完整历史。可读消息、已完成工具的调用参数、结果、ID 和顺序保留。旧 agent/reasoning 内容转换为有明确出处的普通上下文,密文用不可用标记替代。`previous_response_id`、`conversation` 及旧账号会话绑定在重建时一起解除,建立新的上游会话。不能保证缺失历史后的结论完整或供应商接受。

HTTP 当前轮尚未发送时,原账号的本地 `owner_rate_limited`(429)和 `owner_overloaded`(503)也进入上述续接流程,无需等待原账号恢复。重新选择的账号仍须通过正常准入;原账号的限流和过载截止时间保持不变。开关关闭时仍返回原错误及 `Retry-After`。实际发到上游后收到的 429/503 不属于这个恢复入口。

以下条件继续返回原错误:

- 最新请求完全不透明且无可读任务线索,也无匹配的未来 shadow 记录。
- 只有服务端指针而没有可读当前意图;当前轮工具调用/结果不成对或状态未确认。
- 交付未确认、owner 冲突、共享存储错误、429 限流或 503 过载。
- 交付未确认、owner 冲突、共享存储错误。
- 压缩端点、当前生成已发送或发送结果不明;已经输出的生成和已完成工具不自动重放。前一轮成功完成不阻止新的未发送轮次恢复。

本功能不针对任意供应商 409 进行删改重试。省略后的实际发送仍检查用户、Key、分组、模型、余额、额度、账号状态和并发;没有可用账号仍会失败。上游拒绝或交付不确定时不自动重新发送。既有 owner 缓存不清空、不改归属;新输出仍通过现有交付屏障登记。
Expand Down
Loading