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
21 changes: 17 additions & 4 deletions .github/workflows/issue715-agent-recovery.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
git rev-parse HEAD
test -z "$(git status --porcelain)"
cd backend
go test -race -tags=unit ./internal/service ./internal/handler ./internal/repository -run '^Test(Issue715|AstraCodexToolCapabilities|EncryptedSticky|EncryptedPrioritySticky|OpenAIGatewayService_SelectAccountWithScheduler_Encrypted)' -count=1 -v -timeout=10m
go test -race -tags=unit ./internal/service ./internal/handler ./internal/repository -run '^Test(Issue715|Issue758|AstraCodexToolCapabilities|EncryptedSticky|EncryptedPrioritySticky|OpenAIGatewayService_SelectAccountWithScheduler_Encrypted)' -count=1 -v -timeout=10m
go test -tags=integration ./internal/repository -run '^TestGatewayCacheSuite$' -testify.m '^TestIssue715AgentOwnership$' -count=1 -v -timeout=5m

red:
Expand Down Expand Up @@ -98,7 +98,7 @@ jobs:
git rev-parse HEAD
original=6df0cd5bb0ce4d774d34004008f9dd661d236468
targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go)
added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/service/openai_ws_agent_recovery.go)
added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go)
# The exact original gateway struct predates analysis admission state.
# Pin this unrelated leaf to its pre-admission version, preserving all
# Issue715 business-chain blobs and the retained handler regressions.
Expand Down Expand Up @@ -226,12 +226,25 @@ jobs:
ws_original=a575df898ccd0876c4c0eb1559da38cedfdfe99d
ws_targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go)
ws_added=backend/internal/service/openai_ws_agent_recovery.go
# The historical recovery request predates Issue758 cooldown state.
# Keep the exact delivery-defect blobs above, and pin only this
# scheduling compatibility leaf to the pre-Issue758 production base.
scheduler_compat=45e92f44470f91435bd261ea18111c271063c0ac
scheduler_leaf=backend/internal/service/openai_account_scheduler.go
wait_added=backend/internal/service/openai_agent_message_recovery_wait.go
git fetch --no-tags --depth=1 origin "$original"
git fetch --no-tags --depth=1 origin "$ws_original"
trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "$ws_added"; git diff --exit-code' EXIT
git fetch --no-tags --depth=1 origin "$scheduler_compat"
trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "$ws_added" "$scheduler_leaf" "$wait_added"; git diff --exit-code' EXIT
git restore --source="$original" -- "${targets[@]}"
git restore --source="$ws_original" -- "${ws_targets[@]}"
rm -- "$added" "$ws_added"
git restore --source="$scheduler_compat" -- "$scheduler_leaf"
expected=$(git rev-parse "$scheduler_compat:$scheduler_leaf")
actual=$(git hash-object "$scheduler_leaf")
echo "compatibility_leaf_baseline=$scheduler_compat path=$scheduler_leaf expected_blob=$expected tested_blob=$actual"
test "$expected" = "$actual"
rm -- "$added" "$ws_added" "$wait_added"
test ! -e "$wait_added"
for target in "${targets[@]}"; do
expected=$(git rev-parse "$original:$target")
actual=$(git hash-object "$target")
Expand Down
36 changes: 34 additions & 2 deletions backend/internal/handler/openai_agent_message_recovery.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package handler

import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"time"

"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
)

Expand All @@ -13,6 +17,34 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er
if !errors.As(err, &recovery) {
return false
}
h.handleStreamingAwareErrorWithCode(c, http.StatusConflict, "invalid_request_error", recovery.ClientCode(), recovery.ClientMessage(), streamStarted || c.Writer.Written(), false)
committed := streamStarted || c.Writer.Written()
if !committed && !recovery.RetryAt.IsZero() {
seconds := max(int64(1), int64((time.Until(recovery.RetryAt)+time.Second-1)/time.Second))
c.Header("Retry-After", strconv.FormatInt(seconds, 10))
}
h.handleStreamingAwareErrorWithCode(c, recovery.HTTPStatus(), recovery.ClientType(), recovery.ClientCode(), recovery.ClientMessage(), committed, false)
return true
}

// The socket has already upgraded when initial scheduling runs. Send the full
// recovery guidance as an error event; close reasons alone are length limited.
func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Context, conn *coderws.Conn, err error) bool {
var recovery *service.OpenAIAgentRecoveryError
if !errors.As(err, &recovery) {
return false
}
payload, _ := json.Marshal(map[string]any{
"type": "error", "status": recovery.HTTPStatus(),
"error": map[string]string{"type": recovery.ClientType(), "code": recovery.ClientCode(), "message": recovery.ClientMessage()},
})
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_ = conn.Write(writeCtx, coderws.MessageText, payload)
status, reason := coderws.StatusPolicyViolation, recovery.ClientCode()
if !recovery.RetryAt.IsZero() {
status = coderws.StatusTryAgainLater
reason += "; retry after " + recovery.RetryAt.UTC().Format(time.RFC3339)
}
closeOpenAIClientWS(conn, status, reason)
return true
}
3 changes: 3 additions & 0 deletions backend/internal/handler/openai_gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3343,6 +3343,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
requestPlatform,
)
if err != nil {
if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err) {
return
}
if errors.Is(err, service.ErrPriorityLatencyUnavailable) {
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "latency scheduling temporarily unavailable; retry after 5 seconds")
return
Expand Down
Loading
Loading