fix(openai,codex): build stream errors via ojson.Doc and preserve SSE status

- Build OpenAI Responses stream error and failed chunks directly through ojson.Doc with single-exit serialization, supporting scalar error strings without map mutations.
- Preserve valid top-level and body envelope HTTP error status codes when normalizing typeless Codex SSE failures and Responses SSE frames.
- Normalize scalar and blank WebSocket error fields purely via ojson.Doc.
This commit is contained in:
sususu98
2026-11-16 13:50:58 +08:00
parent 20df0c25b2
commit 80e8350c95
7 changed files with 180 additions and 172 deletions

View File

@@ -180,7 +180,7 @@ func codexTerminalFailureErrWithCooling(eventData []byte, modelLevelCooling bool
}
func codexTerminalFailureStatus(body []byte) int {
for _, path := range []string{"error.status_code", "error.status"} {
for _, path := range []string{"error.status_code", "error.status", "status_code", "status"} {
if status := int(ojson.GetBytesNoCopy(body, path).Int()); status >= 400 && status <= 599 {
return status
}
@@ -234,6 +234,12 @@ func codexTerminalFailureBody(eventData []byte) ([]byte, bool) {
if doc == nil {
doc = ojson.NewDocString(`{"error":{"message":"upstream stream failed without error details"}}`)
}
for _, statusPath := range []string{"status_code", "status", "body.status_code", "body.status"} {
if status := int(ojson.GetBytesNoCopy(eventData, statusPath).Int()); status >= 400 && status <= 599 {
_ = doc.Set("status", status)
break
}
}
if seq := ojson.GetBytesNoCopy(eventData, "sequence_number"); seq.Exists() {
_ = doc.Set("sequence_number", seq.Int())
}

View File

@@ -147,10 +147,10 @@ func TestCodexTypelessErrorsPreserveCredentialStatus(t *testing.T) {
payload := fmt.Sprintf(`{"status":%d,"error":{"type":"authentication_error","code":"invalid_request_error","message":"rejected"},"headers":{"retry-after":"7"}}`, status)
err, ok := parseCodexWebsocketError([]byte(payload))
if !ok || statusCodeFromTestError(t, err) != status {
t.Fatalf("status %d: %v", status, err)
t.Fatalf("websocket status %d: %v", status, err)
}
if clienterror.IsRequestFault(status, err) {
t.Fatalf("credential status %d became a request fault", status)
t.Fatalf("websocket credential status %d became a request fault", status)
}
if status == 429 {
retry := err.(interface{ RetryAfter() *time.Duration }).RetryAfter()
@@ -158,5 +158,27 @@ func TestCodexTypelessErrorsPreserveCredentialStatus(t *testing.T) {
t.Fatalf("retry-after = %v", retry)
}
}
sseErr, _, okSSE := codexTerminalFailureErr([]byte(payload))
if !okSSE || statusCodeFromTestError(t, sseErr) != status {
t.Fatalf("sse status %d: %v", status, sseErr)
}
if clienterror.IsRequestFault(statusCodeFromTestError(t, sseErr), sseErr) {
t.Fatalf("sse credential status %d became a request fault", status)
}
}
untypedRateLimit := []byte(`{"status":429,"error":{"message":"Too many concurrent requests"}}`)
sseRateLimitErr, _, ok := codexTerminalFailureErr(untypedRateLimit)
if !ok || statusCodeFromTestError(t, sseRateLimitErr) != http.StatusTooManyRequests {
t.Fatalf("untyped 429 sse status = %v (ok=%v)", sseRateLimitErr, ok)
}
blankScalarWS, okWS := parseCodexWebsocketError([]byte(`{"type":"error","status":503,"error":" "}`))
if !okWS || blankScalarWS == nil {
t.Fatal("missing blank scalar websocket error")
}
if got := ojson.Get(blankScalarWS.Error(), "error.message").String(); got != http.StatusText(http.StatusServiceUnavailable) {
t.Fatalf("blank scalar fallback message = %q, want %q", got, http.StatusText(http.StatusServiceUnavailable))
}
}

View File

@@ -91,9 +91,16 @@ func buildCodexWebsocketErrorPayload(payload []byte, status int) []byte {
}
fillBlankErrorMessage := func() {
if node := doc.Get("error"); node.Type == ojson.String && strings.TrimSpace(node.String()) != "" {
_ = doc.Set("error", map[string]any{"message": node.String()})
return
if node := doc.Get("error"); !node.IsObject() {
scalar := ""
if node.Type != ojson.Null && strings.TrimSpace(node.String()) != "" {
scalar = node.String()
}
_ = doc.SetRawBytes("error", []byte(`{}`))
if scalar != "" {
_ = doc.Set("error.message", scalar)
return
}
}
if strings.TrimSpace(doc.Get("error.message").String()) != "" {
return

View File

@@ -344,8 +344,8 @@ func (f *responsesSSEFramer) repairFrame(frame []byte) []byte {
func responsesSSEPayloadErrorMessage(payload []byte) *interfaces.ErrorMessage {
status := http.StatusBadGateway
var candidatesBuf [6]ojson.Result
candidates := ojson.GetManyBytesNoCopy(candidatesBuf[:0], payload, "status", "status_code", "error.status", "error.status_code", "response.error.status", "response.error.status_code")
var candidatesBuf [10]ojson.Result
candidates := ojson.GetManyBytesNoCopy(candidatesBuf[:0], payload, "status", "status_code", "error.status", "error.status_code", "response.error.status", "response.error.status_code", "body.status", "body.status_code", "body.error.status", "body.error.status_code")
foundStatus := false
for _, res := range candidates {
candidate := int(res.Int())

View File

@@ -27,4 +27,10 @@ func TestResponsesSSEFramerTypelessBodyPolicyError(t *testing.T) {
if got := ojson.GetBytes(payload, "sequence_number").Int(); got != 7 {
t.Fatalf("sequence = %d", got)
}
bodyStatusFramer := &responsesSSEFramer{}
_ = bodyStatusFramer.repairFrame([]byte("data: " + `{"body":{"status":429,"error":{"message":"rate limited"}}}` + "\n\n"))
if bodyStatusFramer.terminalError == nil || bodyStatusFramer.terminalError.StatusCode != http.StatusTooManyRequests {
t.Fatalf("body status terminal error = %#v", bodyStatusFramer.terminalError)
}
}

View File

@@ -1,12 +1,10 @@
package handlers
import (
"bytes"
"fmt"
"net/http"
"strings"
"github.com/MoeForge/moego/json"
"github.com/MoeForge/moego/ojson"
)
type openAIResponsesStreamErrorChunk struct {
@@ -15,17 +13,6 @@ type openAIResponsesStreamErrorChunk struct {
SequenceNumber int `json:"sequence_number"`
}
type openAIResponsesStreamFailedChunk struct {
Type string `json:"type"`
SequenceNumber int `json:"sequence_number"`
Response openAIResponsesStreamFailedResponse `json:"response"`
}
type openAIResponsesStreamFailedResponse struct {
Status string `json:"status"`
Error map[string]any `json:"error"`
}
// openAIResponsesStreamErrorClass pairs the OpenAI error code and the OpenAI
// error type that a given HTTP status is reported as.
//
@@ -81,15 +68,29 @@ func openAIResponsesStreamErrorType(status int) string {
return openAIResponsesStreamErrorClassFor(status).errorType
}
func unmarshalJSONWithNumber(data []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
return dec.Decode(v)
}
// BuildOpenAIResponsesStreamErrorChunk builds an OpenAI Responses streaming error chunk.
// It matches the official responses streaming event shape where the error details are nested.
func BuildOpenAIResponsesStreamErrorChunk(status int, errText string, sequenceNumber int) []byte {
doc := ojson.NewDocString(`{"type":"error","error":{},"sequence_number":0}`)
populateOpenAIResponsesStreamErrorChunkDoc(doc, "error", status, errText, sequenceNumber)
if data := doc.Bytes(); len(data) > 0 {
return data
}
return []byte(`{"type":"error","error":{"type":"server_error","code":"internal_server_error","message":"internal error","param":null},"sequence_number":0}`)
}
// BuildOpenAIResponsesStreamFailedChunk builds the terminal Responses event used by official Codex clients.
// It is intentionally separate from BuildOpenAIResponsesStreamErrorChunk so existing clients keep the legacy shape.
func BuildOpenAIResponsesStreamFailedChunk(status int, errText string, sequenceNumber int) []byte {
doc := ojson.NewDocString(`{"type":"response.failed","sequence_number":0,"response":{"status":"failed","error":{}}}`)
populateOpenAIResponsesStreamErrorChunkDoc(doc, "response.error", status, errText, sequenceNumber)
if data := doc.Bytes(); len(data) > 0 {
return data
}
return []byte(`{"type":"response.failed","sequence_number":0,"response":{"status":"failed","error":{"type":"server_error","code":"internal_server_error","message":"internal error"}}}`)
}
func populateOpenAIResponsesStreamErrorChunkDoc(doc *ojson.Doc, errorPath string, status int, errText string, sequenceNumber int) {
if status <= 0 {
status = http.StatusInternalServerError
}
@@ -103,55 +104,81 @@ func BuildOpenAIResponsesStreamErrorChunk(status int, errText string, sequenceNu
}
code := openAIResponsesStreamErrorCode(status)
trimmed := strings.TrimSpace(errText)
if trimmed != "" && json.Valid([]byte(trimmed)) {
var payload map[string]any
if errUnmarshal := unmarshalJSONWithNumber([]byte(trimmed), &payload); errUnmarshal == nil {
if v, ok := payload["sequence_number"]; ok {
switch n := v.(type) {
case json.Number:
if seqInt, err := n.Int64(); err == nil {
sequenceNumber = int(seqInt)
}
case float64:
sequenceNumber = int(n)
}
}
}
}
if strings.TrimSpace(code) == "" {
code = "unknown_error"
}
errorDetail := openAIResponsesStreamErrorDetail(status, errText, code, message)
errorType := openAIResponsesStreamErrorType(status)
var paramRaw string
hasParam := false
data, errMarshal := json.Marshal(openAIResponsesStreamErrorChunk{
Type: "error",
Error: errorDetail,
SequenceNumber: sequenceNumber,
})
if errMarshal == nil {
return data
trimmed := strings.TrimSpace(errText)
if trimmed != "" && ojson.Valid(trimmed) {
root := ojson.Parse(trimmed)
if root.IsObject() {
if seqNode := root.Get("sequence_number"); seqNode.Type == ojson.Number {
sequenceNumber = int(seqNode.Int())
}
_ = doc.Set("sequence_number", sequenceNumber)
hasScalarMessage := false
for _, path := range []string{"error", "response.error", "body.error"} {
errNode := root.Get(path)
if !errNode.Exists() || errNode.Type == ojson.Null {
continue
}
if errNode.IsObject() {
_ = doc.SetRaw(errorPath, errNode.Raw)
applyOpenAIResponsesNestedErrorCodeDoc(doc, errorPath)
return
}
if errNode.Type == ojson.String && !hasScalarMessage {
if scalar := strings.TrimSpace(errNode.String()); scalar != "" {
message = scalar
} else {
message = http.StatusText(status)
}
hasScalarMessage = true
}
}
if msgNode := root.Get("message"); msgNode.Type == ojson.String && strings.TrimSpace(msgNode.String()) != "" {
message = strings.TrimSpace(msgNode.String())
}
hasTopLevelCode := false
if codeNode := root.Get("code"); codeNode.Exists() && codeNode.Type != ojson.Null {
if c := strings.TrimSpace(codeNode.String()); c != "" {
code = c
hasTopLevelCode = true
}
}
if hasTopLevelCode && !hasScalarMessage && strings.TrimSpace(root.Get("message").String()) == "" {
fallback := openAIResponsesPolicyFallbackMessage(code)
if fallback == "" {
fallback = code
}
message = fallback
}
if typeNode := root.Get("type"); typeNode.Type == ojson.String {
if t := strings.TrimSpace(typeNode.String()); t != "" && t != "error" && t != "response.failed" && t != "response.error" {
errorType = t
}
}
if paramNode := root.Get("param"); paramNode.Exists() {
paramRaw = paramNode.Raw
hasParam = true
}
}
}
// Extremely defensive fallback.
fallbackDetail := map[string]any{
"type": "server_error",
"code": "internal_server_error",
"message": message,
"param": nil,
_ = doc.Set("sequence_number", sequenceNumber)
_ = doc.SetRaw(errorPath, `{"type":"","code":"","message":"","param":null}`)
_ = doc.Set(errorPath+".type", errorType)
_ = doc.Set(errorPath+".code", code)
_ = doc.Set(errorPath+".message", message)
if hasParam {
_ = doc.SetRaw(errorPath+".param", paramRaw)
}
data, _ = json.Marshal(openAIResponsesStreamErrorChunk{
Type: "error",
Error: fallbackDetail,
SequenceNumber: sequenceNumber,
})
if len(data) > 0 {
return data
}
return []byte(`{"type":"error","error":{"type":"server_error","code":"internal_server_error","message":"internal error","param":null},"sequence_number":0}`)
}
func openAIResponsesPolicyFallbackMessage(code string) string {
@@ -169,116 +196,22 @@ func openAIResponsesPolicyFallbackMessage(code string) string {
}
}
func applyOpenAIResponsesNestedErrorCode(errorDetail map[string]any) map[string]any {
if existing, ok := errorDetail["code"]; ok && existing != nil {
code := strings.TrimSpace(fmt.Sprint(existing))
if code != "" {
if msg, _ := errorDetail["message"].(string); strings.TrimSpace(msg) == "" {
func applyOpenAIResponsesNestedErrorCodeDoc(doc *ojson.Doc, errorPath string) {
if codeNode := doc.Get(errorPath + ".code"); codeNode.Exists() && codeNode.Type != ojson.Null {
if code := strings.TrimSpace(codeNode.String()); code != "" {
if strings.TrimSpace(doc.Get(errorPath+".message").String()) == "" {
fallback := openAIResponsesPolicyFallbackMessage(code)
if fallback == "" {
fallback = code
}
errorDetail["message"] = fallback
_ = doc.Set(errorPath+".message", fallback)
}
return errorDetail
return
}
}
// Anthropic reports input overflow by message only; Responses clients key on this code.
if m, _ := errorDetail["message"].(string); errorDetail["type"] == "invalid_request_error" && strings.HasPrefix(m, "prompt is too long") {
errorDetail["code"] = "context_length_exceeded"
if doc.Get(errorPath+".type").String() == "invalid_request_error" &&
strings.HasPrefix(doc.Get(errorPath+".message").String(), "prompt is too long") {
_ = doc.Set(errorPath+".code", "context_length_exceeded")
}
return errorDetail
}
func openAIResponsesStreamErrorDetail(status int, errText, code, message string) map[string]any {
var payload map[string]any
trimmed := strings.TrimSpace(errText)
if trimmed != "" && json.Valid([]byte(trimmed)) {
if errUnmarshal := unmarshalJSONWithNumber([]byte(trimmed), &payload); errUnmarshal == nil {
if errorDetail, ok := payload["error"].(map[string]any); ok {
return applyOpenAIResponsesNestedErrorCode(errorDetail)
}
if response, ok := payload["response"].(map[string]any); ok {
if errorDetail, ok := response["error"].(map[string]any); ok {
return applyOpenAIResponsesNestedErrorCode(errorDetail)
}
}
if bodyMap, ok := payload["body"].(map[string]any); ok {
if errorDetail, ok := bodyMap["error"].(map[string]any); ok {
return applyOpenAIResponsesNestedErrorCode(errorDetail)
}
}
if m, ok := payload["message"].(string); ok && strings.TrimSpace(m) != "" {
message = strings.TrimSpace(m)
}
if v, ok := payload["code"]; ok && v != nil {
if c, ok := v.(string); ok && strings.TrimSpace(c) != "" {
code = strings.TrimSpace(c)
} else {
code = strings.TrimSpace(fmt.Sprint(v))
}
}
}
}
errorType := openAIResponsesStreamErrorType(status)
detail := map[string]any{
"type": errorType,
"code": code,
"message": message,
"param": nil,
}
if payload != nil {
if t, ok := payload["type"].(string); ok && strings.TrimSpace(t) != "" && strings.TrimSpace(t) != "error" {
detail["type"] = strings.TrimSpace(t)
}
if paramVal, exists := payload["param"]; exists {
detail["param"] = paramVal
}
}
return detail
}
func openAIResponsesStreamFailedErrorDetail(status int, errText, code, message string) map[string]any {
return openAIResponsesStreamErrorDetail(status, errText, code, message)
}
// BuildOpenAIResponsesStreamFailedChunk builds the terminal Responses event used by official Codex clients.
// It is intentionally separate from BuildOpenAIResponsesStreamErrorChunk so existing clients keep the legacy shape.
func BuildOpenAIResponsesStreamFailedChunk(status int, errText string, sequenceNumber int) []byte {
if status <= 0 {
status = http.StatusInternalServerError
}
if sequenceNumber < 0 {
sequenceNumber = 0
}
errorChunkBytes := BuildOpenAIResponsesStreamErrorChunk(status, errText, sequenceNumber)
var errorChunk openAIResponsesStreamErrorChunk
_ = unmarshalJSONWithNumber(errorChunkBytes, &errorChunk)
sequenceNumber = errorChunk.SequenceNumber
errorDetail := errorChunk.Error
if errorDetail == nil {
code := openAIResponsesStreamErrorCode(status)
message := strings.TrimSpace(errText)
if message == "" {
message = http.StatusText(status)
}
errorDetail = openAIResponsesStreamErrorDetail(status, errText, code, message)
}
data, errMarshal := json.Marshal(openAIResponsesStreamFailedChunk{
Type: "response.failed",
SequenceNumber: sequenceNumber,
Response: openAIResponsesStreamFailedResponse{
Status: "failed",
Error: errorDetail,
},
})
if errMarshal == nil {
return data
}
return []byte(`{"type":"response.failed","sequence_number":0,"response":{"status":"failed","error":{"type":"server_error","code":"internal_server_error","message":"internal error"}}}`)
}

View File

@@ -376,4 +376,38 @@ func TestBuildOpenAIResponsesStreamErrorChunk_BodyErrorLayoutAndBlankPolicyFallb
if genericChunk.Error["message"] != "content_policy_violation" {
t.Fatalf("error.message = %v, want content_policy_violation", genericChunk.Error["message"])
}
scalarBody := BuildOpenAIResponsesStreamErrorChunk(
http.StatusServiceUnavailable,
`{"type":"error","body":{"error":"model is at capacity"},"sequence_number":4}`,
0,
)
var scalarChunk openAIResponsesStreamErrorChunk
if err := json.Unmarshal(scalarBody, &scalarChunk); err != nil {
t.Fatalf("unmarshal scalar body chunk: %v", err)
}
if scalarChunk.SequenceNumber != 4 {
t.Fatalf("sequence_number = %d, want 4", scalarChunk.SequenceNumber)
}
if scalarChunk.Error["message"] != "model is at capacity" {
t.Fatalf("error.message = %v, want scalar message", scalarChunk.Error["message"])
}
scalarFailed := BuildOpenAIResponsesStreamFailedChunk(
http.StatusServiceUnavailable,
`{"error":"model is at capacity","sequence_number":6}`,
0,
)
var failedPayload struct {
SequenceNumber int `json:"sequence_number"`
Response struct {
Error map[string]any `json:"error"`
} `json:"response"`
}
if err := json.Unmarshal(scalarFailed, &failedPayload); err != nil {
t.Fatalf("unmarshal scalar failed chunk: %v", err)
}
if failedPayload.SequenceNumber != 6 || failedPayload.Response.Error["message"] != "model is at capacity" {
t.Fatalf("unexpected scalar failed payload: %+v", failedPayload)
}
}