From 47389a5b80ffaecf14d7b80ecfc7d83dc23e7140 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:33:52 +0800 Subject: [PATCH 1/4] feat(toolcall): add the canonical tool-call contract package Introduce internal/toolcall as the single model of tool declarations, tool choice, argument repair, native call identity and rendering. translate.ValidateChatRequest now delegates tool_choice validation to toolcall.ParseRequest, which keeps an orphan `auto` degrading to unspecified while a `required` or named choice fails instead of being silently dropped. translate's own tool-argument helpers stay in place until the delivery path switches to the new package in a follow-up change. --- .../unreleased/toolcall-contract-package.md | 10 + internal/toolcall/args.go | 193 +++ internal/toolcall/model.go | 243 +++ internal/toolcall/native.go | 1398 +++++++++++++++++ internal/toolcall/native_identity_test.go | 81 + internal/toolcall/native_test.go | 352 +++++ internal/toolcall/reducer.go | 435 +++++ internal/toolcall/render.go | 239 +++ internal/toolcall/request.go | 387 +++++ internal/toolcall/schema.go | 482 ++++++ internal/toolcall/toolcall_test.go | 261 +++ internal/translate/compat.go | 104 +- internal/translate/compat_test.go | 14 +- internal/translate/native_responses.go | 10 + internal/translate/responses_collect_test.go | 15 + internal/translate/session_seed.go | 1 - 16 files changed, 4130 insertions(+), 95 deletions(-) create mode 100644 changelog/unreleased/toolcall-contract-package.md create mode 100644 internal/toolcall/args.go create mode 100644 internal/toolcall/model.go create mode 100644 internal/toolcall/native.go create mode 100644 internal/toolcall/native_identity_test.go create mode 100644 internal/toolcall/native_test.go create mode 100644 internal/toolcall/reducer.go create mode 100644 internal/toolcall/render.go create mode 100644 internal/toolcall/request.go create mode 100644 internal/toolcall/schema.go create mode 100644 internal/toolcall/toolcall_test.go diff --git a/changelog/unreleased/toolcall-contract-package.md b/changelog/unreleased/toolcall-contract-package.md new file mode 100644 index 000000000..969a000b7 --- /dev/null +++ b/changelog/unreleased/toolcall-contract-package.md @@ -0,0 +1,10 @@ +### English + +- Add `internal/toolcall`: one canonical model of tool declarations, tool choice, argument repair, native call identity and rendering, so protocols stop each re-implementing the contract. +- Validate `tools`, `tool_choice` and `parallel_tool_calls` through that parser in the shared chat-request validation every protocol entry runs, so an orphan `auto` degrades to unspecified while `required` or a named choice fails instead of silently dropping the tool request. + +### 中文 + +- 新增 `internal/toolcall`:工具声明、工具选择、参数修复、原生调用身份与渲染只有一份规范模型,协议层不再各自实现这套契约。 +- Responses 入口与各协议的共用请求校验都通过该解析器校验 `tools`、`tool_choice`、`parallel_tool_calls`:孤立的 `auto` 降级为未指定,`required` 或指定工具则校验失败,不再静默丢弃工具请求。 + diff --git a/internal/toolcall/args.go b/internal/toolcall/args.go new file mode 100644 index 000000000..994ec00e7 --- /dev/null +++ b/internal/toolcall/args.go @@ -0,0 +1,193 @@ +package toolcall + +import ( + "encoding/json" + "strings" +) + +const maxCloseClosers = 24 + +// RepairArguments attempts formatting-level repair only. It returns ok=false +// when a value was cut mid-string, so callers never receive a value the model +// did not finish writing. +func RepairArguments(raw string) (string, bool) { + text := strings.TrimSpace(raw) + if text == "" { + return "{}", true + } + if json.Valid([]byte(text)) { + return text, true + } + candidates := argumentRepairCandidates(text) + for _, candidate := range candidates { + if json.Valid([]byte(candidate)) { + return candidate, true + } + } + for _, candidate := range candidates { + if closed, ok := closeArgumentTail(candidate); ok { + return closed, true + } + } + if prefix, ok := decodeArgumentPrefix(text); ok { + return prefix, true + } + return "", false +} + +func decodeArgumentPrefix(text string) (string, bool) { + decoder := json.NewDecoder(strings.NewReader(text)) + var value any + if err := decoder.Decode(&value); err != nil { + return "", false + } + var extra any + if err := decoder.Decode(&extra); err == nil { + return "", false + } + encoded, err := json.Marshal(value) + if err != nil { + return "", false + } + return string(encoded), true +} + +func argumentRepairCandidates(text string) []string { + candidates := []string{text} + if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text { + candidates = append(candidates, withoutTrailing) + } + if escaped := escapeBareQuotes(text); escaped != text { + candidates = append(candidates, escaped, stripTrailingCommas(escaped)) + } + return candidates +} + +// stripTrailingCommas removes `,` that directly precede a closing brace or +// bracket, which models emit routinely and strict JSON rejects. +func stripTrailingCommas(text string) string { + var out strings.Builder + out.Grow(len(text)) + for index := 0; index < len(text); index++ { + character := text[index] + if character == ',' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next < len(text) && (text[next] == '}' || text[next] == ']') { + continue + } + } + out.WriteByte(character) + } + return out.String() +} + +// escapeBareQuotes escapes `"` characters that appear inside a JSON string +// value. A closing quote is accepted only when the next non-space byte is one +// of `, } ] :` or the end of the buffer. +func escapeBareQuotes(text string) string { + var out strings.Builder + out.Grow(len(text)) + inString := false + for index := 0; index < len(text); { + character := text[index] + if !inString { + out.WriteByte(character) + if character == '"' { + inString = true + } + index++ + continue + } + if character == '\\' && index+1 < len(text) { + out.WriteString(text[index : index+2]) + index += 2 + continue + } + if character == '"' { + next := index + 1 + for next < len(text) && isJSONSpace(text[next]) { + next++ + } + if next >= len(text) || strings.IndexByte(",}]:", text[next]) >= 0 { + out.WriteByte(character) + inString = false + } else { + out.WriteString(`\"`) + } + index++ + continue + } + out.WriteByte(character) + index++ + } + return out.String() +} + +// closeArgumentTail appends the closers the model never got to emit, but only +// when no string is left open - a value cut mid-string stays unrepaired. +func closeArgumentTail(text string) (string, bool) { + stack := make([]byte, 0, maxCloseClosers) + var out strings.Builder + out.Grow(len(text) + maxCloseClosers) + inString := false + for index := 0; index < len(text); index++ { + character := text[index] + if inString { + out.WriteByte(character) + if character == '\\' && index+1 < len(text) { + out.WriteByte(text[index+1]) + index++ + continue + } + if character == '"' { + inString = false + } + continue + } + switch character { + case '"': + inString = true + out.WriteByte(character) + case '{', '[': + if len(stack) >= maxCloseClosers { + return "", false + } + stack = append(stack, character) + out.WriteByte(character) + case '}', ']': + if len(stack) == 0 { + return "", false + } + open := stack[len(stack)-1] + if (character == '}' && open != '{') || (character == ']' && open != '[') { + return "", false + } + stack = stack[:len(stack)-1] + out.WriteByte(character) + default: + out.WriteByte(character) + } + } + if inString || len(stack) == 0 { + return "", false + } + for index := len(stack) - 1; index >= 0; index-- { + if stack[index] == '{' { + out.WriteString("}") + } else { + out.WriteString("]") + } + } + closed := stripTrailingCommas(out.String()) + if json.Valid([]byte(closed)) { + return closed, true + } + return "", false +} + +func isJSONSpace(character byte) bool { + return character == ' ' || character == '\t' || character == '\n' || character == '\r' +} diff --git a/internal/toolcall/model.go b/internal/toolcall/model.go new file mode 100644 index 000000000..80e82b222 --- /dev/null +++ b/internal/toolcall/model.go @@ -0,0 +1,243 @@ +// Package toolcall defines the provider-neutral tool-call contract shared by +// request translation, provider adapters, routing and the three public +// protocol renderers. +// +// The package deliberately does not import translate or any provider package. +// It owns validation and stream assembly; adapters own wire dialects. +package toolcall + +import ( + "encoding/json" + "fmt" + "strings" +) + +// Protocol is one public request dialect. It scopes fallback call indexes and +// selectors, but never tool identity. +type Protocol string + +const ( + ProtocolChat Protocol = "chat" + ProtocolMessages Protocol = "messages" + ProtocolResponses Protocol = "responses" +) + +func NormalizeProtocol(value string) Protocol { + switch strings.ToLower(strings.TrimSpace(value)) { + case "messages", "anthropic", "anthropic_messages": + return ProtocolMessages + case "responses", "openai_responses", "native_responses": + return ProtocolResponses + default: + return ProtocolChat + } +} + +// Dialect names the wire shape a provider adapter speaks. +type Dialect string + +const ( + DialectOpenAIChat Dialect = "openai_chat" + DialectAnthropic Dialect = "anthropic_messages" + DialectResponses Dialect = "openai_responses" + DialectPromptedTools Dialect = "prompted_tools" +) + +// ExecutionLevel records how strongly a provider can enforce a tool request. +// Native is a real upstream constraint; Validated is a prompt plus a +// post-response check; Prompted has no enforceable selector. +type ExecutionLevel string + +const ( + ExecutionNative ExecutionLevel = "native" + ExecutionValidated ExecutionLevel = "validated" + ExecutionPrompted ExecutionLevel = "prompted" + ExecutionNone ExecutionLevel = "none" +) + +// ChoiceMode is the canonical tool_choice state. Unspecified is distinct from +// auto: a missing selector must not be rewritten into an explicit one. +type ChoiceMode string + +const ( + ChoiceUnspecified ChoiceMode = "unspecified" + ChoiceNone ChoiceMode = "none" + ChoiceAuto ChoiceMode = "auto" + ChoiceRequired ChoiceMode = "required" + ChoiceNamed ChoiceMode = "named" +) + +// RepairMode makes historical argument repair explicit. Preserve keeps the raw +// bytes and reports invalid; SafeRepair only removes clearly unfinished syntax +// and never pads a truncated value; Reject returns an invalid-call error. +type RepairMode string + +const ( + RepairPreserve RepairMode = "preserve" + RepairSafe RepairMode = "safe-repair" + RepairReject RepairMode = "reject" +) + +// SchemaMode controls whether a request requires strict object schemas. +type SchemaMode string + +const ( + SchemaRelaxed SchemaMode = "relaxed" + SchemaStrict SchemaMode = "strict" +) + +// Spec is one declared tool. Name is the upstream wire name; Namespace and +// OriginalName preserve the protocol identity separately so a flat name can +// round-trip without guessing from underscores. +type Spec struct { + Name string `json:"name"` + OriginalName string `json:"original_name,omitempty"` + Namespace string `json:"namespace,omitempty"` + Description string `json:"description,omitempty"` + Parameters json.RawMessage `json:"parameters,omitempty"` + Strict bool `json:"strict,omitempty"` + Custom bool `json:"custom,omitempty"` + Source Protocol `json:"source,omitempty"` +} + +// Choice is a parsed tool_choice. Name is only set for ChoiceNamed. +type Choice struct { + Mode ChoiceMode `json:"mode"` + Name string `json:"name,omitempty"` +} + +// Policy carries request-level call constraints. +type Policy struct { + Parallel *bool `json:"parallel,omitempty"` + MaxCalls int `json:"max_calls,omitempty"` + Schema SchemaMode `json:"schema"` + Repair RepairMode `json:"repair"` + NativeStrict bool `json:"native_strict,omitempty"` +} + +// Request is the canonical tool declaration for one provider attempt. +type Request struct { + Protocol Protocol `json:"protocol"` + Specs []Spec `json:"specs"` + Choice Choice `json:"choice"` + Policy Policy `json:"policy"` + Diagnostics []string `json:"diagnostics,omitempty"` +} + +func (r Request) HasTools() bool { return len(r.Specs) > 0 } + +func (r Request) SpecByName(name string) (Spec, bool) { + name = strings.TrimSpace(name) + for _, spec := range r.Specs { + if spec.Name == name { + return spec, true + } + } + return Spec{}, false +} + +func (r Request) Names() []string { + names := make([]string, 0, len(r.Specs)) + for _, spec := range r.Specs { + names = append(names, spec.Name) + } + return names +} + +// CallStatus is the lifecycle of one tool call. +type CallStatus string + +const ( + CallStarted CallStatus = "started" + CallCompleted CallStatus = "completed" + CallInvalid CallStatus = "invalid" + CallFailed CallStatus = "failed" + CallTruncated CallStatus = "truncated" +) + +// Call is one ordered tool invocation. ArgumentsRaw is the exact concatenated +// provider byte stream; Arguments is the validated object for the renderer. +type Call struct { + Index int `json:"index"` + InternalID string `json:"internal_id"` + ProviderID string `json:"provider_id,omitempty"` + Name string `json:"name"` + Namespace string `json:"namespace,omitempty"` + OriginalName string `json:"original_name,omitempty"` + ArgumentsRaw string `json:"arguments_raw"` + Arguments json.RawMessage `json:"arguments,omitempty"` + Status CallStatus `json:"status"` + Repaired bool `json:"repaired,omitempty"` + Error string `json:"error,omitempty"` + Sealed bool `json:"sealed,omitempty"` +} + +// EventKind is one canonical stream event. +type EventKind string + +const ( + EventTextDelta EventKind = "text_delta" + EventReasoningDelta EventKind = "reasoning_delta" + EventCallStarted EventKind = "tool_call_started" + EventCallArguments EventKind = "tool_arguments_delta" + EventCallSealed EventKind = "tool_call_sealed" + EventTurnFailed EventKind = "turn_failed" +) + +// Event is a renderer-facing delta. Call is a snapshot copy; renderers must +// treat it as read-only. +type Event struct { + Kind EventKind `json:"kind"` + Text string `json:"text,omitempty"` + Call *Call `json:"call,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// TurnStatus is the mutually exclusive terminal state of one upstream turn. +type TurnStatus string + +const ( + TurnCompleted TurnStatus = "completed" + TurnToolCalls TurnStatus = "tool_calls" + TurnTruncated TurnStatus = "truncated" + TurnInvalid TurnStatus = "invalid" + TurnFailed TurnStatus = "failed" + TurnCanceled TurnStatus = "canceled" +) + +// TurnResult is the normalized assistant turn. UpstreamTerminal and +// DownstreamDelivered are deliberately separate facts. +type TurnResult struct { + Protocol Protocol `json:"protocol"` + Text string `json:"text"` + Reasoning string `json:"reasoning"` + Calls []Call `json:"calls,omitempty"` + FinishReason string `json:"finish_reason,omitempty"` + Status TurnStatus `json:"status"` + Error string `json:"error,omitempty"` + UpstreamTerminal string `json:"upstream_terminal,omitempty"` + DownstreamDelivered bool `json:"downstream_delivered,omitempty"` +} + +func (r TurnResult) HasCalls() bool { return len(r.Calls) > 0 } + +// Validate checks the canonical invariants every renderer relies on. +func (r TurnResult) Validate() error { + if r.Status == "" { + return fmt.Errorf("turn status required") + } + if r.Status == TurnCompleted || r.Status == TurnToolCalls { + if r.UpstreamTerminal != "done" { + return fmt.Errorf("successful turn requires upstream terminal done, got %q", r.UpstreamTerminal) + } + } + for index, call := range r.Calls { + if strings.TrimSpace(call.Name) == "" { + return fmt.Errorf("tool call %d has no name", index) + } + if call.Status == CallInvalid || call.Status == CallFailed || call.Status == CallTruncated { + return fmt.Errorf("tool call %d is %s: %s", index, call.Status, call.Error) + } + } + return nil +} diff --git a/internal/toolcall/native.go b/internal/toolcall/native.go new file mode 100644 index 000000000..fa8e09db9 --- /dev/null +++ b/internal/toolcall/native.go @@ -0,0 +1,1398 @@ +package toolcall + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" + "strconv" + "strings" +) + +// NativeLimits bounds the native Responses tool suffix that may be retained +// before it is validated. Every limit is checked before bytes are appended or +// copied, and the same limits are used by buffered and terminal-only turns. +type NativeLimits struct { + MaxFrames int + MaxBufferedBytes int + MaxArgumentBytes int + MaxCalls int + MaxJSONDepth int +} + +func DefaultNativeLimits() NativeLimits { + return NativeLimits{ + MaxFrames: 8192, + MaxBufferedBytes: 8 << 20, + MaxArgumentBytes: 1 << 20, + MaxCalls: 128, + MaxJSONDepth: 64, + } +} + +// NativeCall is one client-executed call after the visible stream and the +// terminal snapshot have been reconciled. +type NativeCall struct { + OutputIndex *int + ItemID string + CallID string + Type string + Name string + Namespace string + Arguments string + Input string + Custom bool +} + +// NativeDelivery is the immutable plan a native relay may write. It exists +// only after the stream calls and terminal snapshot have been reconciled. +type NativeDelivery struct { + Calls []NativeCall +} + +type nativeCall struct { + key string + itemID string + callID string + outputIndex *int + itemType string + name string + namespace string + arguments string + input string + completed bool + done map[string]nativeSnapshot + terminal *nativeTerminalCall + // deltaArgs / deltaInput are the exact concatenation of argument/input + // delta frames seen so far. A completion frame (arguments.done, + // output_item.done) must agree with this accumulated value; it may not + // silently replace the bytes the client was already going to receive. + deltaArgs string + deltaInput string + sawDelta bool +} + +type nativeSnapshot struct { + call *nativeCall + kind string + arguments string + input string +} + +type nativeEvent struct { + Type string `json:"type"` + Name string `json:"name"` + Namespace string `json:"namespace"` + ItemID string `json:"item_id"` + CallID string `json:"call_id"` + OutputIndex *int `json:"output_index"` + Delta string `json:"delta"` + Arguments json.RawMessage `json:"arguments"` + Input json.RawMessage `json:"input"` + Item *nativeItem `json:"item"` + Response json.RawMessage `json:"response"` +} + +type nativeItem struct { + ID string `json:"id"` + CallID string `json:"call_id"` + Type string `json:"type"` + Name string `json:"name"` + Namespace string `json:"namespace"` + Arguments json.RawMessage `json:"arguments"` + Input json.RawMessage `json:"input"` +} + +type nativeResponse struct { + ID string `json:"id"` + Status string `json:"status"` + Output []nativeItem `json:"output"` +} + +type nativeTerminalCall struct { + itemID string + callID string + outputIndex int + itemType string + name string + namespace string + arguments string + input string + spec Spec +} + +// NativeTurn is the single native Responses tool-round validator. It keeps +// independent output-index, output-item, and call-ID indexes and refuses to +// merge two already established calls through a late identity. +type NativeTurn struct { + request Request + limits NativeLimits + responseID string + started bool + frameCount int + bufferBytes int + calls map[string]*nativeCall + aliases map[string]string + order []string + snapshots []nativeSnapshot + finished bool + delivery *NativeDelivery + terminalErr error +} + +func NewNativeTurn(request Request, limits ...NativeLimits) *NativeTurn { + limit := DefaultNativeLimits() + if len(limits) > 0 { + limit = limits[0] + } + if limit.MaxFrames <= 0 { + limit.MaxFrames = DefaultNativeLimits().MaxFrames + } + if limit.MaxBufferedBytes <= 0 { + limit.MaxBufferedBytes = DefaultNativeLimits().MaxBufferedBytes + } + if limit.MaxArgumentBytes <= 0 { + limit.MaxArgumentBytes = DefaultNativeLimits().MaxArgumentBytes + } + if limit.MaxCalls <= 0 { + limit.MaxCalls = DefaultNativeLimits().MaxCalls + } + if limit.MaxJSONDepth <= 0 { + limit.MaxJSONDepth = DefaultNativeLimits().MaxJSONDepth + } + return &NativeTurn{ + request: request, limits: limit, + calls: make(map[string]*nativeCall), aliases: make(map[string]string), + } +} + +// Observe consumes one SSE JSON payload. eventName is the SSE event name when +// present; a payload whose JSON type conflicts with it is rejected. A response +// object embedded in any non-terminal event is inspected too, so a tool item +// cannot bypass reconciliation by arriving inside a control frame. +func (t *NativeTurn) Observe(eventName string, data []byte) error { + if t.finished { + return fmt.Errorf("native tool turn is already finished") + } + trimmed := bytes.TrimSpace(data) + if len(trimmed) == 0 || string(trimmed) == "[DONE]" { + return nil + } + var event nativeEvent + if err := json.Unmarshal(trimmed, &event); err != nil { + return fmt.Errorf("native event is not valid JSON: %w", err) + } + if event.Type == "" { + event.Type = strings.TrimSpace(eventName) + } + if event.Type == "" { + return nil + } + if eventName = strings.TrimSpace(eventName); eventName != "" && eventName != event.Type { + return fmt.Errorf("native SSE event %q conflicts with payload type %q", eventName, event.Type) + } + if t.started || nativeEventHasToolSignal(event) { + t.started = true + if t.frameCount+1 > t.limits.MaxFrames { + return fmt.Errorf("native SSE frame count exceeds %d", t.limits.MaxFrames) + } + if t.bufferBytes+len(data) > t.limits.MaxBufferedBytes { + return fmt.Errorf("native buffered bytes exceed %d", t.limits.MaxBufferedBytes) + } + t.frameCount++ + t.bufferBytes += len(data) + } + if len(event.Response) > 0 && !nativeTerminalEventType(event.Type) { + if err := t.observeResponseEnvelope(event.Response); err != nil { + return err + } + } + switch event.Type { + case "response.output_item.added", "response.output_item.done": + if event.Item == nil { + return nil + } + return t.observeItem(*event.Item, event.OutputIndex, event.Type == "response.output_item.done") + case "response.function_call_arguments.delta": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + return t.observeArgumentsDelta(itemID, callID, event.OutputIndex, name, namespace, event.Delta, false) + case "response.function_call_arguments.done": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + raw := event.Arguments + if len(bytes.TrimSpace(raw)) == 0 && event.Item != nil { + raw = event.Item.Arguments + } + return t.observeArgumentsDone(itemID, callID, event.OutputIndex, name, namespace, raw, false) + case "response.custom_tool_call_input.delta": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + return t.observeArgumentsDelta(itemID, callID, event.OutputIndex, name, namespace, event.Delta, true) + case "response.custom_tool_call_input.done": + name, namespace := eventArgumentIdentity(event) + itemID, callID := eventArgumentIDs(event) + raw := event.Input + if len(bytes.TrimSpace(raw)) == 0 && event.Item != nil { + raw = event.Item.Input + } + return t.observeArgumentsDone(itemID, callID, event.OutputIndex, name, namespace, raw, true) + } + return nil +} + +func eventArgumentIDs(event nativeEvent) (string, string) { + itemID, callID := event.ItemID, event.CallID + if event.Item != nil { + if itemID == "" { + itemID = event.Item.ID + } + if callID == "" { + callID = event.Item.CallID + } + } + return itemID, callID +} + +func eventArgumentIdentity(event nativeEvent) (string, string) { + name, namespace := event.Name, event.Namespace + if event.Item != nil { + if name == "" { + name = event.Item.Name + } + if namespace == "" { + namespace = event.Item.Namespace + } + } + return name, namespace +} + +func nativeTerminalEventType(kind string) bool { + switch kind { + case "response.completed", "response.incomplete", "response.failed", "error": + return true + } + return false +} + +func (t *NativeTurn) observeResponseEnvelope(raw json.RawMessage) error { + var response nativeResponse + if err := json.Unmarshal(raw, &response); err != nil { + return fmt.Errorf("native response envelope is invalid: %w", err) + } + if response.ID != "" { + if t.responseID != "" && t.responseID != response.ID { + return fmt.Errorf("native response id changed from %q to %q", t.responseID, response.ID) + } + t.responseID = response.ID + } + for index := range response.Output { + item := response.Output[index] + if !nativeKnownItemType(item.Type) { + return fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + continue + } + itemIndex := index + completed := false + if item.Type == "function_call" { + arguments, hasArguments, err := nativeRawString(item.Arguments, false) + if err != nil { + return err + } + completed = hasArguments && strings.TrimSpace(arguments) != "" + } else { + input, hasInput, err := nativeRawInput(item.Input) + if err != nil { + return err + } + completed = hasInput && input != "" + } + if err := t.observeItem(item, &itemIndex, completed); err != nil { + return err + } + } + return nil +} + +func (t *NativeTurn) observeItem(item nativeItem, outputIndex *int, completed bool) error { + if !nativeKnownItemType(item.Type) { + return fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + return nil + } + call, err := t.resolve(item.ID, item.CallID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(item.ID, item.CallID, outputIndex); err != nil { + return err + } + if err := call.mergeName("", item.Namespace, item.Type); err != nil { + return err + } + if err := t.mergeEventName(call, item.Name, item.Namespace, item.Type == "custom_tool_call"); err != nil { + return err + } + arguments, hasArguments, err := nativeRawString(item.Arguments, false) + if err != nil { + return err + } + input, hasInput, err := nativeRawInput(item.Input) + if err != nil { + return err + } + // Check argument/input size and the accumulated delta on every item frame, + // not only on delta/done events. An oversized or contradictory item frame is + // permanently fatal for this call: a later same-identity frame with smaller + // valid arguments must not be allowed to rewrite it into a successful turn. + if len([]byte(arguments)) > t.limits.MaxArgumentBytes || len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if hasArguments && call.sawDelta && call.deltaArgs != arguments { + return fmt.Errorf("native tool call %q item arguments differ from the accumulated deltas", call.name) + } + if hasInput && call.sawDelta && call.deltaInput != input { + return fmt.Errorf("native tool call %q item input differs from the accumulated deltas", call.name) + } + if completed { + if item.Type == "function_call" { + if !hasArguments { + return fmt.Errorf("native tool call %q completed without arguments", call.name) + } + } else if !hasInput { + return fmt.Errorf("native custom tool call %q completed without input", call.name) + } + if err := t.validateSnapshotValues(call, string(item.Type), arguments, input, item.Type == "function_call"); err != nil { + return err + } + return t.addSnapshot(call, string(item.Type), arguments, input) + } + if hasArguments { + call.arguments = arguments + } + if hasInput { + call.input = input + } + return nil +} + +func (t *NativeTurn) observeArgumentsDelta(itemID, callID string, outputIndex *int, name, namespace, delta string, custom bool) error { + call, err := t.resolve(itemID, callID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(itemID, callID, outputIndex); err != nil { + return err + } + if err := t.mergeEventName(call, name, namespace, custom); err != nil { + return err + } + if call.completed { + return fmt.Errorf("native tool call %q received a delta after completion", call.name) + } + if len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if custom { + if len([]byte(delta)) > t.limits.MaxArgumentBytes || len([]byte(call.deltaInput))+len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q input exceeds the limit", call.name) + } + if call.itemType != "" && call.itemType != "custom_tool_call" { + return fmt.Errorf("native tool call %q changed type from %q to custom_tool_call", call.name, call.itemType) + } + call.itemType = "custom_tool_call" + call.sawDelta = true + call.deltaInput += delta + call.input += delta + return nil + } + if len([]byte(delta)) > t.limits.MaxArgumentBytes || len([]byte(call.deltaArgs))+len([]byte(delta)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if call.itemType != "" && call.itemType != "function_call" { + return fmt.Errorf("native tool call %q changed type from %q to function_call", call.name, call.itemType) + } + call.itemType = "function_call" + call.sawDelta = true + call.deltaArgs += delta + call.arguments += delta + return nil +} + +func (t *NativeTurn) observeArgumentsDone(itemID, callID string, outputIndex *int, name, namespace string, raw json.RawMessage, custom bool) error { + call, err := t.resolve(itemID, callID, outputIndex) + if err != nil { + return err + } + if err := call.mergeIdentity(itemID, callID, outputIndex); err != nil { + return err + } + if err := t.mergeEventName(call, name, namespace, custom); err != nil { + return err + } + itemType := "function_call" + if custom { + itemType = "custom_tool_call" + } + if call.itemType != "" && call.itemType != itemType { + return fmt.Errorf("native tool call %q changed type from %q to %q", call.name, call.itemType, itemType) + } + call.itemType = itemType + if custom { + input, hasInput, err := nativeRawInput(raw) + if err != nil { + return err + } + if !hasInput { + return fmt.Errorf("native custom tool call %q completed without input", call.name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q input exceeds the limit", call.name) + } + if call.sawDelta && call.deltaInput != input { + return fmt.Errorf("native custom tool call %q completion input differs from the accumulated deltas", call.name) + } + if err := t.validateSnapshotValues(call, itemType, "", input, false); err != nil { + return err + } + return t.addSnapshot(call, "custom_tool_call_input.done", "", input) + } + text, hasArguments, err := nativeRawString(raw, true) + if err != nil { + return err + } + if !hasArguments { + return fmt.Errorf("native tool call %q completed without arguments", call.name) + } + if len([]byte(text)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q arguments exceed the limit", call.name) + } + if call.sawDelta && !semanticJSONEqual(call.deltaArgs, text) { + return fmt.Errorf("native tool call %q completion arguments differ from the accumulated deltas", call.name) + } + if err := t.validateSnapshotValues(call, itemType, text, "", true); err != nil { + return err + } + return t.addSnapshot(call, "function_call_arguments.done", text, "") +} + +func (t *NativeTurn) addSnapshot(call *nativeCall, kind, arguments, input string) error { + if len([]byte(arguments)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native tool call %q completed arguments exceed the limit", call.name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return fmt.Errorf("native custom tool call %q completed input exceeds the limit", call.name) + } + if call.completed && call.done == nil { + return fmt.Errorf("native tool call %q has inconsistent completion state", call.name) + } + if call.done == nil { + call.done = make(map[string]nativeSnapshot) + } + if previous, exists := call.done[kind]; exists { + if !snapshotEqual(previous, nativeSnapshot{call: call, kind: kind, arguments: arguments, input: input}) { + return fmt.Errorf("native tool call %q repeated completion with different content", call.name) + } + return nil + } + snapshot := nativeSnapshot{call: call, kind: kind, arguments: arguments, input: input} + if strings.Contains(kind, "custom") { + call.input = input + } else { + call.arguments = arguments + } + call.done[kind] = snapshot + call.completed = true + t.snapshots = append(t.snapshots, snapshot) + return nil +} + +func (t *NativeTurn) validateSnapshotValues(call *nativeCall, itemType, arguments, input string, function bool) error { + if function { + if err := validateStrictJSONObject(arguments, t.limits.MaxJSONDepth); err != nil { + return fmt.Errorf("native tool call %q arguments are invalid: %w", call.name, err) + } + } else if len(bytes.TrimSpace([]byte(call.name))) == 0 { + // A custom completion can arrive before the item name is bound. The + // terminal response is the authority for its identity and declaration, + // and Finish rejects the turn if no such call exists. + return nil + } + if len(bytes.TrimSpace([]byte(call.name))) > 0 { + spec, err := resolveNativeSpec(t.request, call.name, call.namespace, itemType) + if err != nil { + return err + } + if function { + if spec.Custom { + return fmt.Errorf("native tool call %q is declared as custom but arrived as function_call", call.name) + } + value, err := parseStrictJSONObject(arguments, t.limits.MaxJSONDepth) + if err != nil { + return err + } + if err := validateNativeSpecValue(spec, value); err != nil { + return err + } + } else if !spec.Custom { + return fmt.Errorf("native tool call %q is declared as function but arrived as custom_tool_call", call.name) + } + } + return nil +} + +func (t *NativeTurn) resolve(itemID, callID string, outputIndex *int) (*nativeCall, error) { + if t.calls == nil { + t.calls = make(map[string]*nativeCall) + t.aliases = make(map[string]string) + } + var matched []string + for _, alias := range nativeAliases(itemID, callID, outputIndex) { + if key, ok := t.aliases[alias]; ok && !containsString(matched, key) { + matched = append(matched, key) + } + } + if len(matched) > 1 { + return nil, fmt.Errorf("native tool identities point to different calls: %s", strings.Join(matched, ", ")) + } + if len(matched) == 1 { + return t.calls[matched[0]], nil + } + key := "item:" + itemID + if itemID == "" { + key = "call:" + callID + } + if itemID == "" && callID == "" && outputIndex != nil { + key = "index:" + strconv.Itoa(*outputIndex) + } + if key == "item:" || key == "call:" { + return nil, fmt.Errorf("native tool event has no stable identity") + } + if _, exists := t.calls[key]; exists { + return nil, fmt.Errorf("native tool identity %q was reused", key) + } + call := &nativeCall{key: key, done: make(map[string]nativeSnapshot)} + t.calls[key] = call + t.order = append(t.order, key) + for _, alias := range nativeAliases(itemID, callID, outputIndex) { + if existing, ok := t.aliases[alias]; ok && existing != key { + return nil, fmt.Errorf("native tool identity %q is already bound to another call", alias) + } + t.aliases[alias] = key + } + if len(t.order) > t.limits.MaxCalls { + return nil, fmt.Errorf("native tool call count exceeds %d", t.limits.MaxCalls) + } + return call, nil +} + +func (c *nativeCall) mergeIdentity(itemID, callID string, outputIndex *int) error { + if itemID != "" { + if c.itemID != "" && c.itemID != itemID { + return fmt.Errorf("native tool call item id changed from %q to %q", c.itemID, itemID) + } + c.itemID = itemID + } + if callID != "" { + if c.callID != "" && c.callID != callID { + return fmt.Errorf("native tool call id changed from %q to %q", c.callID, callID) + } + c.callID = callID + } + if outputIndex != nil { + if c.outputIndex != nil && *c.outputIndex != *outputIndex { + return fmt.Errorf("native tool call %q moved output index from %d to %d", c.name, *c.outputIndex, *outputIndex) + } + c.outputIndex = outputIndex + } + return nil +} + +func (c *nativeCall) mergeName(name, namespace, itemType string) error { + if itemType != "" { + if c.itemType != "" && c.itemType != itemType { + return fmt.Errorf("native tool call changed type from %q to %q", c.itemType, itemType) + } + c.itemType = itemType + } + if name != "" { + if c.name != "" && c.name != name { + return fmt.Errorf("native tool call changed name from %q to %q", c.name, name) + } + c.name = name + } + if namespace != "" { + if c.namespace != "" && c.namespace != namespace { + return fmt.Errorf("native tool call changed namespace from %q to %q", c.namespace, namespace) + } + c.namespace = namespace + } + return nil +} + +// mergeEventName binds a name carried by an argument event. Argument events +// often arrive after an added item and may spell the same declared tool either +// as its flattened wire name or as namespace + original name; that alias is +// legal. A different declared tool is an identity conflict and must fail. +func (t *NativeTurn) mergeEventName(call *nativeCall, name, namespace string, custom bool) error { + name = strings.TrimSpace(name) + namespace = strings.TrimSpace(namespace) + itemType := "function_call" + if custom { + itemType = "custom_tool_call" + } + if namespace != "" { + if call.namespace != "" && call.namespace != namespace { + return fmt.Errorf("native tool call changed namespace from %q to %q", call.namespace, namespace) + } + if call.name != "" { + if _, err := resolveNativeSpec(t.request, call.name, namespace, itemType); err != nil { + return err + } + } + call.namespace = namespace + } + if name == "" { + return nil + } + if call.name == "" { + call.name = name + return nil + } + if call.name == name { + return nil + } + streamSpec, streamErr := resolveNativeSpec(t.request, call.name, call.namespace, itemType) + eventSpec, eventErr := resolveNativeSpec(t.request, name, namespace, itemType) + if streamErr != nil || eventErr != nil || streamSpec.Name != eventSpec.Name { + return fmt.Errorf("native tool call changed name from %q to %q", call.name, name) + } + call.name = streamSpec.Name + return nil +} + +func snapshotEqual(a, b nativeSnapshot) bool { + if strings.Contains(a.kind, "custom") { + return a.input == b.input + } + return semanticJSONEqual(a.arguments, b.arguments) +} + +func nativeAliases(itemID, callID string, outputIndex *int) []string { + aliases := make([]string, 0, 3) + if itemID != "" { + aliases = append(aliases, "item:"+itemID) + } + if callID != "" { + aliases = append(aliases, "call:"+callID) + } + if outputIndex != nil { + aliases = append(aliases, "index:"+strconv.Itoa(*outputIndex)) + } + return aliases +} + +func nativeKnownItemType(kind string) bool { + switch kind { + case "", "message", "reasoning", "function_call", "custom_tool_call", + "mcp_call", "local_shell_call", "web_search_call", "file_search_call", + "code_interpreter_call", "image_generation_call": + return true + } + return false +} + +func nativeEventHasToolSignal(event nativeEvent) bool { + switch event.Type { + case "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done": + return true + } + if strings.Contains(event.Type, "mcp_call") { + return true + } + if event.Item != nil && (event.Item.Type == "function_call" || event.Item.Type == "custom_tool_call" || + event.Item.Type == "local_shell_call" || strings.HasSuffix(event.Item.Type, "_call")) { + return true + } + if len(event.Response) > 0 { + var response nativeResponse + if json.Unmarshal(event.Response, &response) == nil { + for _, item := range response.Output { + if item.Type == "function_call" || item.Type == "custom_tool_call" || + item.Type == "local_shell_call" || strings.HasSuffix(item.Type, "_call") { + return true + } + } + } + } + return false +} + +func containsString(values []string, value string) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + +func nativeRawString(raw json.RawMessage, required bool) (string, bool, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + if required { + return "", false, fmt.Errorf("string field is missing") + } + return "", false, nil + } + var value string + if err := json.Unmarshal(trimmed, &value); err != nil { + return "", true, fmt.Errorf("string field is not a string: %w", err) + } + return value, true, nil +} + +func nativeRawInput(raw json.RawMessage) (string, bool, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return "", false, nil + } + var value string + if err := json.Unmarshal(trimmed, &value); err != nil { + return "", true, fmt.Errorf("input field is not a string: %w", err) + } + return value, true, nil +} + +func validateNativeSpecValue(spec Spec, value map[string]any) error { + if len(spec.Parameters) > 0 && string(spec.Parameters) != "null" { + var schema any + if err := json.Unmarshal(spec.Parameters, &schema); err != nil { + return fmt.Errorf("tool %q schema is invalid: %w", spec.Name, err) + } + if err := validateValue(schema, schema, value, 0); err != nil { + return fmt.Errorf("tool %q arguments do not match schema: %w", spec.Name, err) + } + } + return nil +} + +func resolveNativeSpec(request Request, name, namespace, itemType string) (Spec, error) { + name = strings.TrimSpace(name) + if name == "" { + return Spec{}, fmt.Errorf("native tool call has no name") + } + if len(request.Specs) == 0 { + return Spec{}, fmt.Errorf("native response delivered tool call %q without a declared tool", name) + } + var candidates []Spec + for _, spec := range request.Specs { + if spec.Name != name { + continue + } + if namespace != "" && spec.Namespace != namespace { + continue + } + candidates = append(candidates, spec) + } + if len(candidates) == 0 && namespace != "" { + for _, spec := range request.Specs { + if spec.Namespace == namespace && (spec.OriginalName == name || spec.Name == name) { + candidates = append(candidates, spec) + } + } + } + if len(candidates) == 0 && namespace == "" { + for _, spec := range request.Specs { + if spec.OriginalName == name { + candidates = append(candidates, spec) + } + } + } + if len(candidates) == 0 { + return Spec{}, fmt.Errorf("native response delivered undeclared tool call %q", name) + } + if len(candidates) > 1 { + return Spec{}, fmt.Errorf("native tool name %q is ambiguous across declarations", name) + } + spec := candidates[0] + custom := itemType == "custom_tool_call" + if spec.Custom != custom { + return Spec{}, fmt.Errorf("native tool call %q has the wrong tool type for its declaration", name) + } + return spec, nil +} + +func validateStrictJSONObject(text string, maxDepth int) error { + if strings.TrimSpace(text) == "" { + return fmt.Errorf("arguments are empty") + } + if _, err := parseStrictJSONObject(text, maxDepth); err != nil { + return err + } + return nil +} + +func parseStrictJSONObject(text string, maxDepth int) (map[string]any, error) { + if strings.TrimSpace(text) == "" { + return nil, fmt.Errorf("arguments are empty") + } + decoder := json.NewDecoder(strings.NewReader(text)) + decoder.UseNumber() + value, err := decodeStrictJSONValue(decoder, 0, maxDepth) + if err != nil { + return nil, err + } + object, ok := value.(map[string]any) + if !ok { + return nil, fmt.Errorf("arguments must be a JSON object") + } + if _, err := decoder.Token(); err != io.EOF { + if err == nil { + return nil, fmt.Errorf("arguments contain a trailing JSON value") + } + return nil, fmt.Errorf("arguments contain trailing data: %w", err) + } + return object, nil +} + +func decodeStrictJSONValue(decoder *json.Decoder, depth, maxDepth int) (any, error) { + if depth > maxDepth { + return nil, fmt.Errorf("arguments nesting exceeds %d levels", maxDepth) + } + token, err := decoder.Token() + if err != nil { + return nil, err + } + switch value := token.(type) { + case json.Delim: + switch value { + case '{': + object := make(map[string]any) + for decoder.More() { + keyToken, err := decoder.Token() + if err != nil { + return nil, err + } + key, ok := keyToken.(string) + if !ok { + return nil, fmt.Errorf("object key is not a string") + } + if _, exists := object[key]; exists { + return nil, fmt.Errorf("arguments contain duplicate object key %q", key) + } + child, err := decodeStrictJSONValue(decoder, depth+1, maxDepth) + if err != nil { + return nil, err + } + object[key] = child + } + end, err := decoder.Token() + if err != nil { + return nil, err + } + if end != json.Delim('}') { + return nil, fmt.Errorf("object is not closed") + } + return object, nil + case '[': + var array []any + for decoder.More() { + child, err := decodeStrictJSONValue(decoder, depth+1, maxDepth) + if err != nil { + return nil, err + } + array = append(array, child) + } + end, err := decoder.Token() + if err != nil { + return nil, err + } + if end != json.Delim(']') { + return nil, fmt.Errorf("array is not closed") + } + return array, nil + default: + return nil, fmt.Errorf("unexpected JSON delimiter %q", value) + } + default: + return value, nil + } +} + +func semanticJSONEqual(left, right string) bool { + leftValue, err := parseStrictJSONValue(left) + if err != nil { + return false + } + rightValue, err := parseStrictJSONValue(right) + if err != nil { + return false + } + return reflect.DeepEqual(leftValue, rightValue) +} + +func parseStrictJSONValue(text string) (any, error) { + decoder := json.NewDecoder(strings.NewReader(text)) + decoder.UseNumber() + value, err := decodeStrictJSONValue(decoder, 0, 64) + if err != nil { + return nil, err + } + if _, err := decoder.Token(); err != io.EOF { + if err == nil { + return nil, fmt.Errorf("trailing JSON value") + } + return nil, err + } + return value, nil +} + +// Finish validates the terminal response once. After a successful Finish the +// turn accepts no more deltas and repeated calls return the same plan without +// producing a second delivery or settlement. +func (t *NativeTurn) Finish(responseRaw []byte, finish string) (*NativeDelivery, error) { + if t.finished { + return t.delivery, t.terminalErr + } + t.finished = true + delivery, err := t.ValidateTerminal(responseRaw, finish) + t.delivery, t.terminalErr = delivery, err + return delivery, err +} + +// ValidateTerminal reconciles every visible call and every completed snapshot +// with the terminal response object. A successful result is the only value +// from which the relay may construct its delivery. +func (t *NativeTurn) ValidateTerminal(responseRaw []byte, finish string) (*NativeDelivery, error) { + if len(responseRaw) > t.limits.MaxBufferedBytes { + return nil, fmt.Errorf("native terminal response exceeds the buffered byte limit") + } + var response nativeResponse + if err := json.Unmarshal(responseRaw, &response); err != nil { + return nil, fmt.Errorf("native terminal response is invalid: %w", err) + } + if response.ID != "" { + if t.responseID != "" && t.responseID != response.ID { + return nil, fmt.Errorf("native response id changed from %q to %q", t.responseID, response.ID) + } + t.responseID = response.ID + } + if strings.TrimSpace(finish) == "" { + switch response.Status { + case "incomplete": + finish = "length" + case "failed", "error": + finish = "error" + default: + finish = "stop" + } + } + // A terminal SSE event and the response object it carries must agree. An + // event claiming completion cannot smuggle status:"incomplete" (which would + // otherwise be treated as a usable turn), and an incomplete/errored event + // cannot be reclassified by a forged status:"completed" body. Empty or + // in_progress status is left to the existing finish/body checks below. + if err := validateNativeTerminalAgreement(finish, response.Status); err != nil { + return nil, err + } + terminal, err := t.parseTerminalCalls(response) + if err != nil { + return nil, err + } + if len(terminal) > t.limits.MaxCalls { + return nil, fmt.Errorf("native tool call count exceeds %d", t.limits.MaxCalls) + } + if finish == "length" { + if len(t.order) > 0 || len(terminal) > 0 { + return nil, fmt.Errorf("incomplete native response cannot deliver a tool call") + } + return &NativeDelivery{}, nil + } + if finish == "error" || response.Status == "failed" || response.Status == "error" { + return nil, fmt.Errorf("failed native response cannot deliver a tool call") + } + if len(t.order) == 0 { + if err := validateNativeRoundConstraints(t.request, terminal); err != nil { + return nil, err + } + return nativeDeliveryFromTerminal(terminal), nil + } + if len(terminal) == 0 { + return nil, fmt.Errorf("native terminal response omitted visible tool calls") + } + calls, err := t.reconcile(terminal) + if err != nil { + return nil, err + } + if err := validateNativeRoundConstraints(t.request, calls); err != nil { + return nil, err + } + delivery := &NativeDelivery{Calls: make([]NativeCall, 0, len(calls))} + for _, call := range calls { + callCopy := NativeCall{ + ItemID: call.itemID, CallID: call.callID, Type: call.itemType, + Name: call.name, Namespace: call.namespace, Arguments: call.arguments, + Input: call.input, Custom: call.itemType == "custom_tool_call", + } + if call.outputIndex >= 0 { + index := call.outputIndex + callCopy.OutputIndex = &index + } + delivery.Calls = append(delivery.Calls, callCopy) + } + return delivery, nil +} + +func (t *NativeTurn) parseTerminalCalls(response nativeResponse) ([]nativeTerminalCall, error) { + var calls []nativeTerminalCall + byItem := make(map[string]int) + byCall := make(map[string]int) + byIndex := make(map[int]int) + for index := range response.Output { + item := response.Output[index] + if !nativeKnownItemType(item.Type) { + return nil, fmt.Errorf("native response carries unsupported item type %q", item.Type) + } + if item.Type != "function_call" && item.Type != "custom_tool_call" { + continue + } + if strings.TrimSpace(item.CallID) == "" { + return nil, fmt.Errorf("native terminal tool call %q has no call id", item.Name) + } + if item.ID != "" { + if previous, exists := byItem[item.ID]; exists { + return nil, fmt.Errorf("native terminal output repeats item id %q (positions %d and %d)", item.ID, previous, index) + } + byItem[item.ID] = len(calls) + } + if item.CallID != "" { + if previous, exists := byCall[item.CallID]; exists { + return nil, fmt.Errorf("native terminal output repeats call id %q (positions %d and %d)", item.CallID, previous, index) + } + byCall[item.CallID] = len(calls) + } + if previous, exists := byIndex[index]; exists { + return nil, fmt.Errorf("native terminal output reuses output position %d for calls %d and %d", index, previous, len(calls)) + } + byIndex[index] = len(calls) + spec, err := resolveNativeSpec(t.request, item.Name, item.Namespace, item.Type) + if err != nil { + return nil, err + } + arguments := "" + input := "" + hasInput := false + if item.Type == "function_call" { + arguments, _, err = nativeRawString(item.Arguments, true) + if err != nil { + return nil, fmt.Errorf("native tool call %q arguments are invalid: %w", item.Name, err) + } + if len([]byte(arguments)) > t.limits.MaxArgumentBytes { + return nil, fmt.Errorf("native tool call %q arguments exceed the limit", item.Name) + } + value, err := parseStrictJSONObject(arguments, t.limits.MaxJSONDepth) + if err != nil { + return nil, fmt.Errorf("native tool call %q arguments are invalid: %w", item.Name, err) + } + if err := validateNativeSpecValue(spec, value); err != nil { + return nil, err + } + } else { + input, hasInput, err = nativeRawInput(item.Input) + if err != nil { + return nil, fmt.Errorf("native custom tool call %q input is invalid: %w", item.Name, err) + } + if !hasInput { + return nil, fmt.Errorf("native custom tool call %q completed without input", item.Name) + } + if len([]byte(input)) > t.limits.MaxArgumentBytes { + return nil, fmt.Errorf("native custom tool call %q input exceeds the limit", item.Name) + } + } + calls = append(calls, nativeTerminalCall{ + itemID: item.ID, callID: item.CallID, outputIndex: index, + itemType: item.Type, name: item.Name, namespace: item.Namespace, + arguments: arguments, input: input, spec: spec, + }) + } + return calls, nil +} + +func (t *NativeTurn) reconcile(terminal []nativeTerminalCall) ([]nativeTerminalCall, error) { + byItem := make(map[string]int) + byCall := make(map[string]int) + byIndex := make(map[int]int) + byName := make(map[string][]int) + for index := range terminal { + call := terminal[index] + if call.itemID != "" { + byItem[call.itemID] = index + } + if call.callID != "" { + byCall[call.callID] = index + } + byIndex[call.outputIndex] = index + byName[call.name] = appendUniqueIndex(byName[call.name], index) + if call.spec.Name != "" && call.spec.Name != call.name { + byName[call.spec.Name] = appendUniqueIndex(byName[call.spec.Name], index) + } + if call.spec.OriginalName != "" && call.spec.OriginalName != call.name { + byName[call.spec.OriginalName] = appendUniqueIndex(byName[call.spec.OriginalName], index) + } + } + matched := make(map[int]bool) + for _, key := range t.order { + call := t.calls[key] + var candidates []int + for _, alias := range nativeAliases(call.itemID, call.callID, call.outputIndex) { + var index int + var ok bool + switch { + case strings.HasPrefix(alias, "item:"): + index, ok = byItem[strings.TrimPrefix(alias, "item:")] + case strings.HasPrefix(alias, "call:"): + index, ok = byCall[strings.TrimPrefix(alias, "call:")] + case strings.HasPrefix(alias, "index:"): + position, err := strconv.Atoi(strings.TrimPrefix(alias, "index:")) + if err == nil { + index, ok = byIndex[position] + } + } + if ok && !containsInt(candidates, index) { + candidates = append(candidates, index) + } + } + if len(candidates) == 0 && call.name != "" { + candidates = byName[call.name] + if len(candidates) == 0 { + if spec, err := resolveNativeSpec(t.request, call.name, call.namespace, call.itemType); err == nil { + candidates = byName[spec.Name] + } + } + } + if len(candidates) != 1 { + return nil, fmt.Errorf("native visible tool call %q does not map to exactly one terminal call", call.name) + } + index := candidates[0] + if matched[index] { + return nil, fmt.Errorf("native terminal call at position %d matches more than one visible call", terminal[index].outputIndex) + } + matched[index] = true + if err := t.reconcileNativeCall(call, terminal[index]); err != nil { + return nil, err + } + call.terminal = &terminal[index] + } + if len(matched) != len(terminal) { + return nil, fmt.Errorf("native terminal response contains tool calls absent from the visible stream") + } + for _, snapshot := range t.snapshots { + if snapshot.call.terminal == nil { + return nil, fmt.Errorf("native completion snapshot has no terminal call") + } + terminalCall := *snapshot.call.terminal + if strings.Contains(snapshot.kind, "custom") { + if snapshot.input != terminalCall.input { + return nil, fmt.Errorf("native custom tool call %q completed with different input", snapshot.call.name) + } + continue + } + if !semanticJSONEqual(snapshot.arguments, terminalCall.arguments) { + return nil, fmt.Errorf("native tool call %q completed with arguments different from the terminal snapshot", snapshot.call.name) + } + } + return terminal, nil +} + +func (t *NativeTurn) reconcileNativeCall(call *nativeCall, terminal nativeTerminalCall) error { + if call.itemID != "" && terminal.itemID != "" && call.itemID != terminal.itemID { + return fmt.Errorf("native tool call item id changed from %q to %q", call.itemID, terminal.itemID) + } + if call.callID != "" && terminal.callID != "" && call.callID != terminal.callID { + return fmt.Errorf("native tool call id changed from %q to %q", call.callID, terminal.callID) + } + if call.itemType != "" && call.itemType != terminal.itemType { + return fmt.Errorf("native tool call %q changed type from %q to %q", call.name, call.itemType, terminal.itemType) + } + if call.name == "" { + call.name = terminal.name + } + if terminal.name != "" && call.name != terminal.name { + streamSpec, streamErr := resolveNativeSpec(t.request, call.name, call.namespace, call.itemType) + terminalSpec, terminalErr := resolveNativeSpec(t.request, terminal.name, terminal.namespace, terminal.itemType) + if streamErr != nil || terminalErr != nil || streamSpec.Name != terminalSpec.Name { + return fmt.Errorf("native tool call name changed from %q to %q", call.name, terminal.name) + } + } + if call.namespace != "" && terminal.namespace != "" && call.namespace != terminal.namespace { + return fmt.Errorf("native tool call namespace changed from %q to %q", call.namespace, terminal.namespace) + } + if call.outputIndex != nil && *call.outputIndex != terminal.outputIndex { + return fmt.Errorf("native tool call %q is at output index %d in the stream but %d in the terminal response", call.name, *call.outputIndex, terminal.outputIndex) + } + if call.itemID == "" { + call.itemID = terminal.itemID + } + if call.callID == "" { + call.callID = terminal.callID + } + if call.itemType == "" { + call.itemType = terminal.itemType + } + if call.namespace == "" { + call.namespace = terminal.namespace + } + if call.outputIndex == nil { + index := terminal.outputIndex + call.outputIndex = &index + } + if call.itemType == "custom_tool_call" { + if call.completed { + if call.input != terminal.input { + return fmt.Errorf("native custom tool call %q completed with different input", call.name) + } + } else if !strings.HasPrefix(terminal.input, call.input) { + return fmt.Errorf("native custom tool call %q visible input is not a prefix of the terminal input", call.name) + } + call.input = terminal.input + return nil + } + if call.completed { + if call.arguments != "" && !semanticJSONEqual(call.arguments, terminal.arguments) { + return fmt.Errorf("native tool call %q completed with arguments different from the terminal snapshot", call.name) + } + } else if !strings.HasPrefix(terminal.arguments, call.arguments) { + return fmt.Errorf("native tool call %q visible arguments are not a prefix of the terminal arguments", call.name) + } + call.arguments = terminal.arguments + return nil +} + +func containsInt(values []int, value int) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + +func appendUniqueIndex(values []int, value int) []int { + if containsInt(values, value) { + return values + } + return append(values, value) +} + +// validateNativeTerminalAgreement rejects a mismatch between the SSE terminal +// event's finish and the status inside the response object. The event is the +// authority; a disagreeing body is a malformed or forged terminal. +func validateNativeTerminalAgreement(finish, status string) error { + status = strings.ToLower(strings.TrimSpace(status)) + if status == "" { + return nil + } + switch finish { + case "stop": + if status == "incomplete" || status == "failed" || status == "error" || status == "in_progress" { + return fmt.Errorf("native terminal event claims completion but response status is %q", status) + } + case "length": + if status == "completed" || status == "failed" || status == "error" { + return fmt.Errorf("native terminal event claims an incomplete turn but response status is %q", status) + } + case "error": + if status == "completed" { + return fmt.Errorf("native terminal event claims failure but response status is %q", status) + } + } + return nil +} + +func validateNativeRoundConstraints(request Request, calls []nativeTerminalCall) error { + if len(calls) == 0 { + if request.Choice.Mode == ChoiceRequired || request.Choice.Mode == ChoiceNamed { + return fmt.Errorf("native response did not deliver the required tool call") + } + return nil + } + if !request.HasTools() { + return fmt.Errorf("native response delivered tool calls without any declared tool") + } + switch request.Choice.Mode { + case ChoiceNone: + return fmt.Errorf("native response delivered a tool call while tool_choice is none") + case ChoiceRequired: + if len(calls) == 0 { + return fmt.Errorf("native response did not deliver the required tool call") + } + case ChoiceNamed: + if len(calls) != 1 { + return fmt.Errorf("native named tool_choice requires exactly one call, got %d", len(calls)) + } + named := calls[0] + if request.Choice.Name != named.name && request.Choice.Name != named.spec.Name && request.Choice.Name != named.spec.OriginalName { + return fmt.Errorf("native response delivered %q while tool_choice names %q", named.name, request.Choice.Name) + } + } + if request.Policy.Parallel != nil && !*request.Policy.Parallel && len(calls) > 1 { + return fmt.Errorf("native response delivered %d calls while parallel_tool_calls is false", len(calls)) + } + if request.Policy.MaxCalls > 0 && len(calls) > request.Policy.MaxCalls { + return fmt.Errorf("native response delivered %d calls, exceeding max_calls %d", len(calls), request.Policy.MaxCalls) + } + return nil +} + +func nativeDeliveryFromTerminal(calls []nativeTerminalCall) *NativeDelivery { + delivery := &NativeDelivery{Calls: make([]NativeCall, 0, len(calls))} + for _, call := range calls { + index := call.outputIndex + delivery.Calls = append(delivery.Calls, NativeCall{ + OutputIndex: &index, ItemID: call.itemID, CallID: call.callID, + Type: call.itemType, Name: call.name, Namespace: call.namespace, + Arguments: call.arguments, Input: call.input, + Custom: call.itemType == "custom_tool_call", + }) + } + return delivery +} + +// ValidateNativeResponsesOutput validates a terminal response body without a +// visible stream, inferring the finish reason from the response object. Prefer +// ValidateNativeResponsesTurn when the SSE terminal event is available: the +// event type is authoritative and cannot be spoofed by a disagreeing body. +func ValidateNativeResponsesOutput(raw json.RawMessage, request Request) error { + return ValidateNativeResponsesTurn(raw, request, "") +} + +// ValidateNativeResponsesTurn validates a terminal response body using the SSE +// terminal event's finish reason as the authoritative outcome. A response that +// claims status:"completed" while the event is response.incomplete (or vice +// versa) is rejected, so a non-stream collector cannot accept a truncated or +// forged turn that the streaming relay already refuses. +func ValidateNativeResponsesTurn(raw json.RawMessage, request Request, eventFinish string) error { + turn := NewNativeTurn(request) + finish := strings.TrimSpace(eventFinish) + if finish == "" { + var response nativeResponse + if json.Unmarshal(raw, &response) == nil { + switch response.Status { + case "incomplete": + finish = "length" + case "failed", "error": + finish = "error" + } + } + } + _, err := turn.Finish(raw, finish) + return err +} diff --git a/internal/toolcall/native_identity_test.go b/internal/toolcall/native_identity_test.go new file mode 100644 index 000000000..9a9335c54 --- /dev/null +++ b/internal/toolcall/native_identity_test.go @@ -0,0 +1,81 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestNativeTurnAcceptsLateBindingCallIDAndItem(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","call_id":"call_1","name":"lookup","delta":"{}"}`)); err != nil { + t.Fatal(err) + } + if err := turn.Observe("response.output_item.done", []byte(`{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`)); err != nil { + t.Fatal(err) + } + if _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop"); err != nil { + t.Fatal(err) + } +} + +func TestNativeTurnAcceptsNonEmptyCustomCompletion(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"custom","name":"exec"}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`)); err != nil { + t.Fatal(err) + } + if err := turn.Observe("response.custom_tool_call_input.done", []byte(`{"type":"response.custom_tool_call_input.done","item_id":"ct_1","input":"pwd"}`)); err != nil { + t.Fatal(err) + } + plan, err := turn.Finish(nativeTerminalResponse(`[{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":"pwd"}]`), "stop") + if err != nil { + t.Fatal(err) + } + if len(plan.Calls) != 1 || plan.Calls[0].Input != "pwd" { + t.Fatalf("custom plan lost input: %+v", plan.Calls) + } +} + +func TestNativeTurnRejectsTerminalWithoutCallID(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","name":"lookup","arguments":"{}"}]`), "stop") + if err == nil || !strings.Contains(err.Error(), "call id") { + t.Fatalf("terminal without call_id must be rejected, got %v", err) + } +} + +func TestNativeTurnRejectsExplicitNamespaceMismatch(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","namespace":"ns1","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + _, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","namespace":"ns2","arguments":"{}"}]`), "stop") + if err == nil { + t.Fatal("explicit namespace mismatch must be rejected") + } +} + +func TestNativeTurnRejectsArgumentDoneNameConflict(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}},{"type":"function","name":"other","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + done := `{"type":"response.function_call_arguments.done","item_id":"fc_1","call_id":"call_1","name":"other","arguments":"{}"}` + if err := turn.Observe("response.function_call_arguments.done", []byte(done)); err == nil { + t.Fatal("argument completion name conflict must be rejected") + } +} + +func TestNativeTurnRejectsCompletedEventWithIncompleteBody(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + body := json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}`) + _, err := NewNativeTurn(request).Finish(body, "stop") + if err == nil { + t.Fatal("response.completed with status=incomplete must not deliver a tool call") + } +} diff --git a/internal/toolcall/native_test.go b/internal/toolcall/native_test.go new file mode 100644 index 000000000..22e75454b --- /dev/null +++ b/internal/toolcall/native_test.go @@ -0,0 +1,352 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func nativeTestRequest(t *testing.T, tools, choice string, parallel *bool) Request { + t.Helper() + var choiceRaw json.RawMessage + if choice != "" { + choiceRaw = json.RawMessage(choice) + } + request, err := ParseRequest(ProtocolResponses, json.RawMessage(tools), choiceRaw, parallel, RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + +func nativeTerminalResponse(output string) json.RawMessage { + return json.RawMessage(`{"id":"resp_1","status":"completed","output":` + output + `}`) +} + +func TestNativeTerminalRejectsEventBodyDisagreement(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + cases := []struct { + name, status, finish string + wantErr bool + }{ + {"completed event with completed body", "completed", "stop", false}, + {"completed event with incomplete body", "incomplete", "stop", true}, + {"incomplete event with completed body", "completed", "length", true}, + {"failed event with completed body", "completed", "error", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := json.RawMessage(`{"id":"resp_1","status":"` + tc.status + `","output":` + output + `}`) + err := ValidateNativeResponsesTurn(body, request, tc.finish) + if tc.wantErr && err == nil { + t.Fatal("event/body disagreement must be rejected") + } + if !tc.wantErr && err != nil { + t.Fatalf("consistent terminal was rejected: %v", err) + } + }) + } +} + +func TestNativeTerminalArgumentsAreStrictAndNeverRepaired(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + cases := []string{ + "", + `{"q":`, + `{"q":"ok"}{"q":"again"}`, + `{"q":"ok","q":"again"}`, + `["q"]`, + `"ok"`, + `null`, + } + for _, arguments := range cases { + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":` + strconvQuote(arguments) + `}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request); err == nil { + t.Fatalf("arguments %q must be rejected", arguments) + } + } +} + +func TestNativeTerminalAcceptsCanonicalArgumentsAndEmptyCustomInput(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + output := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request); err != nil { + t.Fatal(err) + } + + customRequest := nativeTestRequest(t, `[{"type":"custom","name":"shell","description":"run"}]`, "", nil) + customOutput := `[{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"shell","input":""}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(customOutput), customRequest); err != nil { + t.Fatal(err) + } +} + +func TestNativeTerminalHonorsChoiceAndParallelConstraints(t *testing.T) { + parallel := false + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", ¶llel) + two := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(two), request); err == nil { + t.Fatal("parallel_tool_calls=false must reject two terminal calls") + } + + none := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, `"none"`, nil) + one := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(one), none); err == nil { + t.Fatal("tool_choice none must reject a terminal call") + } + + required := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, `"required"`, nil) + if err := ValidateNativeResponsesOutput(nativeTerminalResponse(`[]`), required); err == nil { + t.Fatal("required tool_choice must reject an empty terminal output") + } +} + +func TestNativeTurnFinishIsIdempotentAndSealsDeltas(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + first, err := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop") + if err != nil { + t.Fatal(err) + } + if len(first.Calls) != 1 { + t.Fatalf("calls = %d", len(first.Calls)) + } + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{}"}`)); err == nil { + t.Fatal("Observe after Finish must fail") + } + second, secondErr := turn.Finish(nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`), "stop") + if secondErr != nil || second == nil || len(second.Calls) != 1 { + t.Fatalf("repeat Finish must return the same plan, got %v %v", second, secondErr) + } +} + +func TestNativeLimitsRejectSuffixBytesBeforeAppend(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxArgumentBytes = 8 + turn := NewNativeTurn(request, limits) + if err := turn.Observe("response.function_call_arguments.delta", []byte(`{"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"123456789"}`)); err == nil { + t.Fatal("oversized argument delta must be rejected") + } +} + +func TestNativeLimitsRejectCompleteOutputSnapshotBytes(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxArgumentBytes = 8 + turn := NewNativeTurn(request, limits) + done := `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"123456789\"}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err == nil { + t.Fatal("oversized completed output item must be rejected") + } +} + +func TestNativeLimitsRejectCallCount(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := DefaultNativeLimits() + limits.MaxCalls = 1 + turn := NewNativeTurn(request, limits) + for _, id := range []string{"fc_1", "fc_2"} { + payload := `{"type":"response.output_item.added","item":{"id":"` + id + `","type":"function_call","call_id":"` + id + `","name":"lookup","arguments":""}}` + if id == "fc_2" { + if err := turn.Observe("response.output_item.added", []byte(payload)); err == nil { + t.Fatal("call count over the limit must be rejected") + } + continue + } + if err := turn.Observe("response.output_item.added", []byte(payload)); err != nil { + t.Fatal(err) + } + } +} + +func TestNativeTerminalRejectsUnknownExecutableItem(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + output := `[{"id":"x","type":"computer_call","call_id":"c","name":"computer"}]` + err := ValidateNativeResponsesOutput(nativeTerminalResponse(output), request) + if err == nil { + t.Fatal("unknown executable item must be rejected") + } + if !strings.Contains(err.Error(), "unsupported") { + t.Fatalf("expected unsupported item error, got %v", err) + } +} + +func TestNativeTurnRejectsTerminalThatOmitsVisibleParallelCall(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + for _, id := range []string{"fc_1", "fc_2"} { + added := `{"type":"response.output_item.added","item":{"id":"` + id + `","type":"function_call","call_id":"call_` + id + `","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + done := `{"type":"response.output_item.done","item":{"id":"` + id + `","type":"function_call","call_id":"call_` + id + `","name":"lookup","arguments":"{}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err != nil { + t.Fatal(err) + } + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_fc_1","name":"lookup","arguments":"{}"}]` + if _, err := turn.Finish(nativeTerminalResponse(terminal), "stop"); err == nil { + t.Fatal("terminal must not silently omit a visible completed call") + } +} + +func TestNativeTurnAcceptsInterleavedCallsWithMatchingTerminal(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + events := []struct { + name string + data string + }{ + {"response.output_item.added", `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`}, + {"response.output_item.added", `{"type":"response.output_item.added","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}`}, + {"response.output_item.done", `{"type":"response.output_item.done","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"}}`}, + {"response.output_item.done", `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`}, + } + for _, event := range events { + if err := turn.Observe(event.name, []byte(event.data)); err != nil { + t.Fatal(err) + } + } + terminal := `[{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"},{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]` + plan, err := turn.Finish(nativeTerminalResponse(terminal), "stop") + if err != nil { + t.Fatal(err) + } + if len(plan.Calls) != 2 { + t.Fatalf("calls = %d", len(plan.Calls)) + } +} + +func TestNativeTurnRejectsConflictingIdentity(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + first := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(first)); err != nil { + t.Fatal(err) + } + second := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(second)); err == nil { + t.Fatal("an item id must not switch call_id") + } +} + +func TestNativeTurnRejectsOutputIndexReuse(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + first := `{"type":"response.output_item.added","output_index":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(first)); err != nil { + t.Fatal(err) + } + second := `{"type":"response.output_item.added","output_index":0,"item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(second)); err == nil { + t.Fatal("output_index must not switch to another item id") + } +} + +func TestNativeTurnRejectsControlEnvelopeToolOmittedByTerminal(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + created := `{"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}` + if err := turn.Observe("response.created", []byte(created)); err != nil { + t.Fatal(err) + } + if _, err := turn.Finish(nativeTerminalResponse(`[]`), "stop"); err == nil { + t.Fatal("a tool item embedded in response.created must not disappear") + } +} + +func TestNativeTurnAllowsEmptyIncompleteButRejectsToolIncomplete(t *testing.T) { + request := nativeTestRequest(t, `[]`, "", nil) + turn := NewNativeTurn(request) + if _, err := turn.Finish(json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[]}`), "length"); err != nil { + t.Fatalf("tool-free incomplete should remain native truncation: %v", err) + } + + request = nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn = NewNativeTurn(request) + added := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + incomplete := json.RawMessage(`{"id":"resp_1","status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":"}]}`) + if _, err := turn.Finish(incomplete, "length"); err == nil { + t.Fatal("a tool-bearing incomplete turn must be rejected") + } +} + +func FuzzNativeTurnNeverDeliversAnOmittedVisibleCall(f *testing.F) { + f.Add(`[]`) + f.Add(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`) + f.Add(`[{"type":"message"}]`) + f.Fuzz(func(t *testing.T, terminalOutput string) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + turn := NewNativeTurn(request) + added := `{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}` + if err := turn.Observe("response.output_item.added", []byte(added)); err != nil { + t.Fatal(err) + } + plan, err := turn.Finish(nativeTerminalResponse(terminalOutput), "stop") + if err == nil && len(plan.Calls) == 0 { + t.Fatalf("terminal output %q dropped a visible call", terminalOutput) + } + }) +} + +func TestNativeDeliveryContainsFinalIdentityAndFullArguments(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","name":"lookup","arguments":""}}`)); err != nil { + t.Fatal(err) + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]` + delivery, err := turn.Finish(nativeTerminalResponse(terminal), "stop") + if err != nil { + t.Fatal(err) + } + if len(delivery.Calls) != 1 || delivery.Calls[0].CallID != "call_1" || delivery.Calls[0].Arguments != `{"q":"ok"}` { + t.Fatalf("delivery lost final identity/arguments: %+v", delivery.Calls) + } +} + +func BenchmarkNativeTurnFinish(b *testing.B) { + request, err := ParseRequest(ProtocolResponses, + json.RawMessage(`[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`), nil, nil, RepairSafe) + if err != nil { + b.Fatal(err) + } + added := []byte(`{"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`) + terminal := nativeTerminalResponse(`[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]`) + b.ResetTimer() + for i := 0; i < b.N; i++ { + turn := NewNativeTurn(request) + if err := turn.Observe("response.output_item.added", added); err != nil { + b.Fatal(err) + } + if _, err := turn.Finish(terminal, "stop"); err != nil { + b.Fatal(err) + } + } +} + +func TestNativeTurnComparesLargeIntegersWithoutFloatRounding(t *testing.T) { + request := nativeTestRequest(t, `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]}}]`, "", nil) + turn := NewNativeTurn(request) + done := `{"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"n\":9007199254740993}"}}` + if err := turn.Observe("response.output_item.done", []byte(done)); err != nil { + t.Fatal(err) + } + terminal := `[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"n\":9007199254740992}"}]` + if _, err := turn.Finish(nativeTerminalResponse(terminal), "stop"); err == nil { + t.Fatal("different large integers must not reconcile as equal") + } +} + +func strconvQuote(value string) string { + encoded, _ := json.Marshal(value) + return string(encoded) +} diff --git a/internal/toolcall/reducer.go b/internal/toolcall/reducer.go new file mode 100644 index 000000000..55c9e9699 --- /dev/null +++ b/internal/toolcall/reducer.go @@ -0,0 +1,435 @@ +package toolcall + +import ( + "fmt" + "sort" + "strings" +) + +// ChatToolDelta is one OpenAI Chat Completions tool_calls fragment. +type ChatToolDelta struct { + Index *int + ID string + Type string + Name string + Arguments string +} + +// ChatDelta is the subset of one Chat Completions chunk the reducer needs. +type ChatDelta struct { + Content string + Reasoning string + ToolCalls []ChatToolDelta + FinishReason string +} + +// Reducer assembles one upstream turn into stable tool calls. Identity is the +// provider call ID; index is only an auxiliary key scoped to this stream. +type Reducer struct { + request Request + + calls map[string]*Call + byIndex map[int]string + order []string + next int + + lastIndex int + text strings.Builder + reasoning strings.Builder + + finishReason string + terminal string + sealed bool + err error +} + +func NewReducer(request Request) *Reducer { + return &Reducer{ + request: request, + calls: make(map[string]*Call), + byIndex: make(map[int]string), + lastIndex: -1, + next: 1, + } +} + +func (r *Reducer) Text() string { return r.text.String() } +func (r *Reducer) Reasoning() string { return r.reasoning.String() } +func (r *Reducer) FinishReason() string { + return r.finishReason +} + +func (r *Reducer) Err() error { return r.err } + +// Absorb consumes one chunk. It returns renderer events for text, reasoning, +// call start and argument fragments. Error events are terminal. +func (r *Reducer) Absorb(delta ChatDelta) ([]Event, error) { + if r.sealed { + return nil, fmt.Errorf("tool stream already sealed") + } + if r.err != nil { + return nil, r.err + } + events := make([]Event, 0, 4) + if delta.Reasoning != "" { + r.reasoning.WriteString(delta.Reasoning) + events = append(events, Event{Kind: EventReasoningDelta, Text: delta.Reasoning}) + } + if delta.Content != "" { + r.text.WriteString(delta.Content) + events = append(events, Event{Kind: EventTextDelta, Text: delta.Content}) + } + for position := range delta.ToolCalls { + fragment := delta.ToolCalls[position] + call, started, err := r.resolveCall(fragment, position) + if err != nil { + r.err = err + return events, err + } + if started { + snapshot := *call + events = append(events, Event{Kind: EventCallStarted, Call: &snapshot}) + } + if fragment.Name != "" && len(r.request.Specs) > 0 { + if _, ok := r.request.SpecByName(fragment.Name); !ok { + r.invalidate(call, fmt.Sprintf("tool %q is not declared", fragment.Name)) + } + } + if fragment.ID != "" { + call.ProviderID = fragment.ID + call.InternalID = fragment.ID + } + if fragment.Name != "" { + if call.Name != "" && call.Name != fragment.Name { + r.invalidate(call, fmt.Sprintf("tool call id %q changed name from %q to %q", call.InternalID, call.Name, fragment.Name)) + } else { + call.Name = fragment.Name + } + } + if fragment.Arguments != "" { + call.ArgumentsRaw = mergeArgumentFragment(call.ArgumentsRaw, fragment.Arguments) + snapshot := *call + events = append(events, Event{Kind: EventCallArguments, Call: &snapshot}) + } + } + if delta.FinishReason != "" { + r.finishReason = delta.FinishReason + for _, id := range r.order { + // A call that fails final validation is reported by Finish; the + // chunk itself is still absorbed so renderers can see partial state. + _ = r.seal(r.calls[id]) + } + r.sealed = true + } + return events, nil +} + +// Finish seals the turn. terminal is done, eof, error, canceled or empty. +func (r *Reducer) Finish(terminal string) (TurnResult, error) { + if terminal == "" { + terminal = r.terminal + } + if terminal == "" { + terminal = "eof" + } + if !r.sealed { + for _, id := range r.order { + if err := r.seal(r.calls[id]); err != nil { + r.err = err + } + } + r.sealed = true + } + result := TurnResult{ + Protocol: r.request.Protocol, + Text: r.text.String(), + Reasoning: r.reasoning.String(), + FinishReason: r.finishReason, + UpstreamTerminal: terminal, + } + for _, id := range r.order { + result.Calls = append(result.Calls, *r.calls[id]) + } + for index := range result.Calls { + if result.Calls[index].Status == CallInvalid || result.Calls[index].Status == CallFailed || result.Calls[index].Status == CallTruncated { + if result.Calls[index].Status == CallTruncated { + result.Status = TurnTruncated + } else { + result.Status = TurnInvalid + } + result.Error = result.Calls[index].Error + return result, fmt.Errorf("%s", result.Error) + } + } + if r.err != nil { + result.Status = TurnInvalid + result.Error = r.err.Error() + return result, r.err + } + if strings.EqualFold(strings.TrimSpace(r.finishReason), "length") { + result.Status = TurnTruncated + result.Error = "upstream response finished with length" + return result, nil + } + if terminal == "error" { + result.Status = TurnFailed + result.Error = "upstream stream failed" + return result, fmt.Errorf("%s", result.Error) + } + if terminal == "canceled" { + result.Status = TurnCanceled + result.Error = "request canceled" + return result, fmt.Errorf("%s", result.Error) + } + if terminal != "done" { + result.Status = TurnTruncated + result.Error = "upstream ended without a terminal frame" + return result, fmt.Errorf("%s", result.Error) + } + if err := r.checkChoice(result); err != nil { + result.Status = TurnInvalid + result.Error = err.Error() + return result, err + } + if strings.EqualFold(strings.TrimSpace(r.finishReason), "tool_calls") && len(result.Calls) == 0 { + result.Status = TurnInvalid + result.Error = "finish_reason tool_calls without a tool call" + return result, fmt.Errorf("%s", result.Error) + } + if len(result.Calls) > 0 { + result.Status = TurnToolCalls + } else { + result.Status = TurnCompleted + } + return result, nil +} + +func (r *Reducer) checkChoice(result TurnResult) error { + choice := r.request.Choice + switch choice.Mode { + case ChoiceNone: + if len(result.Calls) > 0 { + return fmt.Errorf("tool_choice none was violated: model called %d tool(s)", len(result.Calls)) + } + case ChoiceRequired: + if len(result.Calls) == 0 { + return fmt.Errorf("tool_choice required was violated: model returned no tool call") + } + case ChoiceNamed: + if len(result.Calls) == 0 { + return fmt.Errorf("tool_choice %q was violated: model returned no tool call", choice.Name) + } + for _, call := range result.Calls { + if call.Name != choice.Name { + return fmt.Errorf("tool_choice %q was violated: model called %q", choice.Name, call.Name) + } + } + } + if r.request.Policy.MaxCalls > 0 && len(result.Calls) > r.request.Policy.MaxCalls { + return fmt.Errorf("tool call limit exceeded: %d > %d", len(result.Calls), r.request.Policy.MaxCalls) + } + if r.request.Policy.Parallel != nil && !*r.request.Policy.Parallel && len(result.Calls) > 1 { + return fmt.Errorf("parallel tool calls disabled: model returned %d calls", len(result.Calls)) + } + return nil +} + +func (r *Reducer) resolveCall(fragment ChatToolDelta, position int) (*Call, bool, error) { + index := -1 + if fragment.Index != nil { + index = *fragment.Index + } + if fragment.ID != "" { + if call, ok := r.calls[fragment.ID]; ok { + if index >= 0 { + r.bindIndex(index, call.InternalID) + } + return call, false, nil + } + if index >= 0 { + if existingID := r.byIndex[index]; existingID != "" { + existing := r.calls[existingID] + if existing != nil { + if existing.ProviderID == "" { + delete(r.calls, existing.InternalID) + for orderIndex := range r.order { + if r.order[orderIndex] == existing.InternalID { + r.order[orderIndex] = fragment.ID + break + } + } + existing.InternalID = fragment.ID + existing.ProviderID = fragment.ID + r.calls[fragment.ID] = existing + r.byIndex[index] = fragment.ID + return existing, false, nil + } + if existing.ProviderID != fragment.ID { + if err := r.seal(existing); err != nil { + return nil, false, err + } + delete(r.byIndex, index) + } + } + } + } + call := r.newCall(fragment, index) + return call, true, nil + } + if index >= 0 { + if existingID := r.byIndex[index]; existingID != "" { + call := r.calls[existingID] + if call != nil && !call.Sealed { + r.lastIndex = index + return call, false, nil + } + // Index reuse after a sealed call starts a new call. + delete(r.byIndex, index) + } + if fragment.Name != "" || r.lastIndex == index || r.lastIndex < 0 { + call := r.newCall(fragment, index) + return call, true, nil + } + call := r.newCall(fragment, index) + return call, true, nil + } + if fragment.Name != "" { + call := r.newCall(fragment, index) + return call, true, nil + } + // A nameless fragment without an index belongs to the most recent open + // call; if there is none, create a placeholder that will fail at seal time. + if len(r.order) > 0 { + call := r.calls[r.order[len(r.order)-1]] + if call != nil && !call.Sealed { + return call, false, nil + } + } + call := r.newCall(fragment, position) + return call, true, nil +} + +func (r *Reducer) newCall(fragment ChatToolDelta, index int) *Call { + id := fragment.ID + if id == "" { + id = fmt.Sprintf("local_%d", r.next) + r.next++ + } + call := &Call{ + Index: index, + InternalID: id, + ProviderID: fragment.ID, + Name: strings.TrimSpace(fragment.Name), + Status: CallStarted, + } + r.calls[id] = call + r.order = append(r.order, id) + r.lastIndex = index + if index >= 0 { + r.bindIndex(index, id) + } + return call +} + +func (r *Reducer) bindIndex(index int, id string) { + if index < 0 { + return + } + if existing := r.byIndex[index]; existing != "" && existing != id { + // The provider reused the index for a new call; the new call wins. + if call := r.calls[existing]; call != nil { + _ = r.seal(call) + } + } + r.byIndex[index] = id +} + +func (r *Reducer) seal(call *Call) error { + if call == nil || call.Sealed { + return nil + } + if call.Status == CallInvalid { + return fmt.Errorf("%s", call.Error) + } + call.Sealed = true + if strings.TrimSpace(call.Name) == "" { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool call %q has no name", call.InternalID) + return fmt.Errorf("%s", call.Error) + } + spec, ok := r.request.SpecByName(call.Name) + if len(r.request.Specs) == 0 { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool %q was returned without being declared", call.Name) + return fmt.Errorf("%s", call.Error) + } + if !ok { + call.Status = CallInvalid + call.Error = fmt.Sprintf("tool %q is not declared", call.Name) + return fmt.Errorf("%s", call.Error) + } + call.Namespace = spec.Namespace + call.OriginalName = spec.OriginalName + arguments, repaired, err := ValidateArguments(spec, call.ArgumentsRaw, r.request.Policy.Repair) + if err != nil { + call.Status = CallInvalid + call.Error = err.Error() + return err + } + call.Arguments = arguments + call.Repaired = repaired + call.Status = CallCompleted + return nil +} + +func (r *Reducer) invalidate(call *Call, reason string) { + if call == nil { + return + } + if call.Status == CallCompleted || call.Status == CallInvalid { + return + } + call.Status = CallInvalid + call.Error = reason +} + +func mergeArgumentFragment(base, fragment string) string { + if fragment == "" { + return base + } + if base == "" { + return fragment + } + // Some upstreams resend the full buffer on every chunk. + if len(fragment) > len(base) && strings.HasPrefix(fragment, base) { + return fragment + } + if len(fragment) >= 8 && strings.HasSuffix(base, fragment) { + return base + } + return base + fragment +} + +// Calls returns a copy in protocol order. +func (r *Reducer) Calls() []Call { + calls := make([]Call, 0, len(r.order)) + for _, id := range r.order { + if call := r.calls[id]; call != nil { + calls = append(calls, *call) + } + } + return calls +} + +// OrderedIndexes returns the canonical call order as indexes for renderers +// that still address calls by their original protocol index. +func (r *Reducer) OrderedIndexes() []int { + indexes := make([]int, 0, len(r.order)) + for _, id := range r.order { + if call := r.calls[id]; call != nil && call.Index >= 0 { + indexes = append(indexes, call.Index) + } + } + sort.Ints(indexes) + return indexes +} diff --git a/internal/toolcall/render.go b/internal/toolcall/render.go new file mode 100644 index 000000000..07a6ecf87 --- /dev/null +++ b/internal/toolcall/render.go @@ -0,0 +1,239 @@ +package toolcall + +import ( + "encoding/json" + "fmt" +) + +// ChatOutput is the buffered Chat Completions representation of one turn. +type ChatOutput struct { + Text string + Reasoning string + FinishReason string + Calls []Call +} + +// ContentBlock is one Anthropic Messages content block. +type ContentBlock struct { + Type string + Text string + ID string + Name string + Input json.RawMessage +} + +// ResponseItem is one Responses API output item. +type ResponseItem struct { + Type string + ID string + CallID string + Name string + Arguments string + Status string + Content []ContentBlock +} + +// RenderChatStream replays buffered Chat chunks through the canonical reducer +// and emits deterministic Chat chunks. It is used by tests and by adapters that +// need to re-normalize a buffered stream. +func RenderChatStream(request Request, deltas []ChatDelta) ([]ChatDelta, TurnResult, error) { + reducer := NewReducer(request) + for index := range deltas { + if _, err := reducer.Absorb(deltas[index]); err != nil { + return nil, reducer.snapshotResult(), err + } + } + result, err := reducer.Finish("done") + if err != nil { + return nil, result, err + } + out := make([]ChatDelta, 0, len(result.Calls)+2) + if result.Text != "" || result.Reasoning != "" { + out = append(out, ChatDelta{Content: result.Text, Reasoning: result.Reasoning}) + } + for index := range result.Calls { + if result.Status == TurnTruncated { + break + } + call := result.Calls[index] + callIndex := index + out = append(out, ChatDelta{ToolCalls: []ChatToolDelta{{ + Index: &callIndex, + ID: call.InternalID, + Type: "function", + Name: call.Name, + Arguments: string(call.Arguments), + }}}) + } + finish := result.FinishReason + if result.Status == TurnToolCalls { + finish = "tool_calls" + } else if finish == "" { + finish = "stop" + } + out = append(out, ChatDelta{FinishReason: finish}) + return out, result, nil +} + +// ReduceChatCompletion folds one buffered assistant turn into the canonical +// result. Callers must use this instead of trusting adapter JSON directly: +// argument and choice violations become errors, never a synthesized success. +func ReduceChatCompletion(request Request, content, reasoning, finishReason string, rawCalls json.RawMessage) (TurnResult, error) { + reducer := NewReducer(request) + delta := ChatDelta{Content: content, Reasoning: reasoning, FinishReason: finishReason} + if len(rawCalls) > 0 && string(rawCalls) != "null" { + var calls []struct { + ID string `json:"id"` + Type string `json:"type"` + Function struct { + Name string `json:"name"` + Arguments string `json:"arguments"` + } `json:"function"` + } + if err := json.Unmarshal(rawCalls, &calls); err != nil { + return TurnResult{}, fmt.Errorf("tool_calls: %w", err) + } + for index, call := range calls { + callIndex := index + delta.ToolCalls = append(delta.ToolCalls, ChatToolDelta{ + Index: &callIndex, + ID: call.ID, + Type: call.Type, + Name: call.Function.Name, + Arguments: call.Function.Arguments, + }) + } + } + if _, err := reducer.Absorb(delta); err != nil { + return reducer.snapshotResult(), err + } + return reducer.Finish("done") +} + +func RenderChat(result TurnResult) ChatOutput { + switch result.Status { + case TurnFailed, TurnInvalid, TurnCanceled: + return ChatOutput{FinishReason: "error"} + case TurnTruncated: + return ChatOutput{Text: result.Text, Reasoning: result.Reasoning, FinishReason: finishReasonFor(result)} + } + return ChatOutput{ + Text: result.Text, + Reasoning: result.Reasoning, + FinishReason: finishReasonFor(result), + Calls: append([]Call(nil), result.Calls...), + } +} + +func finishReasonFor(result TurnResult) string { + if result.Status == TurnToolCalls { + return "tool_calls" + } + if result.FinishReason != "" { + return result.FinishReason + } + return "stop" +} + +// RenderMessagesBlocks renders only valid turns. A failed or truncated turn is +// never converted into a successful content block list. +func RenderMessagesBlocks(result TurnResult) ([]ContentBlock, error) { + if result.Status == TurnFailed || result.Status == TurnTruncated || result.Status == TurnInvalid || result.Status == TurnCanceled { + return nil, failureFor(result) + } + blocks := make([]ContentBlock, 0, len(result.Calls)+1) + if result.Text != "" { + blocks = append(blocks, ContentBlock{Type: "text", Text: result.Text}) + } + for _, call := range result.Calls { + if err := requireCompletedCall(call); err != nil { + return nil, err + } + input := call.Arguments + if len(input) == 0 { + input = json.RawMessage("{}") + } + blocks = append(blocks, ContentBlock{ + Type: "tool_use", + ID: call.InternalID, + Name: call.Name, + Input: input, + }) + } + return blocks, nil +} + +// RenderResponsesItems renders only valid turns. Function call items are never +// emitted when the reducer marked their arguments invalid. +func RenderResponsesItems(result TurnResult) ([]ResponseItem, error) { + if result.Status == TurnFailed || result.Status == TurnTruncated || result.Status == TurnInvalid || result.Status == TurnCanceled { + return nil, failureFor(result) + } + items := make([]ResponseItem, 0, len(result.Calls)+1) + if result.Text != "" { + items = append(items, ResponseItem{ + Type: "message", + ID: "msg_" + stablePart(result.Protocol), + Status: "completed", + Content: []ContentBlock{{Type: "output_text", Text: result.Text}}, + }) + } + for _, call := range result.Calls { + if err := requireCompletedCall(call); err != nil { + return nil, err + } + items = append(items, ResponseItem{ + Type: "function_call", + ID: "fc_" + call.InternalID, + CallID: call.InternalID, + Name: call.Name, + Arguments: string(call.Arguments), + Status: "completed", + }) + } + return items, nil +} + +func requireCompletedCall(call Call) error { + if call.Status != CallCompleted { + if call.Error != "" { + return fmt.Errorf("%s", call.Error) + } + return fmt.Errorf("tool call %q is %s", call.InternalID, call.Status) + } + return nil +} + +func failureFor(result TurnResult) error { + if result.Error != "" { + return fmt.Errorf("%s", result.Error) + } + return fmt.Errorf("turn %s cannot be rendered as success", result.Status) +} + +func stablePart(protocol Protocol) string { + if protocol == "" { + return "chat" + } + return string(protocol) +} + +func (r *Reducer) snapshotResult() TurnResult { + result := TurnResult{ + Protocol: r.request.Protocol, + Text: r.text.String(), + Reasoning: r.reasoning.String(), + FinishReason: r.finishReason, + UpstreamTerminal: r.terminal, + Status: TurnFailed, + } + if r.err != nil { + result.Error = r.err.Error() + } + for _, id := range r.order { + if call := r.calls[id]; call != nil { + result.Calls = append(result.Calls, *call) + } + } + return result +} diff --git a/internal/toolcall/request.go b/internal/toolcall/request.go new file mode 100644 index 000000000..82a00964c --- /dev/null +++ b/internal/toolcall/request.go @@ -0,0 +1,387 @@ +package toolcall + +import ( + "encoding/json" + "fmt" + "strings" +) + +const defaultParameters = `{"type":"object","properties":{}}` + +// ParseRequest parses the normalized OpenAI tool array and selector used by +// all current adapters. It also accepts flat Responses function declarations so +// a native Responses body can be validated before an adapter is chosen. +func ParseRequest(protocol Protocol, tools, choice json.RawMessage, parallel *bool, repair RepairMode) (Request, error) { + if protocol == "" { + protocol = ProtocolChat + } + if repair == "" { + repair = RepairSafe + } + request := Request{Protocol: protocol, Policy: Policy{Repair: repair, Schema: SchemaRelaxed}} + specs, diagnostics, err := parseSpecs(protocol, tools) + if err != nil { + return Request{}, err + } + request.Specs = specs + request.Diagnostics = diagnostics + for _, spec := range specs { + if spec.Strict { + request.Policy.Schema = SchemaStrict + break + } + } + request.Policy.Parallel = cloneBool(parallel) + parsedChoice, diagnostic, err := parseChoice(specs, choice) + if err != nil { + return Request{}, err + } + if diagnostic != "" { + request.Diagnostics = append(request.Diagnostics, diagnostic) + } + request.Choice = parsedChoice + return request, nil +} + +func cloneBool(value *bool) *bool { + if value == nil { + return nil + } + copy := *value + return © +} + +func parseSpecs(protocol Protocol, raw json.RawMessage) ([]Spec, []string, error) { + if emptyJSON(raw) { + return nil, nil, nil + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return nil, nil, fmt.Errorf("tools must be an array") + } + specs := make([]Spec, 0, len(items)) + diagnostics := make([]string, 0) + seen := map[string]int{} + appendSpec := func(spec Spec) error { + if strings.TrimSpace(spec.Name) == "" { + return fmt.Errorf("tool name required") + } + if index, exists := seen[spec.Name]; exists { + return fmt.Errorf("duplicate tool name %q (tools[%d])", spec.Name, index) + } + seen[spec.Name] = len(specs) + specs = append(specs, spec) + return nil + } + for index, item := range items { + var object map[string]json.RawMessage + if err := json.Unmarshal(item, &object); err != nil { + return nil, nil, fmt.Errorf("tools[%d] must be an object", index) + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + switch kind { + case "namespace": + namespace := strings.TrimSpace(rawString(object["name"])) + nested, nestedDiagnostics, err := parseNamespace(protocol, namespace, object["tools"]) + if err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + diagnostics = append(diagnostics, nestedDiagnostics...) + for _, spec := range nested { + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + } + case "mcp", "web_search", "web_search_preview": + diagnostics = append(diagnostics, fmt.Sprintf("hosted tool tools[%d] type %q is not executable", index, kind)) + case "custom": + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + return nil, nil, fmt.Errorf("tools[%d].name required", index) + } + parameters := customParameters() + spec := Spec{ + Name: customWireName("", name), + OriginalName: name, + Description: rawString(object["description"]), + Parameters: parameters, + Custom: true, + Source: protocol, + } + if format := strings.TrimSpace(string(object["format"])); format != "" && format != "null" { + spec.Description = strings.TrimSpace(spec.Description + "\n\nCustom tool input format:\n" + format) + } + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + case "function", "": + spec, err := parseFunctionSpec(protocol, object) + if err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + if err := appendSpec(spec); err != nil { + return nil, nil, fmt.Errorf("tools[%d]: %w", index, err) + } + default: + diagnostics = append(diagnostics, fmt.Sprintf("tool tools[%d] type %q is not supported", index, kind)) + } + } + return specs, diagnostics, nil +} + +func parseNamespace(protocol Protocol, namespace string, raw json.RawMessage) ([]Spec, []string, error) { + if emptyJSON(raw) { + return nil, nil, nil + } + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return nil, nil, fmt.Errorf("namespace tools must be an array") + } + specs := make([]Spec, 0, len(items)) + diagnostics := make([]string, 0) + for index, item := range items { + var object map[string]json.RawMessage + if err := json.Unmarshal(item, &object); err != nil { + return nil, nil, fmt.Errorf("namespace tools[%d] must be an object", index) + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + if kind != "" && kind != "function" && kind != "custom" { + diagnostics = append(diagnostics, fmt.Sprintf("namespace tool %q type %q is not supported", namespace, kind)) + continue + } + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + return nil, nil, fmt.Errorf("namespace tools[%d].name required", index) + } + spec := Spec{ + Name: qualifyName(namespace, name), + OriginalName: name, + Namespace: namespace, + Description: rawString(object["description"]), + Parameters: json.RawMessage(defaultParameters), + Source: protocol, + } + if kind == "custom" { + spec.Name = qualifyName(namespace, customWireName("", name)) + spec.Custom = true + spec.Parameters = customParameters() + } else { + parameters := rawJSON(object["parameters"]) + if len(parameters) == 0 { + parameters = rawJSON(object["input_schema"]) + } + if len(parameters) > 0 { + spec.Parameters = parameters + } + var strict bool + if json.Unmarshal(object["strict"], &strict) == nil { + spec.Strict = strict + } + } + if err := validateSpecSchema(spec); err != nil { + return nil, nil, fmt.Errorf("namespace tool %q: %w", spec.Name, err) + } + specs = append(specs, spec) + } + return specs, diagnostics, nil +} + +func parseFunctionSpec(protocol Protocol, object map[string]json.RawMessage) (Spec, error) { + var function map[string]json.RawMessage + if raw := rawJSON(object["function"]); len(raw) > 0 { + _ = json.Unmarshal(raw, &function) + } + name := firstNonEmpty(rawString(function["name"]), rawString(object["name"])) + description := firstNonEmpty(rawString(function["description"]), rawString(object["description"])) + parameters := firstNonEmptyRaw(rawJSON(function["parameters"]), rawJSON(object["parameters"]), rawJSON(object["input_schema"])) + if len(parameters) == 0 { + parameters = json.RawMessage(defaultParameters) + } + var strict bool + if json.Unmarshal(function["strict"], &strict) != nil { + _ = json.Unmarshal(object["strict"], &strict) + } + spec := Spec{ + Name: strings.TrimSpace(name), + OriginalName: strings.TrimSpace(name), + Description: description, + Parameters: parameters, + Strict: strict, + Source: protocol, + } + if namespace := strings.TrimSpace(rawString(object["namespace"])); namespace != "" { + spec.Namespace = namespace + spec.Name = qualifyName(namespace, spec.Name) + } + if err := validateSpecSchema(spec); err != nil { + return Spec{}, err + } + return spec, nil +} + +func validateSpecSchema(spec Spec) error { + if strings.TrimSpace(spec.Name) == "" { + return fmt.Errorf("tool name required") + } + if len(spec.Parameters) == 0 || string(spec.Parameters) == "null" { + spec.Parameters = json.RawMessage(defaultParameters) + } + return ValidateSchema(spec.Parameters) +} + +func parseChoice(specs []Spec, raw json.RawMessage) (Choice, string, error) { + if emptyJSON(raw) { + return Choice{Mode: ChoiceUnspecified}, "", nil + } + text, isString := rawStringOK(raw) + if isString { + switch strings.ToLower(strings.TrimSpace(text)) { + case "none": + return Choice{Mode: ChoiceNone}, "", nil + case "auto": + if len(specs) == 0 { + return Choice{Mode: ChoiceUnspecified}, "tool_choice auto dropped: no executable tools were declared", nil + } + return Choice{Mode: ChoiceAuto}, "", nil + case "required", "any": + if len(specs) == 0 { + return Choice{}, "", fmt.Errorf("tool_choice requires executable tools") + } + return Choice{Mode: ChoiceRequired}, "", nil + default: + name := strings.TrimSpace(text) + if name == "" { + return Choice{}, "", fmt.Errorf("tool_choice name required") + } + if _, ok := findSpec(specs, name); !ok { + return Choice{}, "", fmt.Errorf("tool_choice references undeclared tool %q", name) + } + return Choice{Mode: ChoiceNamed, Name: name}, "", nil + } + } + var object map[string]json.RawMessage + if err := json.Unmarshal(raw, &object); err != nil { + return Choice{}, "", fmt.Errorf("tool_choice must be a string or an object") + } + kind := strings.ToLower(strings.TrimSpace(rawString(object["type"]))) + switch kind { + case "none": + return Choice{Mode: ChoiceNone}, "", nil + case "auto": + if len(specs) == 0 { + return Choice{Mode: ChoiceUnspecified}, "tool_choice auto dropped: no executable tools were declared", nil + } + return Choice{Mode: ChoiceAuto}, "", nil + case "required", "any": + if len(specs) == 0 { + return Choice{}, "", fmt.Errorf("tool_choice requires executable tools") + } + return Choice{Mode: ChoiceRequired}, "", nil + case "function", "custom", "tool": + name := strings.TrimSpace(rawString(object["name"])) + if name == "" { + var function map[string]json.RawMessage + if json.Unmarshal(rawJSON(object["function"]), &function) == nil { + name = strings.TrimSpace(rawString(function["name"])) + } + } + if kind == "custom" { + name = customWireName(rawString(object["namespace"]), name) + } + if namespace := strings.TrimSpace(rawString(object["namespace"])); namespace != "" { + name = qualifyName(namespace, name) + } + if name == "" { + return Choice{}, "", fmt.Errorf("tool_choice.name required") + } + if _, ok := findSpec(specs, name); !ok { + return Choice{}, "", fmt.Errorf("tool_choice references undeclared tool %q", name) + } + return Choice{Mode: ChoiceNamed, Name: name}, "", nil + default: + return Choice{}, "", fmt.Errorf("tool_choice type %q is not supported", kind) + } +} + +func findSpec(specs []Spec, name string) (Spec, bool) { + for _, spec := range specs { + if spec.Name == name { + return spec, true + } + } + return Spec{}, false +} + +func customWireName(namespace, name string) string { + name = strings.TrimSpace(name) + if name == "" { + return "" + } + namespace = strings.TrimSpace(namespace) + if namespace == "" { + return "__codex_custom__" + name + } + return strings.TrimRight(namespace, "_") + "__codex_custom__" + name +} + +func qualifyName(namespace, name string) string { + name = strings.TrimSpace(name) + namespace = strings.TrimSpace(namespace) + if namespace == "" { + return name + } + return namespace + "__" + name +} + +func customParameters() json.RawMessage { + return json.RawMessage(`{"type":"object","properties":{"input":{"type":"string","description":"Raw freeform input for the custom tool."}},"required":["input"],"additionalProperties":false}`) +} + +func emptyJSON(raw json.RawMessage) bool { + text := strings.TrimSpace(string(raw)) + return text == "" || text == "null" || text == "[]" +} + +func rawJSON(raw json.RawMessage) json.RawMessage { + if len(raw) == 0 || string(raw) == "null" { + return nil + } + return raw +} + +func firstNonEmptyRaw(values ...json.RawMessage) json.RawMessage { + for _, value := range values { + if len(value) > 0 && string(value) != "null" { + return value + } + } + return nil +} + +func rawString(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var value string + if json.Unmarshal(raw, &value) == nil { + return value + } + return "" +} + +func rawStringOK(raw json.RawMessage) (string, bool) { + var value string + if json.Unmarshal(raw, &value) == nil { + return value, true + } + return "", false +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/internal/toolcall/schema.go b/internal/toolcall/schema.go new file mode 100644 index 000000000..a8c787b9b --- /dev/null +++ b/internal/toolcall/schema.go @@ -0,0 +1,482 @@ +package toolcall + +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "strings" +) + +// ValidateSchema performs the structural checks a routing/adapter contract +// needs before a tool is advertised. It intentionally accepts unknown JSON +// Schema keywords, but rejects malformed type/properties/required shapes. +func ValidateSchema(raw json.RawMessage) error { + text := strings.TrimSpace(string(raw)) + if text == "" || text == "null" { + return nil + } + if text == "true" || text == "false" { + return nil + } + var schema map[string]json.RawMessage + if err := json.Unmarshal(raw, &schema); err != nil { + return fmt.Errorf("tool schema must be an object") + } + return validateSchemaNode(schema, 0) +} + +func validateSchemaNode(schema map[string]json.RawMessage, depth int) error { + if depth > 64 { + return fmt.Errorf("tool schema nesting exceeds 64 levels") + } + if refRaw, ok := schema["$ref"]; ok { + var ref string + if err := json.Unmarshal(refRaw, &ref); err != nil { + return fmt.Errorf("schema $ref must be a string") + } + ref = strings.TrimSpace(ref) + if ref == "" || ref[0] != '#' { + return fmt.Errorf("schema $ref %q is not a local JSON pointer", ref) + } + } + if typeRaw, ok := schema["type"]; ok { + if err := validateSchemaType(typeRaw); err != nil { + return err + } + } + if propertiesRaw, ok := schema["properties"]; ok { + var properties map[string]json.RawMessage + if err := json.Unmarshal(propertiesRaw, &properties); err != nil { + return fmt.Errorf("schema properties must be an object") + } + for name, property := range properties { + var child map[string]json.RawMessage + if err := json.Unmarshal(property, &child); err != nil { + return fmt.Errorf("schema property %q must be an object", name) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema property %q: %w", name, err) + } + } + } + if requiredRaw, ok := schema["required"]; ok { + var required []string + if err := json.Unmarshal(requiredRaw, &required); err != nil { + return fmt.Errorf("schema required must be an array of strings") + } + propertiesRaw := schema["properties"] + var properties map[string]json.RawMessage + if len(propertiesRaw) > 0 { + _ = json.Unmarshal(propertiesRaw, &properties) + } + for _, name := range required { + if strings.TrimSpace(name) == "" { + return fmt.Errorf("schema required contains an empty name") + } + if _, exists := properties[name]; !exists { + return fmt.Errorf("schema required names undeclared property %q", name) + } + } + } + if itemsRaw, ok := schema["items"]; ok { + var child map[string]json.RawMessage + if err := json.Unmarshal(itemsRaw, &child); err != nil { + return fmt.Errorf("schema items must be an object") + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema items: %w", err) + } + } + if additionalRaw, ok := schema["additionalProperties"]; ok { + text := strings.TrimSpace(string(additionalRaw)) + if text != "true" && text != "false" { + var child map[string]json.RawMessage + if err := json.Unmarshal(additionalRaw, &child); err != nil { + return fmt.Errorf("schema additionalProperties must be bool or object") + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema additionalProperties: %w", err) + } + } + } + for _, keyword := range []string{"anyOf", "oneOf", "allOf"} { + raw, ok := schema[keyword] + if !ok { + continue + } + var children []json.RawMessage + if err := json.Unmarshal(raw, &children); err != nil || len(children) == 0 { + return fmt.Errorf("schema %s must be a non-empty array", keyword) + } + for index, childRaw := range children { + var child map[string]json.RawMessage + if err := json.Unmarshal(childRaw, &child); err != nil { + return fmt.Errorf("schema %s[%d] must be an object", keyword, index) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema %s[%d]: %w", keyword, index, err) + } + } + } + for _, keyword := range []string{"$defs", "definitions"} { + raw, ok := schema[keyword] + if !ok { + continue + } + var definitions map[string]json.RawMessage + if err := json.Unmarshal(raw, &definitions); err != nil { + return fmt.Errorf("schema %s must be an object", keyword) + } + for name, childRaw := range definitions { + var child map[string]json.RawMessage + if err := json.Unmarshal(childRaw, &child); err != nil { + return fmt.Errorf("schema %s.%s must be an object", keyword, name) + } + if err := validateSchemaNode(child, depth+1); err != nil { + return fmt.Errorf("schema %s.%s: %w", keyword, name, err) + } + } + } + return nil +} + +func validateSchemaType(raw json.RawMessage) error { + var single string + if json.Unmarshal(raw, &single) == nil { + return validateTypeName(single) + } + var list []string + if json.Unmarshal(raw, &list) == nil { + if len(list) == 0 { + return fmt.Errorf("schema type array must not be empty") + } + for _, item := range list { + if err := validateTypeName(item); err != nil { + return err + } + } + return nil + } + return fmt.Errorf("schema type must be a string or string array") +} + +func validateTypeName(name string) error { + switch strings.ToLower(strings.TrimSpace(name)) { + case "object", "array", "string", "number", "integer", "boolean", "null": + return nil + default: + return fmt.Errorf("schema type %q is not supported", name) + } +} + +// ValidateArguments validates one call's argument bytes against its spec. It +// repairs only when the request policy explicitly allows safe repair. +func ValidateArguments(spec Spec, raw string, mode RepairMode) (json.RawMessage, bool, error) { + text := strings.TrimSpace(raw) + repaired := false + if text == "" { + text = "{}" + repaired = true + } + if !json.Valid([]byte(text)) { + switch mode { + case RepairSafe: + fixed, ok := RepairArguments(text) + if !ok { + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + } + text, repaired = fixed, true + case RepairPreserve: + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + default: + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON", spec.Name) + } + } + var value any + decoder := json.NewDecoder(bytes.NewReader([]byte(text))) + decoder.UseNumber() + if err := decoder.Decode(&value); err != nil { + return nil, false, fmt.Errorf("tool %q arguments are not valid JSON: %w", spec.Name, err) + } + if len(spec.Parameters) > 0 && string(spec.Parameters) != "null" { + var schema any + if err := json.Unmarshal(spec.Parameters, &schema); err != nil { + return nil, false, fmt.Errorf("tool %q schema is invalid: %w", spec.Name, err) + } + if err := validateValue(schema, schema, value, 0); err != nil { + return nil, false, fmt.Errorf("tool %q arguments do not match schema: %w", spec.Name, err) + } + } + normalized, err := json.Marshal(value) + if err != nil { + return nil, false, fmt.Errorf("tool %q arguments cannot be encoded: %w", spec.Name, err) + } + return normalized, repaired, nil +} + +func validateValue(root, schema, value any, depth int) error { + if depth > 64 { + return fmt.Errorf("schema nesting exceeds 64 levels") + } + switch typed := schema.(type) { + case bool: + if !typed { + return fmt.Errorf("schema is false") + } + return nil + case map[string]any: + if ref, ok := typed["$ref"].(string); ok && strings.TrimSpace(ref) != "" { + resolved, err := resolveSchemaRef(root, ref) + if err != nil { + return err + } + if err := validateValue(root, resolved, value, depth+1); err != nil { + return fmt.Errorf("$ref %q: %w", ref, err) + } + } + if enum, ok := typed["enum"].([]any); ok && len(enum) > 0 { + matched := false + for _, candidate := range enum { + if jsonEqual(candidate, value) { + matched = true + break + } + } + if !matched { + return fmt.Errorf("value is not in enum") + } + } + if constant, ok := typed["const"]; ok && !jsonEqual(constant, value) { + return fmt.Errorf("value does not equal const") + } + if err := validateComposed(root, typed, value, depth); err != nil { + return err + } + if typeValue, ok := typed["type"]; ok { + if err := matchType(typeValue, value); err != nil { + return err + } + } + switch value.(type) { + case map[string]any: + return validateObject(root, typed, value.(map[string]any), depth) + case []any: + return validateArray(root, typed, value.([]any), depth) + } + return nil + default: + return fmt.Errorf("schema must be an object or bool") + } +} + +func resolveSchemaRef(root any, ref string) (any, error) { + ref = strings.TrimSpace(ref) + if ref == "#" { + return root, nil + } + if !strings.HasPrefix(ref, "#/") { + return nil, fmt.Errorf("$ref %q is not a local JSON pointer", ref) + } + current := root + for _, token := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") { + token = strings.ReplaceAll(strings.ReplaceAll(token, "~1", "/"), "~0", "~") + switch node := current.(type) { + case map[string]any: + value, ok := node[token] + if !ok { + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + current = value + case []any: + index, err := strconv.Atoi(token) + if err != nil || index < 0 || index >= len(node) { + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + current = node[index] + default: + return nil, fmt.Errorf("$ref %q does not resolve", ref) + } + } + return current, nil +} + +func validateComposed(root any, schema map[string]any, value any, depth int) error { + if anyOf, ok := schema["anyOf"].([]any); ok && len(anyOf) > 0 { + matched := false + for _, candidate := range anyOf { + if validateValue(root, candidate, value, depth+1) == nil { + matched = true + break + } + } + if !matched { + return fmt.Errorf("value matches no anyOf branch") + } + } + if oneOf, ok := schema["oneOf"].([]any); ok && len(oneOf) > 0 { + matches := 0 + for _, candidate := range oneOf { + if validateValue(root, candidate, value, depth+1) == nil { + matches++ + } + } + if matches != 1 { + return fmt.Errorf("value matches %d oneOf branches", matches) + } + } + if allOf, ok := schema["allOf"].([]any); ok { + for _, candidate := range allOf { + if err := validateValue(root, candidate, value, depth+1); err != nil { + return fmt.Errorf("allOf: %w", err) + } + } + } + return nil +} + +func validateObject(root any, schema map[string]any, object map[string]any, depth int) error { + properties, _ := schema["properties"].(map[string]any) + if required, ok := schema["required"].([]any); ok { + for _, nameValue := range required { + name, _ := nameValue.(string) + if _, exists := object[name]; !exists { + return fmt.Errorf("required property %q is missing", name) + } + } + } + for name, value := range object { + property, declared := properties[name] + if declared { + if err := validateValue(root, property, value, depth+1); err != nil { + return fmt.Errorf("property %q: %w", name, err) + } + continue + } + if additional, ok := schema["additionalProperties"]; ok { + switch additional := additional.(type) { + case bool: + if !additional { + return fmt.Errorf("additional property %q is not allowed", name) + } + case map[string]any: + if err := validateValue(root, additional, value, depth+1); err != nil { + return fmt.Errorf("additional property %q: %w", name, err) + } + } + } + } + return nil +} + +func validateArray(root any, schema map[string]any, array []any, depth int) error { + items, ok := schema["items"] + if !ok { + return nil + } + for index, value := range array { + if err := validateValue(root, items, value, depth+1); err != nil { + return fmt.Errorf("item %d: %w", index, err) + } + } + return nil +} + +func matchType(typeValue any, value any) error { + switch typed := typeValue.(type) { + case string: + if typeMatches(typed, value) { + return nil + } + return fmt.Errorf("value is %s, want %s", valueType(value), typed) + case []any: + for _, candidate := range typed { + name, _ := candidate.(string) + if typeMatches(name, value) { + return nil + } + } + return fmt.Errorf("value is %s, want one of %v", valueType(value), typed) + default: + return fmt.Errorf("schema type is invalid") + } +} + +func typeMatches(name string, value any) bool { + switch strings.ToLower(strings.TrimSpace(name)) { + case "object": + _, ok := value.(map[string]any) + return ok + case "array": + _, ok := value.([]any) + return ok + case "string": + _, ok := value.(string) + return ok + case "boolean": + _, ok := value.(bool) + return ok + case "null": + return value == nil + case "number": + switch value.(type) { + case json.Number, float64, int, int64: + return true + } + return false + case "integer": + number, ok := value.(json.Number) + if !ok { + return false + } + text := number.String() + return !strings.ContainsAny(text, ".eE") + default: + return false + } +} + +func valueType(value any) string { + switch value.(type) { + case map[string]any: + return "object" + case []any: + return "array" + case string: + return "string" + case bool: + return "boolean" + case nil: + return "null" + case json.Number, float64, int, int64: + return "number" + default: + return fmt.Sprintf("%T", value) + } +} + +func jsonEqual(left, right any) bool { + leftJSON, leftErr := json.Marshal(left) + rightJSON, rightErr := json.Marshal(right) + if leftErr != nil || rightErr != nil { + return false + } + return bytes.Equal(leftJSON, rightJSON) +} + +// Numeric helpers are kept here so future schema keywords can use the same +// exact representation as the validated value. +func numberString(value any) string { + switch typed := value.(type) { + case json.Number: + return typed.String() + case float64: + return strconv.FormatFloat(typed, 'g', -1, 64) + case int: + return strconv.Itoa(typed) + case int64: + return strconv.FormatInt(typed, 10) + default: + return "" + } +} diff --git a/internal/toolcall/toolcall_test.go b/internal/toolcall/toolcall_test.go new file mode 100644 index 000000000..77fc5fa57 --- /dev/null +++ b/internal/toolcall/toolcall_test.go @@ -0,0 +1,261 @@ +package toolcall + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestParseRequestCanonicalChoiceAndSpecs(t *testing.T) { + tools := json.RawMessage(`[ + {"type":"function","function":{"name":"read_file","description":"read a file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}, + {"type":"function","function":{"name":"write_file","parameters":{"type":"object","properties":{"path":{"type":"string"},"body":{"type":"string"}},"required":["path"]}}} + ]`) + request, err := ParseRequest(ProtocolChat, tools, json.RawMessage(`{"type":"function","function":{"name":"read_file"}}`), boolPtr(false), RepairSafe) + if err != nil { + t.Fatal(err) + } + if len(request.Specs) != 2 || request.Specs[0].Name != "read_file" { + t.Fatalf("specs = %+v", request.Specs) + } + if request.Choice.Mode != ChoiceNamed || request.Choice.Name != "read_file" { + t.Fatalf("choice = %+v", request.Choice) + } + if request.Policy.Parallel == nil || *request.Policy.Parallel { + t.Fatalf("parallel = %+v", request.Policy.Parallel) + } + if request.Policy.Repair != RepairSafe { + t.Fatalf("repair = %q", request.Policy.Repair) + } +} + +func TestParseRequestRejectsUndeclaredNamedTool(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`) + _, err := ParseRequest(ProtocolChat, tools, json.RawMessage(`{"type":"function","function":{"name":"shell"}}`), nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "undeclared") { + t.Fatalf("err = %v", err) + } +} + +func TestParseRequestRejectsRequiredWithoutTools(t *testing.T) { + _, err := ParseRequest(ProtocolChat, nil, json.RawMessage(`"required"`), nil, RepairSafe) + if err == nil { + t.Fatal("expected required without tools to fail") + } +} + +func TestParseRequestRejectsDuplicateToolNames(t *testing.T) { + tools := json.RawMessage(`[ + {"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}, + {"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}} + ]`) + _, err := ParseRequest(ProtocolChat, tools, nil, nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "duplicate") { + t.Fatalf("err = %v", err) + } +} + +func TestParseRequestRejectsInvalidSchema(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":"not-an-object"}}}]`) + _, err := ParseRequest(ProtocolChat, tools, nil, nil, RepairSafe) + if err == nil || !strings.Contains(err.Error(), "properties") { + t.Fatalf("err = %v", err) + } +} + +func TestReducerStableIDAcrossFragments(t *testing.T) { + request, parseErr := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`), nil, nil, RepairSafe) + if parseErr != nil { + t.Fatal(parseErr) + } + reducer := NewReducer(request) + chunks := []ChatDelta{ + {ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":`}}}, + {ToolCalls: []ChatToolDelta{{Arguments: `"a.go"}`}}}, + } + for index := range chunks { + if _, err := reducer.Absorb(chunks[index]); err != nil { + t.Fatal(err) + } + } + result, err := reducer.Finish("done") + if err != nil { + t.Fatal(err) + } + if result.Status != TurnToolCalls || len(result.Calls) != 1 { + t.Fatalf("result = %+v", result) + } + if string(result.Calls[0].Arguments) != `{"path":"a.go"}` { + t.Fatalf("args = %s", result.Calls[0].Arguments) + } +} + +func TestReducerSeparatesSameNameDifferentID(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + zero := 0 + chunks := []ChatDelta{ + {ToolCalls: []ChatToolDelta{{Index: &zero, ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}}, + {ToolCalls: []ChatToolDelta{{Index: &zero, ID: "call_2", Name: "read_file", Arguments: `{"path":"b"}`}}, FinishReason: "tool_calls"}, + } + for index := range chunks { + if _, err := reducer.Absorb(chunks[index]); err != nil { + t.Fatal(err) + } + } + result, err := reducer.Finish("done") + if err != nil { + t.Fatal(err) + } + if len(result.Calls) != 2 { + t.Fatalf("calls = %+v", result.Calls) + } + if string(result.Calls[0].Arguments) != `{"path":"a"}` || string(result.Calls[1].Arguments) != `{"path":"b"}` { + t.Fatalf("calls = %+v", result.Calls) + } +} + +func TestReducerRejectsMissingTerminalFrame(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{Content: "partial"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("eof") + if err == nil || result.Status != TurnTruncated { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsTruncatedArguments(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "run", Arguments: `{"cmd":"rm -rf /tmp/fo`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRequiredChoiceViolation(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), json.RawMessage(`"required"`), nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{Content: "I cannot call tools."}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerNoneChoiceViolation(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`), json.RawMessage(`"none"`), nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{}`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsToolCallsFinishWithoutCalls(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{Content: "no call", FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsLengthFinishEvenWhenArgumentsParse(t *testing.T) { + request, _ := ParseRequest(ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`), nil, nil, RepairSafe) + reducer := NewReducer(request) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}, FinishReason: "length"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err != nil || result.Status != TurnTruncated { + t.Fatalf("result=%+v err=%v", result, err) + } +} + +func TestReducerRejectsUnsolicitedCallsWhenRequestDeclaresNoTools(t *testing.T) { + reducer := NewReducer(Request{}) + if _, err := reducer.Absorb(ChatDelta{ToolCalls: []ChatToolDelta{{ID: "call_1", Name: "read_file", Arguments: `{"path":"a"}`}}, FinishReason: "tool_calls"}); err != nil { + t.Fatal(err) + } + result, err := reducer.Finish("done") + if err == nil || result.Status != TurnInvalid { + t.Fatalf("result=%+v err=%v", result, err) + } + out := RenderChat(result) + if out.FinishReason != "error" || len(out.Calls) != 0 { + t.Fatalf("undeclared call rendered: %+v", out) + } +} + +func TestRenderMessagesAndResponsesRejectInvalidTurn(t *testing.T) { + invalid := TurnResult{Status: TurnInvalid, Error: "bad arguments", Calls: []Call{{Name: "read_file", InternalID: "call_1", Status: CallInvalid}}} + if _, err := RenderMessagesBlocks(invalid); err == nil { + t.Fatal("messages renderer accepted an invalid turn") + } + if _, err := RenderResponsesItems(invalid); err == nil { + t.Fatal("responses renderer accepted an invalid turn") + } +} + +func TestValidateArgumentsResolvesLocalSchemaRefs(t *testing.T) { + spec := Spec{Name: "read_file", Parameters: json.RawMessage(`{ + "type":"object", + "properties":{"file":{"$ref":"#/$defs/file"}}, + "required":["file"], + "$defs":{"file":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}} + }`)} + if _, _, err := ValidateArguments(spec, `{"file":{}}`, RepairSafe); err == nil || !strings.Contains(err.Error(), "path") { + t.Fatalf("missing $ref required property error = %v", err) + } + if _, _, err := ValidateArguments(spec, `{"file":{"path":"README.md"}}`, RepairSafe); err != nil { + t.Fatalf("valid $ref arguments rejected: %v", err) + } + rootRef := Spec{Name: "root_ref", Parameters: json.RawMessage(`{"$ref":"#/$defs/root","$defs":{"root":{"type":"object","properties":{"value":{"type":"integer"}},"required":["value"]}}}`)} + if _, _, err := ValidateArguments(rootRef, `{"value":"not-an-integer"}`, RepairSafe); err == nil { + t.Fatal("root $ref accepted a non-integer") + } + external := Spec{Name: "external", Parameters: json.RawMessage(`{"$ref":"https://example.com/schema.json"}`)} + if err := ValidateSchema(external.Parameters); err == nil { + t.Fatal("external $ref was accepted as a local schema") + } +} + +func TestRenderChatMarksToolCalls(t *testing.T) { + result := TurnResult{Status: TurnToolCalls, UpstreamTerminal: "done", FinishReason: "stop", Calls: []Call{{InternalID: "call_1", Name: "read_file", Arguments: json.RawMessage(`{"path":"a"}`), Status: CallCompleted}}} + out := RenderChat(result) + if out.FinishReason != "tool_calls" { + t.Fatalf("finish = %q", out.FinishReason) + } + if len(out.Calls) != 1 || out.Calls[0].Name != "read_file" { + t.Fatalf("calls = %+v", out.Calls) + } +} + +func TestRenderChatDropsToolCallsFromTruncatedTurn(t *testing.T) { + out := RenderChat(TurnResult{Status: TurnTruncated, FinishReason: "length", Text: "partial", Calls: []Call{{InternalID: "call_1", Name: "read_file", Arguments: json.RawMessage(`{"path":"a"}`), Status: CallCompleted}}}) + if out.FinishReason != "length" || out.Text != "partial" || len(out.Calls) != 0 { + t.Fatalf("truncated turn exposed calls: %+v", out) + } +} + +func TestRenderChatDoesNotTurnFailureIntoSavableOutput(t *testing.T) { + out := RenderChat(TurnResult{Status: TurnInvalid, Error: "bad", Text: "partial", Calls: []Call{{Name: "read_file", Status: CallInvalid}}}) + if out.FinishReason != "error" || out.Text != "" || len(out.Calls) != 0 { + t.Fatalf("failed turn rendered as success: %+v", out) + } +} + +func boolPtr(value bool) *bool { return &value } diff --git a/internal/translate/compat.go b/internal/translate/compat.go index 8ec626f74..2ce4cc8f9 100644 --- a/internal/translate/compat.go +++ b/internal/translate/compat.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "strings" + + "github.com/caigee-cmd/cli2api/internal/toolcall" ) // RestoreResponseToolNames only visits protocol containers, never user content @@ -249,9 +251,9 @@ func translateResponses(request ResponsesRequest) (ChatRequest, map[string]Respo if err != nil { return ChatRequest{}, nil, err } - // Codex Desktop compact / recovery turns can keep a tool_choice while - // tools normalize to empty (hosted shells dropped, etc). Drop the - // orphan choice instead of failing the whole turn. + // A hosted-only tool list may normalize to empty while `auto` remains. That + // degrades to unspecified; required/named must fail validation instead of + // being silently cleared. chat.ToolChoice = sanitizeToolChoice(chat.Tools, toolChoice) chat.ResponseFormat, err = translateResponsesTextFormat(request.Text) if err != nil { @@ -784,104 +786,38 @@ func ValidateChatRequest(request *ChatRequest) error { return fmt.Errorf("max_tokens and max_completion_tokens are mutually exclusive") } request.ToolChoice = sanitizeToolChoice(request.Tools, request.ToolChoice) - return validateToolChoice(request.Tools, request.ToolChoice) + _, err := toolcall.ParseRequest(toolcall.ProtocolChat, request.Tools, request.ToolChoice, request.ParallelToolCalls, toolcall.RepairSafe) + return err } -// sanitizeToolChoice drops orphan tool_choice values when tools are empty, and -// clears named tool choices that no longer exist after tool normalization. +// sanitizeToolChoice only degrades an orphan `auto` to unspecified. Every +// stronger choice is left in place for the canonical parser to reject: silently +// clearing `required` or a named tool would turn a failed tool request into a +// successful text turn. func sanitizeToolChoice(tools, choice json.RawMessage) json.RawMessage { if emptyJSON(choice) { return nil } if emptyJSON(tools) { - return nil + return dropOrphanAuto(choice) } var declared []map[string]json.RawMessage if json.Unmarshal(tools, &declared) != nil || len(declared) == 0 { - return nil - } - names := make(map[string]bool, len(declared)) - for _, tool := range declared { - name, _ := rawJSONString(tool["name"]) - if name == "" { - fn, _ := tool["function"] - var function map[string]json.RawMessage - if json.Unmarshal(fn, &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" { - names[strings.TrimSpace(name)] = true - } - } - if text, ok := rawJSONString(choice); ok { - switch strings.ToLower(strings.TrimSpace(text)) { - case "none", "auto", "required": - return choice - default: - if names[strings.TrimSpace(text)] { - return choice - } - return nil - } + return dropOrphanAuto(choice) } - var object map[string]json.RawMessage - if json.Unmarshal(choice, &object) != nil { - return choice - } - name := rawMapString(object, "name") - if name == "" { - var function map[string]json.RawMessage - if json.Unmarshal(object["function"], &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" && !names[strings.TrimSpace(name)] { + return choice +} + +func dropOrphanAuto(choice json.RawMessage) json.RawMessage { + if text, ok := rawJSONString(choice); ok && strings.EqualFold(strings.TrimSpace(text), "auto") { return nil } return choice } func validateToolChoice(tools, choice json.RawMessage) error { - if emptyJSON(choice) { - return nil - } - if emptyJSON(tools) { - return fmt.Errorf("tool_choice requires tools") - } - var declared []map[string]json.RawMessage - if err := json.Unmarshal(tools, &declared); err != nil || len(declared) == 0 { - return fmt.Errorf("tool_choice requires tools") - } - names := make(map[string]bool, len(declared)) - for _, tool := range declared { - name, _ := rawJSONString(tool["name"]) - if name == "" { - fn, _ := tool["function"] - var function map[string]json.RawMessage - if json.Unmarshal(fn, &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" { - names[strings.TrimSpace(name)] = true - } - } - var object map[string]json.RawMessage - if json.Unmarshal(choice, &object) != nil { - return nil - } - name := rawMapString(object, "name") - if name == "" { - var function map[string]json.RawMessage - if json.Unmarshal(object["function"], &function) == nil { - name, _ = rawJSONString(function["name"]) - } - } - if name != "" && !names[strings.TrimSpace(name)] { - return fmt.Errorf("tool_choice references undeclared tool %q", name) - } - return nil + _, err := toolcall.ParseRequest(toolcall.ProtocolChat, tools, choice, nil, toolcall.RepairSafe) + return err } func mergeJSONArray(left, right json.RawMessage) json.RawMessage { diff --git a/internal/translate/compat_test.go b/internal/translate/compat_test.go index 6e826870c..50ef13747 100644 --- a/internal/translate/compat_test.go +++ b/internal/translate/compat_test.go @@ -6,21 +6,15 @@ import ( "testing" ) -func TestTranslateResponsesDropsOrphanToolChoiceWhenToolsEmpty(t *testing.T) { - chat, err := TranslateResponses(ResponsesRequest{ +func TestTranslateResponsesRejectsNamedChoiceWhenToolsEmpty(t *testing.T) { + _, err := TranslateResponses(ResponsesRequest{ Model: "devin/gpt-5-6-sol", Input: json.RawMessage(`[{"role":"user","content":[{"type":"input_text","text":"compact this conversation"}]}]`), Tools: json.RawMessage(`[{"type":"mcp","server_label":"codex_app"},{"type":"web_search"}]`), ToolChoice: json.RawMessage(`{"type":"function","name":"exec_command"}`), }) - if err != nil { - t.Fatal(err) - } - if len(chat.Tools) > 0 { - t.Fatalf("tools=%s want empty after hosted shells drop", chat.Tools) - } - if len(chat.ToolChoice) > 0 { - t.Fatalf("tool_choice=%s want dropped", chat.ToolChoice) + if err == nil || !strings.Contains(err.Error(), "tool_choice") { + t.Fatalf("named choice without tools error = %v", err) } } diff --git a/internal/translate/native_responses.go b/internal/translate/native_responses.go index d11a68c08..65e2ededc 100644 --- a/internal/translate/native_responses.go +++ b/internal/translate/native_responses.go @@ -143,6 +143,16 @@ func (r *NativeResponsesRequest) Compat() (ResponsesTranslation, error) { return TranslateResponsesRequest(source) } +// ToolingFields returns the request's tool declarations, tool_choice and +// parallel_tool_calls as the client sent them. The native adapter owns their +// dialect; routing parses them through the same canonical model as Chat. +func (r *NativeResponsesRequest) ToolingFields() (tools, choice, parallel json.RawMessage) { + if r == nil { + return nil, nil, nil + } + return r.fields["tools"], r.fields["tool_choice"], r.fields["parallel_tool_calls"] +} + // RequestedReasoningEffort is the client's reasoning.effort, empty when absent. func (r *NativeResponsesRequest) RequestedReasoningEffort() string { var reasoning struct { diff --git a/internal/translate/responses_collect_test.go b/internal/translate/responses_collect_test.go index 5ec343c49..da961495a 100644 --- a/internal/translate/responses_collect_test.go +++ b/internal/translate/responses_collect_test.go @@ -46,3 +46,18 @@ func TestCollectResponsesRejectsTerminalWithoutResponse(t *testing.T) { t.Fatalf("missing response error = %v", err) } } + +func TestCollectResponsesKeepsEventFinishReason(t *testing.T) { + // The SSE event type is authoritative even when the embedded response + // object claims a different status. The collector must expose the event's + // finish so the non-stream validator can reject the disagreement. + sse := "event: response.incomplete\n" + + "data: {\"type\":\"response.incomplete\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n" + got, err := CollectResponses(strings.NewReader(sse)) + if err != nil { + t.Fatal(err) + } + if got.FinishReason != "length" { + t.Fatalf("event finish reason lost: %q", got.FinishReason) + } +} diff --git a/internal/translate/session_seed.go b/internal/translate/session_seed.go index e22599fb9..c849d38bb 100644 --- a/internal/translate/session_seed.go +++ b/internal/translate/session_seed.go @@ -261,7 +261,6 @@ func compactSessionJSON(raw json.RawMessage) string { return compact.String() } - // PrefixSessionSeed is the cache-affine part of ContentSessionSeed: model, // tools and the leading system/developer prefix only. It deliberately excludes // the first user message so workbuddy2api-hub-style sharding does not scatter From ee93142e969ccf74ee743d63d7d7f3a4fce806d4 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:34:54 +0800 Subject: [PATCH 2/4] feat(providers): canonical tool profiles and honest retry accounting Adapters now derive their tool payload from the canonical toolcall profile instead of each package reshaping tools on its own, so declared tools, tool_choice and parallel_tool_calls reach the upstream request body unchanged. Adapters also replay a transient failure in place and report the internal retry count upward, keep the upstream Retry-After hint, and fail a stream that ends without a terminal frame instead of relaying it as success. --- .../unreleased/provider-tool-profiles.md | 9 + internal/providers/client_ua.go | 8 +- internal/providers/codex/sse.go | 45 ++- internal/providers/codex/sse_test.go | 46 +++ internal/providers/devin/chat.go | 1 + internal/providers/devin/payload.go | 44 +++ internal/providers/devin/wire.go | 4 + internal/providers/devin/wire_test.go | 1 + internal/providers/interfaces.go | 9 + internal/providers/kimi/chat.go | 23 +- internal/providers/kimi/flows_test.go | 12 + internal/providers/meta/client.go | 3 +- internal/providers/meta/constants.go | 14 +- internal/providers/meta/meta_test.go | 1 - internal/providers/meta/oauth.go | 18 +- internal/providers/meta/sse.go | 45 ++- .../providers/minimaxcode/minimaxcode_test.go | 20 ++ internal/providers/minimaxcode/sse.go | 19 +- internal/providers/opencode/opencode_test.go | 57 ++++ internal/providers/opencode/payload.go | 20 +- internal/providers/opencode/sse.go | 22 +- internal/providers/qoder/direct.go | 59 +++- internal/providers/qoder/terminal_test.go | 64 +++++ internal/providers/qoder/tool_stream.go | 5 +- internal/providers/qoder/tool_tags.go | 22 +- internal/providers/qoder/tool_tags_test.go | 26 +- internal/providers/retry_after.go | 30 ++ internal/providers/retry_after_test.go | 20 ++ internal/providers/retry_count.go | 46 +++ internal/providers/toolprofile.go | 102 +++++++ internal/providers/toolprofile_test.go | 79 ++++++ internal/providers/trae/checkin.go | 4 +- internal/providers/trae/checkin_test.go | 4 + internal/providers/trae/client.go | 64 +++-- internal/providers/trae/client_test.go | 48 ++++ internal/providers/trae/payload.go | 4 +- internal/providers/trae/sse.go | 60 +++- internal/providers/trae/terminal_test.go | 69 +++++ internal/providers/workbuddy/client.go | 62 ++-- internal/providers/workbuddy/client_test.go | 8 +- internal/providers/workbuddy/credential.go | 4 +- .../providers/workbuddy/credential_test.go | 5 +- internal/providers/workbuddy/payload.go | 11 +- internal/providers/workbuddy/sse.go | 264 +++++++++++++++--- internal/providers/workbuddy/terminal_test.go | 148 ++++++++++ internal/providers/zhipu/chat.go | 23 +- internal/providers/zhipu/zhipu_test.go | 12 + 47 files changed, 1493 insertions(+), 171 deletions(-) create mode 100644 changelog/unreleased/provider-tool-profiles.md create mode 100644 internal/providers/qoder/terminal_test.go create mode 100644 internal/providers/retry_after.go create mode 100644 internal/providers/retry_after_test.go create mode 100644 internal/providers/retry_count.go create mode 100644 internal/providers/toolprofile.go create mode 100644 internal/providers/toolprofile_test.go create mode 100644 internal/providers/trae/terminal_test.go create mode 100644 internal/providers/workbuddy/terminal_test.go diff --git a/changelog/unreleased/provider-tool-profiles.md b/changelog/unreleased/provider-tool-profiles.md new file mode 100644 index 000000000..71c00c8da --- /dev/null +++ b/changelog/unreleased/provider-tool-profiles.md @@ -0,0 +1,9 @@ +### English + +- Give every adapter the canonical tool profile from `internal/toolcall`, so declared tools, tool choice and parallel calls reach the upstream payload unchanged. +- Replay a transient failure inside the adapter and report the internal retry count, keep an upstream `Retry-After` instead of a generic backoff, and stop a stream that ends without a terminal frame. + +### 中文 + +- 各适配器统一使用 `internal/toolcall` 的规范工具档案,声明的工具、工具选择与并行调用原样进入上游请求体。 +- 瞬时失败由适配器就地重放并回报内部重试次数,保留上游 `Retry-After` 而非通用退避,并对没有终态帧的流立即结束。 diff --git a/internal/providers/client_ua.go b/internal/providers/client_ua.go index 419e9a1ad..f0672e346 100644 --- a/internal/providers/client_ua.go +++ b/internal/providers/client_ua.go @@ -34,16 +34,12 @@ func ClientUserAgentFromContext(ctx context.Context) string { // WithConversation records the gateway session key so a provider can keep one // upstream conversation id across the turns of a chat. Routing still owns the -// key; this only carries it. +// key; this only carries it. An empty key clears any inherited conversation. func WithConversation(ctx context.Context, key string) context.Context { if ctx == nil { ctx = context.Background() } - key = strings.TrimSpace(key) - if key == "" { - return ctx - } - return context.WithValue(ctx, conversationKey{}, key) + return context.WithValue(ctx, conversationKey{}, strings.TrimSpace(key)) } // ConversationFromContext returns the session key set by WithConversation, or diff --git a/internal/providers/codex/sse.go b/internal/providers/codex/sse.go index c5549a33d..c07d6a091 100644 --- a/internal/providers/codex/sse.go +++ b/internal/providers/codex/sse.go @@ -261,6 +261,16 @@ func (c *streamConverter) handleEvent(event, payload string) { c.finishReason = "stop" if typ == "response.incomplete" { c.finishReason = "length" + } else { + for _, item := range resp.Response.Output { + var probe struct { + Type string `json:"type"` + } + if json.Unmarshal(item, &probe) == nil && isResponsesToolItem(probe.Type) { + c.finishReason = "tool_calls" + break + } + } } c.sawTerminal = true c.emitUsage() @@ -270,15 +280,36 @@ func (c *streamConverter) handleEvent(event, payload string) { var errObj struct { Message string `json:"message"` Code string `json:"code"` + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + Response struct { + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + } `json:"response"` } _ = json.Unmarshal([]byte(payload), &errObj) - c.emitDone() + message := firstNonEmpty(errObj.Message, errObj.Error.Message, errObj.Response.Error.Message, "upstream response failed") + code := firstNonEmpty(errObj.Code, errObj.Error.Code, errObj.Response.Error.Code, "upstream_error") + c.emitError(message, code) c.sawTerminal = true case "response.created": // no-op; gateway synthesizes its own response.created } } +func isResponsesToolItem(kind string) bool { + switch kind { + case "function_call", "custom_tool_call", "local_shell_call", "mcp_call": + return true + default: + return false + } +} + func (c *streamConverter) emitContent(text string) { if text == "" { return @@ -401,6 +432,18 @@ func (c *streamConverter) emitDone() { _, _ = c.writer.Write([]byte("data: [DONE]\n\n")) } +func (c *streamConverter) emitError(message, code string) { + payload, err := json.Marshal(map[string]any{"error": map[string]any{ + "message": message, + "code": code, + "type": "upstream_error", + }}) + if err != nil { + return + } + _, _ = c.writer.Write([]byte("data: " + string(payload) + "\n\n")) +} + func (c *streamConverter) writeChunk(obj map[string]any) { obj["object"] = "chat.completion.chunk" obj["model"] = c.model diff --git a/internal/providers/codex/sse_test.go b/internal/providers/codex/sse_test.go index cf10423a6..1f57ca0e5 100644 --- a/internal/providers/codex/sse_test.go +++ b/internal/providers/codex/sse_test.go @@ -47,6 +47,52 @@ data: {"type":"response.completed","response":{"status":"completed","usage":{"in } } +func TestRewriteStreamMapsToolOutputToToolCallsFinish(t *testing.T) { + sse := `event: response.output_item.added +data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}} + +event: response.function_call_arguments.done +data: {"type":"response.function_call_arguments.done","output_index":0,"item_id":"fc_1","arguments":"{\"city\":\"Tokyo\"}"} + +event: response.completed +data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":1,"output_tokens":1},"output":[{"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}]}} + +` + stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol") + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(stream.Reader) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), `"finish_reason":"tool_calls"`) { + t.Fatalf("tool output finished without tool_calls: %s", body) + } +} + +func TestRewriteStreamFailureIsAnErrorNotStop(t *testing.T) { + sse := `event: response.failed +data: {"type":"response.failed","response":{"status":"failed","error":{"message":"quota exhausted","code":"insufficient_quota"}}} + +` + stream, err := rewriteStream(strings.NewReader(sse), "gpt-6.1-sol") + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(stream.Reader) + if err != nil { + t.Fatal(err) + } + out := string(body) + if !strings.Contains(out, `"error"`) || !strings.Contains(out, "quota exhausted") { + t.Fatalf("failure was not relayed as an error: %s", out) + } + if strings.Contains(out, `"finish_reason":"stop"`) || strings.Contains(out, "[DONE]") { + t.Fatalf("failure was turned into a successful terminal: %s", out) + } +} + // An item that is not a tool call must not consume a tool-call index or emit a // chunk, otherwise a reasoning item would shift every later call. func TestRewriteStreamIgnoresNonToolOutputItems(t *testing.T) { diff --git a/internal/providers/devin/chat.go b/internal/providers/devin/chat.go index 86b6b09c1..e71c081ca 100644 --- a/internal/providers/devin/chat.go +++ b/internal/providers/devin/chat.go @@ -223,6 +223,7 @@ func (c *Client) buildChatHTTPRequestFromPayload(ctx context.Context, credential payload.System, payload.Prompts, payload.Tools, + payload.ToolChoice, payload.Temperature, payload.MaxTokens, "", diff --git a/internal/providers/devin/payload.go b/internal/providers/devin/payload.go index 284000337..88408c73f 100644 --- a/internal/providers/devin/payload.go +++ b/internal/providers/devin/payload.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/caigee-cmd/cli2api/internal/providers" + chatpb "github.com/caigee-cmd/cli2api/internal/providers/devin/devinpb/chat_pb" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -24,6 +25,7 @@ type ChatPayload struct { System string Prompts []Prompt Tools []Tool + ToolChoice *chatpb.ChatToolChoice Temperature *float64 MaxTokens int ModelUID string @@ -83,6 +85,7 @@ func BuildChatPayload(req translate.ChatRequest, catalogLevels map[string][]stri System: system, Prompts: prompts, Tools: tools, + ToolChoice: parseToolChoice(req.ToolChoice, aliases), Temperature: temp, MaxTokens: maxTokens, ModelUID: modelUID, @@ -269,6 +272,47 @@ func parseTools(raw json.RawMessage, aliases *toolAliasMaps) []Tool { return out } +func parseToolChoice(raw json.RawMessage, aliases *toolAliasMaps) *chatpb.ChatToolChoice { + if len(raw) == 0 || string(raw) == "null" { + return nil + } + var text string + if json.Unmarshal(raw, &text) == nil { + switch strings.ToLower(strings.TrimSpace(text)) { + case "auto", "none", "required": + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: strings.ToLower(strings.TrimSpace(text))}} + default: + name := strings.TrimSpace(text) + if name == "" { + return nil + } + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}} + } + } + var object map[string]any + if json.Unmarshal(raw, &object) != nil { + return nil + } + kind, _ := object["type"].(string) + kind = strings.ToLower(strings.TrimSpace(kind)) + switch kind { + case "none", "auto", "required": + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_OptionName{OptionName: kind}} + case "function", "custom", "tool": + name, _ := object["name"].(string) + if fn, ok := object["function"].(map[string]any); ok { + name, _ = fn["name"].(string) + } + name = strings.TrimSpace(name) + if name == "" { + return nil + } + return &chatpb.ChatToolChoice{Choice: &chatpb.ChatToolChoice_ToolName{ToolName: aliases.alias(name)}} + default: + return nil + } +} + func expandNamespaceTools(raw json.RawMessage, namespace string) []Tool { var wrapper struct { Tools []json.RawMessage `json:"tools"` diff --git a/internal/providers/devin/wire.go b/internal/providers/devin/wire.go index ab6110d52..5b386a655 100644 --- a/internal/providers/devin/wire.go +++ b/internal/providers/devin/wire.go @@ -224,6 +224,7 @@ func BuildGetChatMessageRequest( systemPrompt string, prompts []Prompt, tools []Tool, + toolChoice *chatpb.ChatToolChoice, temperature *float64, maxTokens int, sessionID string, @@ -252,6 +253,9 @@ func BuildGetChatMessageRequest( PlannerMode: commonpb.ConversationalPlannerMode_CONVERSATIONAL_PLANNER_MODE_DEFAULT, ChatModelUid: chatModelUID, } + if toolChoice != nil { + req.ToolChoice = toolChoice + } if strings.TrimSpace(systemPrompt) != "" { req.Prompt = systemPrompt } diff --git a/internal/providers/devin/wire_test.go b/internal/providers/devin/wire_test.go index d7e0c28e3..f873bec5b 100644 --- a/internal/providers/devin/wire_test.go +++ b/internal/providers/devin/wire_test.go @@ -47,6 +47,7 @@ func TestChatRequestWireContract(t *testing.T) { Images: []Image{{Base64Data: "aGVsbG8=", MimeType: "image/png"}}, Thinking: "reason", Signature: []byte("signature"), SignatureType: "type"}}, []Tool{{Name: "lookup", Description: "description", Parameters: []byte(`{"type":"object"}`)}}, + nil, &temperature, 1234, t.Name(), "cascade") if err != nil { t.Fatal(err) diff --git a/internal/providers/interfaces.go b/internal/providers/interfaces.go index 4feb11732..02163bb06 100644 --- a/internal/providers/interfaces.go +++ b/internal/providers/interfaces.go @@ -123,6 +123,8 @@ type ChatOutcome struct { // ReasoningLevel is the clamped reasoning level actually sent upstream, // empty when the provider did not include one in the payload. ReasoningLevel string + // InternalRetries counts same-account replays the adapter performed. + InternalRetries int } // ResolvedChat carries provider-side metadata for a stream request that the @@ -131,6 +133,9 @@ type ResolvedChat struct { // ReasoningLevel is the clamped reasoning level actually sent upstream, // empty when the provider did not include one in the payload. ReasoningLevel string + // InternalRetries counts same-account replays the adapter performed + // before opening this stream. + InternalRetries int } // ProviderChat executes chat for one account. Stream implementations return @@ -341,6 +346,10 @@ type Error struct { Code string Type string RetryAfter time.Duration + // InternalRetries counts upstream requests the adapter already replayed + // before returning this failure. The executor adds it to the route attempt + // so one route attempt does not hide several wire requests. + InternalRetries int } func (e *Error) Error() string { diff --git a/internal/providers/kimi/chat.go b/internal/providers/kimi/chat.go index 48e37a1e1..61a0211d8 100644 --- a/internal/providers/kimi/chat.go +++ b/internal/providers/kimi/chat.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -201,16 +202,25 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err if err != nil { return providers.ChatOutcome{}, err } + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -239,6 +249,13 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("kimi stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("kimi stream: %s", message) + } if chunk.Usage != nil { if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage = chatUsage{ @@ -262,6 +279,7 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err } if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -280,6 +298,9 @@ func collectChatStream(body io.Reader, model string) (providers.ChatOutcome, err } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("kimi stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/kimi/flows_test.go b/internal/providers/kimi/flows_test.go index 0b3a41f91..ca7969234 100644 --- a/internal/providers/kimi/flows_test.go +++ b/internal/providers/kimi/flows_test.go @@ -1032,3 +1032,15 @@ func TestDeviceLoginPendingDoesNotWidenInterval(t *testing.T) { t.Fatalf("pending widened the interval to %v", got) } } + +func TestCollectChatStreamRejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatStream(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "kimi-k2"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatStream(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "kimi-k2"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} diff --git a/internal/providers/meta/client.go b/internal/providers/meta/client.go index c79e4d4e5..c6edd70c6 100644 --- a/internal/providers/meta/client.go +++ b/internal/providers/meta/client.go @@ -38,7 +38,7 @@ type Client struct { transports proxyutil.TransportCache - nowFn func() time.Time + nowFn func() time.Time authHost string // test override for AuthHost mintURL string // test override for MintURL @@ -163,7 +163,6 @@ func (c *Client) Probe(ctx context.Context, accountID string) (providers.Account return providers.AccountHealth{Ready: true, Hot: true, UID: uid}, nil } - // Quota returns nil — Meta Muse does not expose a usage/quota endpoint // in CPA 8.0.40; the console shows "unknown" rather than a fake zero. func (c *Client) Quota(ctx context.Context, accountID string) (*providers.QuotaInfo, error) { diff --git a/internal/providers/meta/constants.go b/internal/providers/meta/constants.go index 677ce49aa..2cd05f166 100644 --- a/internal/providers/meta/constants.go +++ b/internal/providers/meta/constants.go @@ -15,10 +15,10 @@ const ( // Wire constants aligned with CPA v8.0.40 (internal/auth/meta + meta_executor). const ( - ClientID = "1031625952748946" - AuthHost = "https://auth.meta.com" - ChatBase = "https://api.meta.ai/v1" - MintURL = "https://api.meta.ai/muse-code/key" + ClientID = "1031625952748946" + AuthHost = "https://auth.meta.com" + ChatBase = "https://api.meta.ai/v1" + MintURL = "https://api.meta.ai/muse-code/key" DeviceAuthorizationPath = "/oidc/device/authorization/" TokenPath = "/oidc/device/token/" @@ -27,9 +27,9 @@ const ( // AuthUserAgent is sent on device/token/mint (CPA muse-code/1.0.2). AuthUserAgent = "muse-code/1.0.2" // ChatUserAgent and ClientIDHeader match CPA meta_executor fingerprints. - ChatUserAgent = "muse-build/1.3.0 (interactive; macos-aarch64; build ac7280f2aca67769d1455a8847bb502b617d50f6)" - ClientIDHeader = "tbh:tui" - ResponsesPath = "/responses" + ChatUserAgent = "muse-build/1.3.0 (interactive; macos-aarch64; build ac7280f2aca67769d1455a8847bb502b617d50f6)" + ClientIDHeader = "tbh:tui" + ResponsesPath = "/responses" ) const ( diff --git a/internal/providers/meta/meta_test.go b/internal/providers/meta/meta_test.go index bd4723e0d..876981670 100644 --- a/internal/providers/meta/meta_test.go +++ b/internal/providers/meta/meta_test.go @@ -346,7 +346,6 @@ func TestMuseAliasResolves(t *testing.T) { } } - func TestAccountProxyOverridesGlobal(t *testing.T) { store := newFakeStore() store.addAccount("a1") diff --git a/internal/providers/meta/oauth.go b/internal/providers/meta/oauth.go index 8c7dcda32..0f83199bc 100644 --- a/internal/providers/meta/oauth.go +++ b/internal/providers/meta/oauth.go @@ -223,15 +223,15 @@ func truncate(body []byte) string { func applyLoginBundle(token tokenPayload, minted mintedKeyResponse, now time.Time) Credential { dca := strings.TrimSpace(token.AccessToken) cred := Credential{ - Format: CredentialFormatOAuth, - DCAToken: dca, - AccessToken: dca, - TokenType: firstNonEmpty(token.TokenType, "Bearer"), - ExpiresIn: token.ExpiresIn, - APIKey: strings.TrimSpace(minted.APIKey), - BaseURL: normalizeBase(minted.BaseURL), - Email: strings.TrimSpace(minted.UserEmail), - Name: strings.TrimSpace(minted.UserFullName), + Format: CredentialFormatOAuth, + DCAToken: dca, + AccessToken: dca, + TokenType: firstNonEmpty(token.TokenType, "Bearer"), + ExpiresIn: token.ExpiresIn, + APIKey: strings.TrimSpace(minted.APIKey), + BaseURL: normalizeBase(minted.BaseURL), + Email: strings.TrimSpace(minted.UserEmail), + Name: strings.TrimSpace(minted.UserFullName), SubsTierName: strings.TrimSpace(minted.SubsTierName), SubsTierID: strings.TrimSpace(minted.SubsTierID), IsSubsActive: minted.IsSubsActive, diff --git a/internal/providers/meta/sse.go b/internal/providers/meta/sse.go index 3946a37ec..4a28ba8be 100644 --- a/internal/providers/meta/sse.go +++ b/internal/providers/meta/sse.go @@ -261,6 +261,16 @@ func (c *streamConverter) handleEvent(event, payload string) { c.finishReason = "stop" if typ == "response.incomplete" { c.finishReason = "length" + } else { + for _, item := range resp.Response.Output { + var probe struct { + Type string `json:"type"` + } + if json.Unmarshal(item, &probe) == nil && isResponsesToolItem(probe.Type) { + c.finishReason = "tool_calls" + break + } + } } c.sawTerminal = true c.emitUsage() @@ -270,15 +280,36 @@ func (c *streamConverter) handleEvent(event, payload string) { var errObj struct { Message string `json:"message"` Code string `json:"code"` + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + Response struct { + Error struct { + Message string `json:"message"` + Code string `json:"code"` + } `json:"error"` + } `json:"response"` } _ = json.Unmarshal([]byte(payload), &errObj) - c.emitDone() + message := firstNonEmpty(errObj.Message, errObj.Error.Message, errObj.Response.Error.Message, "upstream response failed") + code := firstNonEmpty(errObj.Code, errObj.Error.Code, errObj.Response.Error.Code, "upstream_error") + c.emitError(message, code) c.sawTerminal = true case "response.created": // no-op; gateway synthesizes its own response.created } } +func isResponsesToolItem(kind string) bool { + switch kind { + case "function_call", "custom_tool_call", "local_shell_call", "mcp_call": + return true + default: + return false + } +} + func (c *streamConverter) emitContent(text string) { if text == "" { return @@ -401,6 +432,18 @@ func (c *streamConverter) emitDone() { _, _ = c.writer.Write([]byte("data: [DONE]\n\n")) } +func (c *streamConverter) emitError(message, code string) { + payload, err := json.Marshal(map[string]any{"error": map[string]any{ + "message": message, + "code": code, + "type": "upstream_error", + }}) + if err != nil { + return + } + _, _ = c.writer.Write([]byte("data: " + string(payload) + "\n\n")) +} + func (c *streamConverter) writeChunk(obj map[string]any) { obj["object"] = "chat.completion.chunk" obj["model"] = c.model diff --git a/internal/providers/minimaxcode/minimaxcode_test.go b/internal/providers/minimaxcode/minimaxcode_test.go index 1a31cb4e8..4f645eb5e 100644 --- a/internal/providers/minimaxcode/minimaxcode_test.go +++ b/internal/providers/minimaxcode/minimaxcode_test.go @@ -326,6 +326,26 @@ func TestChatStreamToolCalls(t *testing.T) { } } +func TestAnthropicDecoderBindsArgumentsToBlockIndex(t *testing.T) { + decoder := newAnthropicDecoder() + first, _, err := decoder.frame("content_block_start", `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_1","name":"first"}}`) + if err != nil || len(first) != 1 || first[0].ToolCalls[0].Index != 0 { + t.Fatalf("first start = %+v err=%v", first, err) + } + second, _, err := decoder.frame("content_block_start", `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_2","name":"second"}}`) + if err != nil || len(second) != 1 || second[0].ToolCalls[0].Index != 1 { + t.Fatalf("second start = %+v err=%v", second, err) + } + delta, _, err := decoder.frame("content_block_delta", `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"a\":1}"}}`) + if err != nil || len(delta) != 1 || delta[0].ToolCalls[0].Index != 0 { + t.Fatalf("first delta bound to %+v err=%v", delta, err) + } + delta, _, err = decoder.frame("content_block_delta", `{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"b\":2}"}}`) + if err != nil || len(delta) != 1 || delta[0].ToolCalls[0].Index != 1 { + t.Fatalf("second delta bound to %+v err=%v", delta, err) + } +} + func TestBuildChatBodyCarriesSamplingAndToolChoice(t *testing.T) { req := translate.ChatRequest{ Model: "MiniMax-M3", diff --git a/internal/providers/minimaxcode/sse.go b/internal/providers/minimaxcode/sse.go index b2ae9903a..babf33c65 100644 --- a/internal/providers/minimaxcode/sse.go +++ b/internal/providers/minimaxcode/sse.go @@ -25,10 +25,11 @@ type toolCallDelta struct { } type anthropicDecoder struct { - sentRole bool - toolIndex int - finish string - usage streamUsage + sentRole bool + toolIndex int + toolIndexByBlock map[int]int + finish string + usage streamUsage } type streamUsage struct { @@ -143,6 +144,10 @@ func (d *anthropicDecoder) frame(eventType string, payload string) ([]openAIDelt block, _ := event["content_block"].(map[string]any) if jsonStr(block, "type") == "tool_use" { d.toolIndex++ + if d.toolIndexByBlock == nil { + d.toolIndexByBlock = map[int]int{} + } + d.toolIndexByBlock[jsonIntValue(event["index"])] = d.toolIndex call := toolCallDelta{Index: d.toolIndex, ID: jsonStr(block, "id"), Name: jsonStr(block, "name"), HasID: true, HasName: true} if call.ID == "" { call.ID = newToolID() @@ -162,7 +167,11 @@ func (d *anthropicDecoder) frame(eventType string, payload string) ([]openAIDelt } case "input_json_delta": if partial := jsonStr(delta, "partial_json"); partial != "" { - call := toolCallDelta{Index: d.toolIndex, Arguments: partial} + toolIndex := d.toolIndex + if mapped, ok := d.toolIndexByBlock[jsonIntValue(event["index"])]; ok { + toolIndex = mapped + } + call := toolCallDelta{Index: toolIndex, Arguments: partial} return []openAIDelta{{ToolCalls: []toolCallDelta{call}}}, false, nil } } diff --git a/internal/providers/opencode/opencode_test.go b/internal/providers/opencode/opencode_test.go index feb783fc0..0f2a20cfb 100644 --- a/internal/providers/opencode/opencode_test.go +++ b/internal/providers/opencode/opencode_test.go @@ -646,3 +646,60 @@ func TestQuotaFallback(t *testing.T) { t.Fatalf("zen info=%+v hits=%d/%d err=%v", info, primaryHits, fallbackHits, err) } } + +func TestBuildPayloadKeepsToolsAndMapsChoiceAcrossProtocols(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"lookup","parameters":{"type":"object"}}}]`) + cases := []struct { + protocol string + choice string + want any + }{ + {protoAnthropic, `"none"`, map[string]any{"type": "none"}}, + {protoAnthropic, `"required"`, map[string]any{"type": "any"}}, + {protoResponses, `"none"`, "none"}, + {protoResponses, `"required"`, "required"}, + {protoChat, `"none"`, "none"}, + } + for _, tc := range cases { + raw, err := buildPayload(tc.protocol, translate.ChatRequest{ + Model: "gpt-5", + Tools: tools, + ToolChoice: json.RawMessage(tc.choice), + Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "gpt-5") + if err != nil { + t.Fatalf("%s/%s: %v", tc.protocol, tc.choice, err) + } + var body map[string]any + if err := json.Unmarshal(raw, &body); err != nil { + t.Fatal(err) + } + if _, ok := body["tools"]; !ok { + t.Fatalf("%s/%s dropped tools: %s", tc.protocol, tc.choice, raw) + } + got, _ := body["tool_choice"].(map[string]any) + if wantMap, ok := tc.want.(map[string]any); ok { + for key, value := range wantMap { + if got[key] != value { + t.Fatalf("%s/%s tool_choice=%v want %v", tc.protocol, tc.choice, body["tool_choice"], tc.want) + } + } + continue + } + if got, _ := body["tool_choice"].(string); got != tc.want { + t.Fatalf("%s/%s tool_choice=%v want %v", tc.protocol, tc.choice, body["tool_choice"], tc.want) + } + } +} + +func TestCollectChatSSERejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatSSE(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "gpt-5"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "gpt-5"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "gpt-5"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} diff --git a/internal/providers/opencode/payload.go b/internal/providers/opencode/payload.go index f2febba11..0aa5f52ca 100644 --- a/internal/providers/opencode/payload.go +++ b/internal/providers/opencode/payload.go @@ -393,7 +393,7 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b if json.Unmarshal(raw, &text) == nil { switch strings.ToLower(strings.TrimSpace(text)) { case "none": - return nil, false + choice["type"] = "none" case "required", "any": choice["type"] = "any" case "auto": @@ -405,10 +405,13 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b typ, _ := object["type"].(string) switch strings.ToLower(strings.TrimSpace(typ)) { case "none": - return nil, false - case "function": + choice["type"] = "none" + case "function", "custom": function, _ := object["function"].(map[string]any) name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } if name = strings.TrimSpace(name); name != "" { choice["type"] = "tool" choice["name"] = name @@ -423,7 +426,7 @@ func anthropicToolChoice(raw json.RawMessage, parallel *bool) (map[string]any, b } return map[string]any{"type": "auto", "disable_parallel_tool_use": true}, true } - if parallelDisabled { + if parallelDisabled && choice["type"] != "none" { choice["disable_parallel_tool_use"] = true } return choice, true @@ -437,7 +440,7 @@ func responseToolChoice(raw json.RawMessage) (any, bool) { if json.Unmarshal(raw, &text) == nil { switch strings.ToLower(strings.TrimSpace(text)) { case "none": - return nil, false + return "none", true case "required", "any": return "required", true case "auto": @@ -450,15 +453,18 @@ func responseToolChoice(raw json.RawMessage) (any, bool) { return nil, true } typ, _ := object["type"].(string) - if strings.EqualFold(typ, "function") { + if strings.EqualFold(typ, "function") || strings.EqualFold(typ, "custom") { function, _ := object["function"].(map[string]any) name, _ := function["name"].(string) + if name == "" { + name, _ = object["name"].(string) + } if name = strings.TrimSpace(name); name != "" { return map[string]any{"type": "function", "name": name}, true } } if strings.EqualFold(typ, "none") { - return nil, false + return "none", true } return nil, true } diff --git a/internal/providers/opencode/sse.go b/internal/providers/opencode/sse.go index ea56a5f81..e175b13b1 100644 --- a/internal/providers/opencode/sse.go +++ b/internal/providers/opencode/sse.go @@ -601,16 +601,25 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) return providers.ChatOutcome{}, err } agg := &sseAggregate{tools: map[int]*collectedTool{}, finish: "stop"} + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -637,6 +646,13 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("opencode stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("opencode stream: %s", message) + } if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage.prompt = chunk.Usage.PromptTokens agg.usage.completion = chunk.Usage.CompletionTokens @@ -647,6 +663,7 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) agg.reasoning.WriteString(choice.Delta.ReasoningContent) if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -665,6 +682,9 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("opencode stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/qoder/direct.go b/internal/providers/qoder/direct.go index f5ac340d1..eb0ef7486 100644 --- a/internal/providers/qoder/direct.go +++ b/internal/providers/qoder/direct.go @@ -197,11 +197,12 @@ func (d *Direct) ChatNonStream(ctx context.Context, accountID string, req transl for attempt := 0; attempt < 2; attempt++ { outcome, err := d.chatNonStreamOnce(ctx, accountID, req) if err == nil { + outcome.InternalRetries = attempt return outcome, nil } last = err if !isImageConversionTimeoutErr(err) || attempt == 1 { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, withDirectRetries(err, attempt) } // hub cdd95ef: one same-account bounded retry; no rotation/cooldown. } @@ -233,7 +234,7 @@ func (d *Direct) chatNonStreamOnce(ctx context.Context, accountID string, req tr return providers.ChatOutcome{}, err } if resp.StatusCode >= 300 { - return providers.ChatOutcome{}, upstreamStatusError(resp.StatusCode, raw) + return providers.ChatOutcome{}, upstreamStatusError(resp.StatusCode, raw, resp.Header) } outcome, err := outcomeFromUpstreamSSE(prepared.model, raw, prepared.allowed) if err != nil { @@ -248,16 +249,30 @@ func (d *Direct) ChatStream(ctx context.Context, accountID string, req translate for attempt := 0; attempt < 2; attempt++ { resp, resolved, err := d.chatStreamOnce(ctx, accountID, req) if err == nil { + resolved.InternalRetries = attempt return resp, resolved, nil } last = err if !isImageConversionTimeoutErr(err) || attempt == 1 { - return nil, providers.ResolvedChat{}, err + return nil, providers.ResolvedChat{}, withDirectRetries(err, attempt) } } return nil, providers.ResolvedChat{}, last } +// withDirectRetries tags a classified error with the same-account replays the +// Direct client already performed. +func withDirectRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + var pe *providers.Error + if errors.As(err, &pe) && pe != nil { + pe.InternalRetries = retries + } + return err +} + func (d *Direct) chatStreamOnce(ctx context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { prepared, err := d.prepare(ctx, accountID, req) if err != nil { @@ -276,7 +291,7 @@ func (d *Direct) chatStreamOnce(ctx context.Context, accountID string, req trans raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() release() - return nil, providers.ResolvedChat{}, upstreamStatusError(resp.StatusCode, raw) + return nil, providers.ResolvedChat{}, upstreamStatusError(resp.StatusCode, raw, resp.Header) } resp.Body = releaseOnClose{ReadCloser: resp.Body, release: release} guarded, err := ensureMeaningfulUpstream(resp, d.ttfb) @@ -301,16 +316,23 @@ const defaultQueueRetryAfter = 5 * time.Second // clientVersionTooLowMessage explains Qoder's HTTP 430 hard gate. const clientVersionTooLowMessage = "client version too low (HTTP 430): Qoder requires a newer client version; upgrade cli2api. This is not an account or network problem." -func upstreamStatusError(status int, body []byte) error { +func upstreamStatusError(status int, body []byte, headers ...http.Header) error { message := strings.TrimSpace(string(body)) if message == "" { message = fmt.Sprintf("qoder upstream status %d", status) } + var headerHint time.Duration + if len(headers) > 0 { + headerHint = providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")) + } // 10605 is model-level queueing, not an account fault (qoder2api-hub // 6b7f65b / 67aa3ce): no cooldown, no dead mark, no failover (which would // rebind the session to another account); surface Retry-After instead. if busy := qauth.ParseBusyEnvelope(status, body); busy != nil { retry := busy.RetryAfter + if retry <= 0 { + retry = headerHint + } if retry <= 0 { retry = defaultQueueRetryAfter } @@ -338,7 +360,7 @@ func upstreamStatusError(status int, body []byte) error { case http.StatusBadRequest: kind = accounts.KindInvalidRequest } - return &providers.Error{Kind: kind, Status: status, Message: message} + return &providers.Error{Kind: kind, Status: status, Message: message, RetryAfter: headerHint} } // emptyUpstreamError mirrors the worker path's upstream_empty classification. @@ -957,7 +979,7 @@ func outcomeFromUpstreamSSE(model string, raw []byte, names ...map[string]struct if err != nil { return providers.ChatOutcome{}, err } - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { if isImageConversionTimeoutMessage(frame.errText) { return providers.ChatOutcome{}, imageConversionTimeoutError(frame.errText) } @@ -1366,6 +1388,8 @@ func newCompletionID() string { return "chatcmpl-" + strings.ReplaceAll(id, "-", "") } +var errQoderSSETerminal = errors.New("qoder SSE terminal frame") + func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { completionID := newCompletionID() var sawFinish, sawTools, sawPayload, sawError bool @@ -1385,7 +1409,10 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { if len(frame.tools) > 0 { sawTools = true } - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { + // An upstream error frame is terminal even when the same frame (or + // an earlier one) carried content. Returning nil here would let the + // final [DONE] below report a failed turn as success. sawError = true errPayload := map[string]any{"message": frame.errText, "type": "api_error", "code": frame.busyCode} if frame.busyCode != "" { @@ -1403,8 +1430,13 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { } } payload, _ := json.Marshal(map[string]any{"error": errPayload}) - _, err := fmt.Fprintf(w, "data: %s\n\n", payload) - return err + if _, writeErr := fmt.Fprintf(w, "data: %s\n\n", payload); writeErr != nil { + return writeErr + } + // The error frame is terminal. Return a sentinel so the converter + // stops before any later content or synthetic finish chunk while the + // already-written error frame is still relayed cleanly. + return errQoderSSETerminal } chunk := map[string]any{ "id": completionID, "object": "chat.completion.chunk", "model": model, @@ -1433,9 +1465,14 @@ func writeOpenAIChunks(w io.Writer, src io.Reader, model string) error { _, err = fmt.Fprintf(w, "data: %s\n\n", payload) return err }) - if err != nil { + if err != nil && !errors.Is(err, errQoderSSETerminal) { return err } + if sawError { + // The failure frame is already on the wire; no success terminal may + // follow it. + return nil + } if !sawFinish { if sawPayload { // Upstream streamed real content but was cut before the terminal diff --git a/internal/providers/qoder/terminal_test.go b/internal/providers/qoder/terminal_test.go new file mode 100644 index 000000000..4aa467d60 --- /dev/null +++ b/internal/providers/qoder/terminal_test.go @@ -0,0 +1,64 @@ +package qoder + +import ( + "bytes" + "strings" + "testing" +) + +// A buffered (non-stream) turn that produced content and then received an +// upstream error frame is a failed turn, not a successful partial answer. +func TestOutcomeFromUpstreamSSEFailsOnLateErrorFrame(t *testing.T) { + raw := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"invalid_request_error","message":"context window exceeded"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + _, err := outcomeFromUpstreamSSE("glm-5.2", []byte(raw)) + if err == nil || !strings.Contains(err.Error(), "context window exceeded") { + t.Fatalf("late error frame was ignored: %v", err) + } +} + +func TestOutcomeFromUpstreamSSEKeepsSuccessfulTurn(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" + + `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}` + "\n\n" + "data: [DONE]\n\n" + out, err := outcomeFromUpstreamSSE("glm-5.2", []byte(raw)) + if err != nil || out.Content != "hello" || out.FinishReason != "stop" { + t.Fatalf("out=%+v err=%v", out, err) + } +} + +// A frame that carries both tool-convertible content and an error must still +// terminate as an error; the converter must not emit a normal [DONE]. +func TestWriteOpenAIChunksToolFrameWithErrorStaysFailed(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"partial","tool_calls":[{"index":0,"id":"call_1","function":{"name":"lookup","arguments":"{}"}}]}}],"error":{"message":"boom","type":"api_error"}}` + "\n\n" + + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := writeOpenAIChunks(&out, strings.NewReader(raw), "glm-5.2"); err != nil { + t.Fatalf("rewrite failed: %v", err) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed a same-frame error: %q", out.String()) + } + if !strings.Contains(out.String(), "boom") { + t.Fatalf("error frame missing: %q", out.String()) + } +} + +// terminal error frame. +func TestWriteOpenAIChunksStopsAfterErrorFrame(t *testing.T) { + raw := `data: {"choices":[{"delta":{"content":"partial"}}]}` + "\n\n" + + `data: {"error":{"message":"boom","type":"api_error"}}` + "\n\n" + + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := writeOpenAIChunks(&out, strings.NewReader(raw), "glm-5.2"); err != nil { + t.Fatalf("rewrite failed: %v", err) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed an error frame: %q", out.String()) + } + if !strings.Contains(out.String(), "boom") { + t.Fatalf("error frame missing: %q", out.String()) + } +} diff --git a/internal/providers/qoder/tool_stream.go b/internal/providers/qoder/tool_stream.go index 439f26fcf..8f263f854 100644 --- a/internal/providers/qoder/tool_stream.go +++ b/internal/providers/qoder/tool_stream.go @@ -85,7 +85,7 @@ func rewriteToolTagFrames(w io.Writer, src io.Reader, allowed map[string]struct{ frame := frameFromBody(body, nil) // Pass errors / usage / structured tools / reasoning through; only // content is subject to tool-tag hold. - if frame.errText != "" && frame.content == "" && frame.reasoning == "" && len(frame.tools) == 0 { + if frame.errText != "" { if holding { if err := flushHold(""); err != nil { return err @@ -106,6 +106,9 @@ func rewriteToolTagFrames(w io.Writer, src io.Reader, allowed map[string]struct{ if frame.reasoning != "" { delta["reasoning_content"] = frame.reasoning } + if frame.content != "" { + delta["content"] = frame.content + } if decoded != nil { delta["tool_calls"] = decoded } diff --git a/internal/providers/qoder/tool_tags.go b/internal/providers/qoder/tool_tags.go index 744b85e01..f99b19e8d 100644 --- a/internal/providers/qoder/tool_tags.go +++ b/internal/providers/qoder/tool_tags.go @@ -10,23 +10,23 @@ import ( // Fake XML / marker constants mirrored from qoder2api-hub issue #140 (e6e7622) // and the shared leak-marker helpers that parse_tool_call_tags depends on. const ( - toolCallOpen = "]*)>`) - callTagCloseRE = regexp.MustCompile(`(?i)<\s*/\s*tool_call\s*>`) + callTagOpenRE = regexp.MustCompile(`(?i)<\s*tool_call\b([^>]*)>`) + callTagCloseRE = regexp.MustCompile(`(?i)<\s*/\s*tool_call\s*>`) callTagAttrNameRE = regexp.MustCompile(`(?i)\b(?:name|tool|tool_name|function)\s*=\s*(?:"([^"]+)"|'([^']+)')`) - callTagLeadRE = regexp.MustCompile(`^\s*([A-Za-z_][A-Za-z0-9_.:\-]*)\s*`) - leakMarkerRE = regexp.MustCompile(`[\[<(]*\s*assistant\s*请求调用工具\s*[\]>)]?`) - leakStructRE = regexp.MustCompile( + callTagLeadRE = regexp.MustCompile(`^\s*([A-Za-z_][A-Za-z0-9_.:\-]*)\s*`) + leakMarkerRE = regexp.MustCompile(`[\[<(]*\s*assistant\s*请求调用工具\s*[\]>)]?`) + leakStructRE = regexp.MustCompile( `name\s*=\s*["']|`) ) diff --git a/internal/providers/qoder/tool_tags_test.go b/internal/providers/qoder/tool_tags_test.go index a7db25a94..ed5479786 100644 --- a/internal/providers/qoder/tool_tags_test.go +++ b/internal/providers/qoder/tool_tags_test.go @@ -35,9 +35,9 @@ func TestParseToolCallTagsUserSample(t *testing.T) { func TestParseToolCallTagsShapes(t *testing.T) { cases := []struct { - name string - text string - allow map[string]struct{} + name string + text string + allow map[string]struct{} wantName string }{ {"bare", `Bash {"command":"ls -la"}`, map[string]struct{}{"Bash": {}}, "Bash"}, @@ -175,6 +175,26 @@ func TestRecoverToolTagStreamRewritesFakeXML(t *testing.T) { } } +func TestRecoverToolTagStreamPreservesErrorsAndSameFrameText(t *testing.T) { + allowed := map[string]struct{}{"Bash": {}} + upstream := "data: " + `{"body":{"error":{"message":"upstream exploded"},"choices":[{"delta":{"content":"partial text"}}]}}` + "\n\n" + + "data: " + `{"body":{"choices":[{"delta":{"content":"before tool","tool_calls":[{"id":"call_1","type":"function","function":{"name":"Bash","arguments":"{\"command\":\"pwd\"}"}}]}}]}}` + "\n\n" + var out strings.Builder + if err := rewriteToolTagFrames(&out, strings.NewReader(upstream), allowed); err != nil { + t.Fatal(err) + } + body := out.String() + if !strings.Contains(body, "upstream exploded") { + t.Fatalf("same-frame error dropped: %s", body) + } + if !strings.Contains(body, "before tool") { + t.Fatalf("same-frame text dropped: %s", body) + } + if !strings.Contains(body, `"tool_calls"`) || !strings.Contains(body, `"Bash"`) { + t.Fatalf("tool calls dropped: %s", body) + } +} + func TestUpstreamStatusErrorMapsImageConversionTimeout(t *testing.T) { err := upstreamStatusError(http.StatusBadGateway, []byte(`{"message":"Image conversion timeout"}`)) if !isImageConversionTimeoutErr(err) { diff --git a/internal/providers/retry_after.go b/internal/providers/retry_after.go new file mode 100644 index 000000000..2a234abc4 --- /dev/null +++ b/internal/providers/retry_after.go @@ -0,0 +1,30 @@ +package providers + +import ( + "net/http" + "strconv" + "strings" + "time" +) + +// ParseRetryAfterHeader parses an upstream Retry-After header. It accepts both +// forms defined by RFC 9110: delay-seconds and an HTTP date. A non-positive or +// unparseable value yields zero. +func ParseRetryAfterHeader(raw string) time.Duration { + text := strings.TrimSpace(raw) + if text == "" { + return 0 + } + if seconds, err := strconv.ParseFloat(text, 64); err == nil { + if seconds > 0 { + return time.Duration(seconds * float64(time.Second)) + } + return 0 + } + if at, err := http.ParseTime(text); err == nil { + if wait := time.Until(at); wait > 0 { + return wait + } + } + return 0 +} diff --git a/internal/providers/retry_after_test.go b/internal/providers/retry_after_test.go new file mode 100644 index 000000000..04749860e --- /dev/null +++ b/internal/providers/retry_after_test.go @@ -0,0 +1,20 @@ +package providers + +import ( + "net/http" + "testing" + "time" +) + +func TestParseRetryAfterHeader(t *testing.T) { + if got := ParseRetryAfterHeader("7"); got != 7*time.Second { + t.Fatalf("seconds = %v", got) + } + future := time.Now().Add(30 * time.Second).UTC().Format(http.TimeFormat) + if got := ParseRetryAfterHeader(future); got < 20*time.Second || got > 31*time.Second { + t.Fatalf("http date = %v", got) + } + if got := ParseRetryAfterHeader("not-a-delay"); got != 0 { + t.Fatalf("invalid = %v", got) + } +} diff --git a/internal/providers/retry_count.go b/internal/providers/retry_count.go new file mode 100644 index 000000000..507814370 --- /dev/null +++ b/internal/providers/retry_count.go @@ -0,0 +1,46 @@ +package providers + +import "errors" + +// retryCountError carries the number of same-account wire retries that +// preceded a failure which is not itself a *Error (for example a body read +// failure after a successful token-refresh resend). +type retryCountError struct { + err error + retries int +} + +func (e *retryCountError) Error() string { return e.err.Error() } +func (e *retryCountError) Unwrap() error { return e.err } +func (e *retryCountError) RetryCount() int { + if e == nil { + return 0 + } + return e.retries +} + +// TagInternalRetries preserves the retry count on any error shape. +func TagInternalRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + return &retryCountError{err: err, retries: retries} +} + +// InternalRetriesOf extracts the retry count from a providers.Error or a +// TagInternalRetries wrapper. +func InternalRetriesOf(err error) int { + if err == nil { + return 0 + } + var pe *Error + if errors.As(err, &pe) && pe != nil { + return pe.InternalRetries + } + type retryCounter interface{ RetryCount() int } + var counted retryCounter + if errors.As(err, &counted) && counted != nil { + return counted.RetryCount() + } + return 0 +} diff --git a/internal/providers/toolprofile.go b/internal/providers/toolprofile.go new file mode 100644 index 000000000..976567c6d --- /dev/null +++ b/internal/providers/toolprofile.go @@ -0,0 +1,102 @@ +package providers + +import ( + "strings" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +// ToolProfile is the provider-declared contract routing needs before it +// reserves an account. It is deliberately coarser than each adapter's wire +// details: a capability is advertised only when the adapter can guarantee it. +type ToolProfile struct { + Execution toolcall.ExecutionLevel `json:"execution"` + Choices []toolcall.ChoiceMode `json:"choices"` + ParallelOff bool `json:"parallel_off"` + StrictSchema bool `json:"strict_schema"` + ResultFormat string `json:"result_format"` + StableStreamID bool `json:"stable_stream_id"` +} + +func (p ToolProfile) SupportsChoice(mode toolcall.ChoiceMode) bool { + if mode == "" || mode == toolcall.ChoiceUnspecified { + return true + } + if p.Execution == toolcall.ExecutionNone { + return false + } + for _, supported := range p.Choices { + if supported == mode { + return true + } + } + return false +} + +func (p ToolProfile) SupportsTools() bool { + return p.Execution != "" && p.Execution != toolcall.ExecutionNone && len(p.Choices) > 0 +} + +func allChoices() []toolcall.ChoiceMode { + return []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone, toolcall.ChoiceRequired, toolcall.ChoiceNamed} +} + +// ToolProfileFor declares the conservative per-family tool contract. A model +// may narrow it, but no adapter may claim a capability it cannot enforce: +// choice modes and parallel-off are routing gates, not documentation. +func ToolProfileFor(provider, model string) ToolProfile { + switch strings.ToLower(strings.TrimSpace(provider)) { + case "qoder": + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: true, StrictSchema: true, ResultFormat: "native", StableStreamID: true} + case "workbuddy": + // WorkBuddy converts function schemas and tool_choice, but its normalizer + // rebuilds each function tool and drops the strict flag; the request body + // now carries parallel_tool_calls, yet the adapter cannot guarantee that + // upstream honors it. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "trae": + // Trae converts choice, but drops the client's parallel limit and the + // strict flag while rebuilding tools; `none` deletes tools instead of + // using a native selector. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "devin": + // The Connect-RPC request carries native tool definitions, tool calls, + // results and a ChatToolChoice (auto/none/required/named). The adapter + // rewrites namespaced names to stable aliases before sending. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: false} + case "command": + // Command sends tools but its request struct has no tool_choice field. + return ToolProfile{Execution: toolcall.ExecutionPrompted, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto}, ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "codex": + // The Chat-compat payload rewrites function tools into Responses shape + // and drops the strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "responses", StableStreamID: true} + case "meta": + // Same Chat-compat normalization as Codex: function tools are rebuilt + // without the strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "responses", StableStreamID: true} + case "zhipu", "kimi", "codearts": + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: true, ResultFormat: "openai_chat", StableStreamID: true} + case "qwenwork": + // Only `none` is special-cased; required/named have no native field. + return ToolProfile{Execution: toolcall.ExecutionValidated, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, ParallelOff: false, StrictSchema: false, ResultFormat: "native", StableStreamID: true} + case "kiro": + // Kiro accepts Anthropic client tools but expresses partial selection in + // the prompt; required/named cannot be guaranteed natively. + return ToolProfile{Execution: toolcall.ExecutionPrompted, Choices: []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "doubaowork": + // Tools are parsed from prompt/output and required/named are verified + // after the fact. A validated profile is still not a native guarantee. + return ToolProfile{Execution: toolcall.ExecutionValidated, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "prompt", StableStreamID: false} + case "minimaxcode": + // The Anthropic payload rebuilds each function tool as name + + // input_schema, so the OpenAI strict flag is not forwarded. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "anthropic", StableStreamID: true} + case "opencode": + // Chat/Responses/Anthropic payloads all rebuild function tools and drop + // the OpenAI strict flag. + return ToolProfile{Execution: toolcall.ExecutionNative, Choices: allChoices(), ParallelOff: false, StrictSchema: false, ResultFormat: "opencode", StableStreamID: true} + default: + return ToolProfile{} + } +} diff --git a/internal/providers/toolprofile_test.go b/internal/providers/toolprofile_test.go new file mode 100644 index 000000000..d3cfa450b --- /dev/null +++ b/internal/providers/toolprofile_test.go @@ -0,0 +1,79 @@ +package providers + +import ( + "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +func TestEveryToolProviderHasAContract(t *testing.T) { + for _, descriptor := range List() { + if !descriptor.Capabilities.Tools { + continue + } + profile := ToolProfileFor(descriptor.ID, "") + if !profile.SupportsTools() { + t.Fatalf("%s advertises tools but has no tool contract: %+v", descriptor.ID, profile) + } + if profile.Execution == toolcall.ExecutionNone || profile.ResultFormat == "" { + t.Fatalf("%s has an incomplete contract: %+v", descriptor.ID, profile) + } + seen := map[toolcall.ChoiceMode]bool{} + for _, choice := range profile.Choices { + if choice == toolcall.ChoiceUnspecified || seen[choice] { + t.Fatalf("%s has an invalid choice list: %+v", descriptor.ID, profile.Choices) + } + seen[choice] = true + } + } +} + +func TestToolProfileChoiceParallelAndSchemaMatrix(t *testing.T) { + type expectation struct { + choices []toolcall.ChoiceMode + parallelOff bool + strict bool + } + want := map[string]expectation{ + "qoder": {allChoices(), true, true}, + "workbuddy": {allChoices(), false, false}, + "trae": {allChoices(), false, false}, + "devin": {allChoices(), false, false}, + "command": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto}, false, false}, + "codex": {allChoices(), false, false}, + "meta": {allChoices(), false, false}, + "zhipu": {allChoices(), false, true}, + "kimi": {allChoices(), false, true}, + "codearts": {allChoices(), false, true}, + "qwenwork": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "kiro": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "doubaowork": {allChoices(), false, false}, + "minimaxcode": {allChoices(), false, false}, + "opencode": {allChoices(), false, false}, + } + if len(want) != len(List()) { + t.Fatalf("matrix covers %d providers, registry has %d", len(want), len(List())) + } + for provider, expected := range want { + profile := ToolProfileFor(provider, "some-model") + if profile.ParallelOff != expected.parallelOff || profile.StrictSchema != expected.strict { + t.Fatalf("%s policy = %+v, want parallelOff=%v strict=%v", provider, profile, expected.parallelOff, expected.strict) + } + for _, mode := range []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone, toolcall.ChoiceRequired, toolcall.ChoiceNamed} { + allowed := false + for _, choice := range expected.choices { + allowed = allowed || choice == mode + } + if profile.SupportsChoice(mode) != allowed { + t.Fatalf("%s SupportsChoice(%s) = %v, want %v", provider, mode, !allowed, allowed) + } + } + } +} + +func TestUnknownProviderHasNoToolContract(t *testing.T) { + profile := ToolProfileFor("unknown", "model") + if profile.SupportsTools() || profile.SupportsChoice(toolcall.ChoiceAuto) { + t.Fatalf("unknown provider must not claim tools: %+v", profile) + } +} diff --git a/internal/providers/trae/checkin.go b/internal/providers/trae/checkin.go index 58b9bc3e5..1e886293d 100644 --- a/internal/providers/trae/checkin.go +++ b/internal/providers/trae/checkin.go @@ -32,6 +32,8 @@ func (AlreadyCheckedInError) AlreadyCheckedIn() bool { return true } // re-probe so success is only reported when the account actually flipped. // "今日已签到" maps to Status="already"; session-dead surfaces KindAuth so the // manager can flag the account for re-login. +var checkinNow = time.Now + func (client *Client) Checkin(ctx context.Context, accountID string) (providers.CheckinResult, error) { credential, err := client.credential(ctx, accountID) if err != nil { @@ -62,7 +64,7 @@ func (client *Client) Checkin(ctx context.Context, accountID string) (providers. if errors.As(err, &already) { // The claim endpoint may replay yesterday's grant during the brief // post-midnight window; do not record that as today's success. - if providers.CheckinClaimProvisional(time.Now()) { + if providers.CheckinClaimProvisional(checkinNow()) { return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核"}, nil } return providers.CheckinResult{Status: "already", Message: already.Msg}, nil diff --git a/internal/providers/trae/checkin_test.go b/internal/providers/trae/checkin_test.go index 463531fd2..0c39cbbf3 100644 --- a/internal/providers/trae/checkin_test.go +++ b/internal/providers/trae/checkin_test.go @@ -8,6 +8,7 @@ import ( "net/http" "strings" "testing" + "time" ) // seedCheckinCredential stores a long-lived Trae credential so Checkin does @@ -114,6 +115,9 @@ func TestCheckinAlreadyByBusinessMessage(t *testing.T) { } func TestCheckinClaimAlreadyRace(t *testing.T) { + oldNow := checkinNow + checkinNow = func() time.Time { return time.Date(2026, 1, 2, 12, 0, 0, 0, time.Local) } + defer func() { checkinNow = oldNow }() client, store := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { diff --git a/internal/providers/trae/client.go b/internal/providers/trae/client.go index ec222c19f..1343603e5 100644 --- a/internal/providers/trae/client.go +++ b/internal/providers/trae/client.go @@ -150,32 +150,32 @@ func (c *Client) httpClient(ctx context.Context, accountID string) (*http.Client return &client, nil } -func (c *Client) do(ctx context.Context, accountID, method, rawURL string, body []byte, setHeaders func(http.Header)) ([]byte, int, error) { +func (c *Client) do(ctx context.Context, accountID, method, rawURL string, body []byte, setHeaders func(http.Header)) ([]byte, int, http.Header, error) { var reader io.Reader if body != nil { reader = bytes.NewReader(body) } req, err := http.NewRequestWithContext(ctx, method, rawURL, reader) if err != nil { - return nil, 0, err + return nil, 0, nil, err } if setHeaders != nil { setHeaders(req.Header) } client, err := c.httpClient(ctx, accountID) if err != nil { - return nil, 0, err + return nil, 0, nil, err } resp, err := client.Do(req) if err != nil { - return nil, 0, err + return nil, 0, nil, err } defer resp.Body.Close() payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { - return nil, resp.StatusCode, err + return nil, resp.StatusCode, resp.Header, err } - return payload, resp.StatusCode, nil + return payload, resp.StatusCode, resp.Header, nil } func (c *Client) StartLogin(ctx context.Context, accountID string) (providers.LoginSession, error) { @@ -714,12 +714,12 @@ func (c *Client) ExchangeToken(ctx context.Context, accountID string, credential if err != nil { return credential, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathExchange, body, SetOAuthHeaders) + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathExchange, body, SetOAuthHeaders) if err != nil { return credential, err } if status >= 300 { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } return decodeExchangeCredential(credential, payload) } @@ -772,7 +772,7 @@ func (c *Client) exchangeDeviceBound(ctx context.Context, accountID string, cred if err != nil { return credential, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, UgHost+pathExchangeCode, body, func(h http.Header) { + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, UgHost+pathExchangeCode, body, func(h http.Header) { SetOAuthHeaders(h) if credential.AccessToken != "" { h.Set("Authorization", "Cloud-IDE-JWT "+credential.AccessToken) @@ -785,7 +785,7 @@ func (c *Client) exchangeDeviceBound(ctx context.Context, accountID string, cred if status >= 300 { // Log the verdict, never the payload: it carries token material. log.Printf("trae: bound exchange rejected account=%s status=%d code=%s", accountID, status, firstNonEmpty(extractMetadataCode(payload), extractCode(string(payload)))) - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } log.Printf("trae: bound exchange accepted account=%s", accountID) return decodeExchangeCredential(credential, payload) @@ -866,8 +866,9 @@ func (c *Client) ExchangeAuthCode(ctx context.Context, accountID string, credent } var payload []byte var status int + var headers http.Header for i, host := range hosts { - payload, status, err = c.do(ctx, accountID, http.MethodPost, host+pathExchangeCode, body, SetOAuthHeaders) + payload, status, headers, err = c.do(ctx, accountID, http.MethodPost, host+pathExchangeCode, body, SetOAuthHeaders) if err != nil { log.Printf("trae: ExchangeAuthCode request failed account=%s host=%s: %v", accountID, host, err) return credential, err @@ -878,11 +879,11 @@ func (c *Client) ExchangeAuthCode(ctx context.Context, accountID string, credent // Log status and the extracted error code only — never the raw payload. log.Printf("trae: ExchangeAuthCode upstream error account=%s host=%s status=%d code=%s", accountID, host, status, firstNonEmpty(extractMetadataCode(payload), extractCode(string(payload)))) if i == len(hosts)-1 || !isInvalidParameter(status, payload) { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } } if status >= 300 { - return credential, classifiedError(status, payload) + return credential, classifiedError(status, payload, headers) } credential, err = decodeExchangeCredential(credential, payload) if err != nil { @@ -905,7 +906,7 @@ func (c *Client) GetUserInfo(ctx context.Context, accountID string, credential C if err != nil { return userInfo{}, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathUserInfo, body, func(h http.Header) { + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.AuthBase()+pathUserInfo, body, func(h http.Header) { SetOAuthHeaders(h) if credential.AccessToken != "" { h.Set("X-Cloudide-Token", credential.AccessToken) @@ -915,7 +916,7 @@ func (c *Client) GetUserInfo(ctx context.Context, accountID string, credential C return userInfo{}, err } if status >= 300 { - return userInfo{}, classifiedError(status, payload) + return userInfo{}, classifiedError(status, payload, headers) } var env struct { Result struct { @@ -1012,13 +1013,13 @@ func (c *Client) fetchCatalogScene(ctx context.Context, accountID string, creden if err != nil { return nil, err } - payload, status, err := c.do(ctx, accountID, http.MethodPost, credential.ChatBase()+pathModels, body, + payload, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.ChatBase()+pathModels, body, func(h http.Header) { SetCatalogHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, payload) + return nil, classifiedError(status, payload, headers) } out, err := parseCatalogModels(payload, function) if err != nil { @@ -1085,6 +1086,9 @@ func (c *Client) chatRequest(ctx context.Context, credential Credential, req tra "tools": req.Tools, "tool_choice": req.ToolChoice, } + if req.ParallelToolCalls != nil { + body["parallel_tool_calls"] = *req.ParallelToolCalls + } if len(req.ResponseFormat) > 0 && string(req.ResponseFormat) != "null" { body["response_format"] = json.RawMessage(req.ResponseFormat) } @@ -1162,7 +1166,7 @@ func (c *Client) ChatNonStream(ctx context.Context, accountID string, req transl defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) if resp.StatusCode >= 300 { - return providers.ChatOutcome{}, classifiedError(resp.StatusCode, body) + return providers.ChatOutcome{}, classifiedError(resp.StatusCode, body, resp.Header) } aggregate, err := Aggregate(bytes.NewReader(body)) if err != nil { @@ -1197,7 +1201,7 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate if resp.StatusCode >= 300 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() - return nil, providers.ResolvedChat{}, classifiedError(resp.StatusCode, body) + return nil, providers.ResolvedChat{}, classifiedError(resp.StatusCode, body, resp.Header) } streamResp, err := rewriteSoloStream(resp.Body, req.Model) if err != nil { @@ -1260,8 +1264,14 @@ func outcomeFromAggregate(aggregate map[string]any, fallbackModel string) (provi return out, nil } -func classifiedError(status int, body []byte) error { - return wrapClassified(Classify(status, string(body)), extractCode(string(body))) +func classifiedError(status int, body []byte, headers ...http.Header) error { + out := wrapClassified(Classify(status, string(body)), extractCode(string(body))) + if pe, ok := out.(*providers.Error); ok && len(headers) > 0 { + if hint := providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")); hint > 0 { + pe.RetryAfter = hint + } + } + return out } // isInvalidParameter reports the upstream's "无效参数" rejection (code 10101). @@ -1430,13 +1440,13 @@ func (c *Client) Quota(ctx context.Context, accountID string) (*providers.QuotaI } func (c *Client) UserEntUsage(ctx context.Context, accountID string, credential Credential) (general, work entitlementBucket, err error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathEntUsage, []byte("{}"), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathEntUsage, []byte("{}"), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return entitlementBucket{}, entitlementBucket{}, err } if status >= 300 { - return entitlementBucket{}, entitlementBucket{}, classifiedError(status, body) + return entitlementBucket{}, entitlementBucket{}, classifiedError(status, body, headers) } general, work = parseEntitlementBuckets(body) if general.total == 0 && general.remain == 0 && general.used == 0 && work.total == 0 && work.remain == 0 && work.used == 0 { @@ -1567,25 +1577,25 @@ func int64FromAny(value any) int64 { } func (c *Client) checkinStatusBody(ctx context.Context, accountID string, credential Credential) ([]byte, error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinStatus, checkinReqSourceBody(credential), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinStatus, checkinReqSourceBody(credential), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, body) + return nil, classifiedError(status, body, headers) } return body, nil } func (c *Client) CheckinClaim(ctx context.Context, accountID string, credential Credential) ([]byte, error) { - body, status, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinClaim, checkinReqSourceBody(credential), + body, status, headers, err := c.do(ctx, accountID, http.MethodPost, credential.BillingBase()+pathCheckinClaim, checkinReqSourceBody(credential), func(h http.Header) { SetUgHeaders(h, credential) }) if err != nil { return nil, err } if status >= 300 { - return nil, classifiedError(status, body) + return nil, classifiedError(status, body, headers) } return body, nil } diff --git a/internal/providers/trae/client_test.go b/internal/providers/trae/client_test.go index f388e481b..3c2ff4738 100644 --- a/internal/providers/trae/client_test.go +++ b/internal/providers/trae/client_test.go @@ -747,6 +747,54 @@ func TestChatNonStreamAggregatesToolsAndReasoning(t *testing.T) { } } +func TestAggregateKeepsSoloToolCallsByStableID(t *testing.T) { + stream := "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"first\",\"arguments\":\"{\\\"a\\\":\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"1}\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_2\",\"type\":\"function\",\"function\":{\"name\":\"second\",\"arguments\":\"{}\"}}]}\n\n" + + "event: done\ndata: {\"finish_reason\":\"tool-calls\"}\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + choices, _ := aggregate["choices"].([]map[string]any) + if len(choices) != 1 { + t.Fatalf("choices=%#v", aggregate["choices"]) + } + message, _ := choices[0]["message"].(map[string]any) + calls, _ := message["tool_calls"].([]any) + if len(calls) != 2 { + t.Fatalf("index reuse collapsed calls: %#v", calls) + } + first, _ := calls[0].(map[string]any) + second, _ := calls[1].(map[string]any) + if first["id"] != "call_1" || second["id"] != "call_2" { + t.Fatalf("call ids = %#v", calls) + } +} + +func TestAggregateAdoptsLateSoloToolCallID(t *testing.T) { + stream := "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"arguments\":\"{}\"}}]}\n\n" + + "event: output\ndata: {\"tool_calls\":[{\"index\":0,\"id\":\"call_late\"}]}\n\n" + + "event: done\ndata: {\"finish_reason\":\"tool-calls\"}\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + choices, _ := aggregate["choices"].([]map[string]any) + if len(choices) != 1 { + t.Fatalf("choices=%#v", aggregate["choices"]) + } + message, _ := choices[0]["message"].(map[string]any) + calls, _ := message["tool_calls"].([]any) + if len(calls) != 1 { + t.Fatalf("late id duplicated call: %#v", calls) + } + call, _ := calls[0].(map[string]any) + if call["id"] != "call_late" { + t.Fatalf("late id not adopted: %#v", call) + } +} + // Solo answers 200 and only then fails inside the stream, so the quota error // cannot surface as a ChatStream return value: bytes are already committed. // The rewritten body must report it as a read error once drained. diff --git a/internal/providers/trae/payload.go b/internal/providers/trae/payload.go index f6f9ebb5d..d1b453406 100644 --- a/internal/providers/trae/payload.go +++ b/internal/providers/trae/payload.go @@ -145,7 +145,9 @@ func normalizeTools(obj map[string]any) { normalized, err := translate.NormalizeOpenAITools(encoded) if err != nil || len(normalized) == 0 { delete(obj, "tools") - delete(obj, "tool_choice") + if choice, ok := obj["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(obj, "tool_choice") + } return } var list []any diff --git a/internal/providers/trae/sse.go b/internal/providers/trae/sse.go index fc0810f87..6af90ef8e 100644 --- a/internal/providers/trae/sse.go +++ b/internal/providers/trae/sse.go @@ -8,7 +8,6 @@ import ( "fmt" "io" "net/http" - "sort" "strings" "sync/atomic" "time" @@ -99,10 +98,11 @@ func normalizeTraeUsage(raw []byte) any { func Aggregate(reader io.Reader) (map[string]any, error) { result := map[string]any{"object": "chat.completion"} message := map[string]any{"role": "assistant"} - toolCalls := map[int]map[string]any{} + toolCalls := map[string]map[string]any{} + indexToKey := map[int]string{} finishReason := "stop" var content, reasoning strings.Builder - var order []int + var order []string sawDone := false var usage any model := "" @@ -132,7 +132,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { if out.FinishReason != "" { finishReason = out.FinishReason } - mergeSoloToolCalls(toolCalls, &order, out.ToolCalls) + mergeSoloToolCalls(toolCalls, indexToKey, &order, out.ToolCalls) case "token_usage": usage = normalizeTraeUsage(ev.Data) case "done": @@ -163,10 +163,9 @@ func Aggregate(reader io.Reader) (map[string]any, error) { message["reasoning_content"] = reasoning.String() } if len(toolCalls) > 0 { - sort.Ints(order) calls := make([]any, 0, len(order)) - for _, index := range order { - calls = append(calls, toolCalls[index]) + for _, key := range order { + calls = append(calls, toolCalls[key]) } message["tool_calls"] = calls } @@ -358,13 +357,23 @@ func startSoloRewrite(src io.ReadCloser, upstream io.Closer, model string) (*htt var se streamError _ = json.Unmarshal(ev.Data, &se) payload, _ := json.Marshal(se.Error()) + // Emit the failure frame only: a following [DONE] would make a + // failed turn look like a successful terminal to strict clients. _, _ = fmt.Fprintf(pw, "event: error\ndata: %s\n\n", payload) - _, _ = io.WriteString(pw, "data: [DONE]\n\n") streamErr.Store(classifiedFromSolo(se)) return nil } return nil }) + if err != nil && !ended { + // The transport failed before Solo sent a terminal event. Writing a + // synthetic finish chunk plus [DONE] here used to convert a truncated + // stream (for example UnexpectedEOF) into a reported success; the + // downstream relay stopped reading at [DONE] and never saw the + // deferred read error. Surface the failure instead. + _ = pw.CloseWithError(err) + return + } if !ended { usage := pendingUsage if usage == nil && lastUsage != nil { @@ -508,7 +517,7 @@ func scanSolo(reader io.Reader, handle func(soloEvent) error) error { return flush() } -func mergeSoloToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMessage) { +func mergeSoloToolCalls(merged map[string]map[string]any, indexToKey map[int]string, order *[]string, raw json.RawMessage) { if len(raw) == 0 || string(raw) == "null" { return } @@ -518,13 +527,38 @@ func mergeSoloToolCalls(merged map[int]map[string]any, order *[]int, raw json.Ra if v, ok := item["index"].(float64); ok { index = int(v) } - call, exists := merged[index] + id, _ := item["id"].(string) + key := "" + if id != "" { + key = "id:" + id + } else if previous, ok := indexToKey[index]; ok { + key = previous + } else { + key = fmt.Sprintf("index:%d", index) + } + if id != "" { + if previous, ok := indexToKey[index]; ok && previous != key { + if call, exists := merged[previous]; exists && call["id"] == nil { + call["id"] = id + merged[key] = call + delete(merged, previous) + for i, orderedKey := range *order { + if orderedKey == previous { + (*order)[i] = key + break + } + } + } + } + } + indexToKey[index] = key + call, exists := merged[key] if !exists { call = map[string]any{"index": index, "type": "function"} - merged[index] = call - *order = append(*order, index) + merged[key] = call + *order = append(*order, key) } - if id, _ := item["id"].(string); id != "" { + if id != "" { call["id"] = id } if typ, _ := item["type"].(string); typ != "" { diff --git a/internal/providers/trae/terminal_test.go b/internal/providers/trae/terminal_test.go new file mode 100644 index 000000000..ae1d8613c --- /dev/null +++ b/internal/providers/trae/terminal_test.go @@ -0,0 +1,69 @@ +package trae + +import ( + "io" + "strings" + "testing" +) + +type failingStream struct { + data []byte + err error +} + +func (f *failingStream) Read(p []byte) (int, error) { + if len(f.data) > 0 { + n := copy(p, f.data) + f.data = f.data[n:] + return n, nil + } + return 0, f.err +} + +func (f *failingStream) Close() error { return nil } + +// A transport read failure before Solo's `done` event must not be converted +// into a synthetic finish chunk plus [DONE]. Downstream used to stop at [DONE] +// and record the truncated turn as a success. +func TestRewriteSoloStreamDoesNotSynthesizeTerminalOnReadError(t *testing.T) { + stream := "event: metadata\ndata: {\"model\":\"glm-5.2\"}\n\n" + + "event: output\ndata: {\"response\":\"partial\"}\n\n" + src := &failingStream{data: []byte(stream), err: io.ErrUnexpectedEOF} + resp, err := rewriteSoloStream(src, "glm-5.2") + if err != nil { + t.Fatalf("headers should be exposed before the read error: %v", err) + } + defer resp.Body.Close() + body, readErr := io.ReadAll(resp.Body) + if readErr == nil { + t.Fatal("truncated stream was reported as complete") + } + text := string(body) + if strings.Contains(text, "data: [DONE]") || strings.Contains(text, `"finish_reason":"stop"`) { + t.Fatalf("failure was converted into a success terminal: %q", text) + } + if !strings.Contains(text, "partial") { + t.Fatalf("content before the failure should stay relayed: %q", text) + } +} + +// A clean EOF without `done` keeps the existing salvage behavior: the upstream +// delivered a full body, so a synthesized terminal is a compatibility fallback, +// not a failure conversion. +func TestRewriteSoloStreamStillSalvagesCleanEOF(t *testing.T) { + stream := "event: metadata\ndata: {\"model\":\"glm-5.2\"}\n\n" + + "event: output\ndata: {\"response\":\"complete\"}\n\n" + src := &failingStream{data: []byte(stream), err: io.EOF} + resp, err := rewriteSoloStream(src, "glm-5.2") + if err != nil { + t.Fatalf("salvage path failed: %v", err) + } + defer resp.Body.Close() + body, readErr := io.ReadAll(resp.Body) + if readErr != nil { + t.Fatalf("clean EOF must not surface as an error: %v", readErr) + } + if !strings.Contains(string(body), "data: [DONE]") { + t.Fatalf("clean EOF salvage lost its terminal: %q", body) + } +} diff --git a/internal/providers/workbuddy/client.go b/internal/providers/workbuddy/client.go index c01e14a3a..7c5c7442f 100644 --- a/internal/providers/workbuddy/client.go +++ b/internal/providers/workbuddy/client.go @@ -479,6 +479,9 @@ func (c *Client) chatRequest(ctx context.Context, accountID string, credential C "tools": req.Tools, "tool_choice": req.ToolChoice, } + if req.ParallelToolCalls != nil { + body["parallel_tool_calls"] = *req.ParallelToolCalls + } // The re-built body used to drop the caller's `thinking` object entirely. // Keep it so applyChatReasoning (and PrepareBody, which preserves unknown // keys) can relay an explicit disabled-thinking request upstream. @@ -508,24 +511,25 @@ func (c *Client) ChatNonStream(ctx context.Context, accountID string, req transl if err != nil { return providers.ChatOutcome{}, err } - resp, err := c.sendChat(ctx, accountID, credential, req, httpReq) + resp, retries, err := c.sendChat(ctx, accountID, credential, req, httpReq) if err != nil { return providers.ChatOutcome{}, err } defer resp.Body.Close() body, readErr := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) if readErr != nil { - return providers.ChatOutcome{}, fmt.Errorf("read workbuddy stream: %w", readErr) + return providers.ChatOutcome{}, providers.TagInternalRetries(fmt.Errorf("read workbuddy stream: %w", readErr), retries) } aggregate, err := Aggregate(bytes.NewReader(body)) if err != nil { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, providers.TagInternalRetries(err, retries) } outcome, err := outcomeFromAggregate(aggregate) if err != nil { - return providers.ChatOutcome{}, err + return providers.ChatOutcome{}, providers.TagInternalRetries(err, retries) } outcome.ReasoningLevel = resolved.ReasoningLevel + outcome.InternalRetries = retries return outcome, nil } @@ -538,10 +542,11 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate if err != nil { return nil, providers.ResolvedChat{}, err } - resp, err := c.sendChat(ctx, accountID, credential, req, httpReq) + resp, retries, err := c.sendChat(ctx, accountID, credential, req, httpReq) if err != nil { return nil, providers.ResolvedChat{}, err } + resolved.InternalRetries = retries return rewriteChatStream(resp), resolved, nil } @@ -554,46 +559,49 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate // so the pool applies short cooldown + failover without marking the account // login_required. TLS certificate verification failures are deterministic // configuration errors and are reported without retry. -func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, req translate.ChatRequest, httpReq *http.Request) (*http.Response, error) { +func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, req translate.ChatRequest, httpReq *http.Request) (*http.Response, int, error) { client, err := c.httpClient(ctx, accountID) if err != nil { - return nil, err + return nil, 0, err } client.Timeout = 0 refreshed := false + // attempts counts only requests actually sent again after a successful + // token refresh. A refresh that fails before the resend is not a retry. + attempts := 0 for { // Fail over when the upstream accepts but never sends a response head // (see ttfb.go). Kept inside sendChat so the 401 refresh loop still runs. resp, err := doWithFirstByteTimeout(client, httpReq, resolveFirstByteTimeout()) if err != nil { - return nil, wrapTransportError(err) + return nil, attempts, withInternalRetries(wrapTransportError(err), attempts) } if resp.StatusCode < 300 { - return resp, nil + return resp, attempts, nil } body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) resp.Body.Close() if resp.StatusCode != http.StatusUnauthorized || refreshed || credential.RefreshToken == "" { - return nil, classifiedError(resp.StatusCode, body) + return nil, attempts, withInternalRetries(classifiedError(resp.StatusCode, body, resp.Header), attempts) } refreshed = true fresh, refreshErr := c.Refresh(ctx, accountID, credential) if refreshErr != nil { if tlsErr := tlsVerifyError(refreshErr); tlsErr != nil { - return nil, tlsErr + return nil, 0, tlsErr } if refreshFailureIsAuth(refreshErr) { - out := classifiedError(resp.StatusCode, body) + out := classifiedError(resp.StatusCode, body, resp.Header) if pe, ok := out.(*providers.Error); ok && pe.Kind == accounts.KindAuth { pe.Message = "token refresh after 401 failed; re-login required" } - return nil, out + return nil, 0, out } // Non-auth refresh failure (transport / 5xx / etc.): keep the // account out of login_required; pool short-cools via Unavailable. summary := refreshErr.Error() _ = c.store.Observe(ctx, accountID, credential.UID, "error", "token refresh after 401: "+summary, accounts.KindUnavailable) - return nil, &providers.Error{ + return nil, 0, &providers.Error{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Message: "token refresh after 401 unavailable: " + summary, @@ -602,9 +610,24 @@ func (c *Client) sendChat(ctx context.Context, accountID string, credential Cred credential = fresh httpReq, _, err = c.chatRequest(ctx, accountID, credential, req) if err != nil { - return nil, err + return nil, 0, err } + attempts = 1 + } +} + +// withInternalRetries tags a classified adapter error with the number of +// same-account replays that preceded it. Errors that are not providers.Error +// stay untouched. +func withInternalRetries(err error, retries int) error { + if err == nil || retries <= 0 { + return err + } + var pe *providers.Error + if errors.As(err, &pe) && pe != nil { + pe.InternalRetries = retries } + return err } // tlsVerifyHint mirrors workbuddy2api-hub #441: certificate failures are a @@ -706,10 +729,15 @@ func outcomeFromAggregate(aggregate map[string]any) (providers.ChatOutcome, erro return out, nil } -func classifiedError(status int, body []byte) error { +func classifiedError(status int, body []byte, headers ...http.Header) error { classified := Classify(status, string(body)) out := &providers.Error{Kind: classified.Kind, Status: classified.Status, Message: classified.Message} - if classified.Kind == accounts.KindRateLimit { + if len(headers) > 0 { + if hint := providers.ParseRetryAfterHeader(headers[0].Get("Retry-After")); hint > 0 { + out.RetryAfter = hint + } + } + if classified.Kind == accounts.KindRateLimit && out.RetryAfter <= 0 { if reset := parseQuotaReset(string(body), time.Now()); reset > 0 { out.RetryAfter = reset } diff --git a/internal/providers/workbuddy/client_test.go b/internal/providers/workbuddy/client_test.go index cbd6db1b0..adad4c246 100644 --- a/internal/providers/workbuddy/client_test.go +++ b/internal/providers/workbuddy/client_test.go @@ -2472,7 +2472,7 @@ func TestOutcomeFromAggregateReadsConsumedCredit(t *testing.T) { `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":16,"completion_tokens":2,"credit":0.75}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2504,7 +2504,7 @@ func TestOutcomeFromAggregatePreservesCacheUsage(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":16,"completion_tokens":2,` + test.usage + `}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2527,7 +2527,7 @@ func TestOutcomeFromAggregateMissingCreditStaysNil(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } @@ -2545,7 +2545,7 @@ func TestOutcomeFromAggregateExplicitZeroCredit(t *testing.T) { `data: {"id":"c1","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1,"credit":0}}`, `data: [DONE]`, "", - }, "\n"))) + }, "\n\n"))) if err != nil { t.Fatal(err) } diff --git a/internal/providers/workbuddy/credential.go b/internal/providers/workbuddy/credential.go index 359445fc9..53655717a 100644 --- a/internal/providers/workbuddy/credential.go +++ b/internal/providers/workbuddy/credential.go @@ -86,8 +86,8 @@ const ( pathModelsCN = "/console/enterprises/personal/models" pathModelsGlobal = "/v2/enterprises/personal/models" pathProductConfig = "/v3/config" - pathUserResource = "/v2/billing/meter/get-user-resource" - pathDailyCheckin = "/v2/billing/meter/daily-checkin" + pathUserResource = "/v2/billing/meter/get-user-resource" + pathDailyCheckin = "/v2/billing/meter/daily-checkin" sessionDeadCode = 12153 sessionDeadText = "Offline user session not found" diff --git a/internal/providers/workbuddy/credential_test.go b/internal/providers/workbuddy/credential_test.go index 61d8258ba..da82114b1 100644 --- a/internal/providers/workbuddy/credential_test.go +++ b/internal/providers/workbuddy/credential_test.go @@ -141,7 +141,6 @@ func TestDecodeCredentialNestedAndSnakeStillWork(t *testing.T) { } } - func TestSplitImportClientExportTypePack(t *testing.T) { payload := []byte(`{ "exportType":"WorkBuddy-accounts", @@ -228,8 +227,8 @@ func TestSplitImportFormatCaseAlias(t *testing.T) { func TestIsGlobalWorkbuddyCN(t *testing.T) { cases := []struct { - domain string - global bool + domain string + global bool }{ {"www.workbuddy.cn", false}, {"workbuddy.cn", false}, diff --git a/internal/providers/workbuddy/payload.go b/internal/providers/workbuddy/payload.go index 5ec6ed0d5..2a818b015 100644 --- a/internal/providers/workbuddy/payload.go +++ b/internal/providers/workbuddy/payload.go @@ -63,7 +63,12 @@ func normalizeTools(body map[string]any) { } if len(normalized) == 0 { delete(body, "tools") - delete(body, "tool_choice") + // Only an orphan auto degrades safely. A required/named selector must + // stay on the wire so upstream rejects it instead of silently answering + // with plain text. + if choice, ok := body["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(body, "tool_choice") + } return } var tools []any @@ -450,7 +455,9 @@ func dropEmptyTools(body map[string]any) { list, ok := raw.([]any) if ok && len(list) == 0 { delete(body, "tools") - delete(body, "tool_choice") + if choice, ok := body["tool_choice"].(string); ok && strings.EqualFold(strings.TrimSpace(choice), "auto") { + delete(body, "tool_choice") + } } } diff --git a/internal/providers/workbuddy/sse.go b/internal/providers/workbuddy/sse.go index 9fe640211..c93ca9643 100644 --- a/internal/providers/workbuddy/sse.go +++ b/internal/providers/workbuddy/sse.go @@ -4,12 +4,14 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" - "sort" "strings" "time" + + "github.com/caigee-cmd/cli2api/internal/providers" ) // Aggregate converts an upstream SSE stream into one Chat Completions object, @@ -19,26 +21,36 @@ func Aggregate(reader io.Reader) (map[string]any, error) { "object": "chat.completion", } message := map[string]any{"role": "assistant"} - toolCalls := map[int]map[string]any{} + toolCalls := map[string]map[string]any{} + indexToKey := map[int]string{} finishReason := "stop" var content, reasoning strings.Builder - var order []int + var order []string sawDone := false + var terminalErr error scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) - for scanner.Scan() { - line := strings.TrimSuffix(scanner.Text(), "\r") - if !strings.HasPrefix(line, "data:") { - continue + var frame []string + flush := func() error { + if len(frame) == 0 { + return nil } - payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + payload := sseDataPayload(frame) + frame = nil if payload == "" { - continue + return nil } if payload == "[DONE]" { sawDone = true - break + return errSSEStreamDone + } + // A terminal error frame is authoritative: never aggregate the content + // that happened to arrive before it into a successful completion, and + // never let a later [DONE] turn the failure into success. + if terminal, ok := terminalSSEPayloadError(payload); ok { + terminalErr = terminal + return errSSEStreamDone } var chunk struct { ID string `json:"id"` @@ -57,7 +69,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { } `json:"choices"` } if err := json.Unmarshal([]byte(payload), &chunk); err != nil { - continue + return nil } if chunk.ID != "" { result["id"] = chunk.ID @@ -72,7 +84,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { result["usage"] = chunk.Usage } if len(chunk.Choices) == 0 { - continue + return nil } choice := chunk.Choices[0] if choice.FinishReason != "" { @@ -84,12 +96,29 @@ func Aggregate(reader io.Reader) (map[string]any, error) { content.WriteString(choice.Delta.Content) reasoning.WriteString(choice.Delta.ReasoningContent) if len(choice.Delta.ToolCalls) > 0 && string(choice.Delta.ToolCalls) != "null" { - mergeToolCalls(toolCalls, &order, choice.Delta.ToolCalls) + mergeToolCalls(toolCalls, indexToKey, &order, choice.Delta.ToolCalls) } + return nil + } + for scanner.Scan() { + line := strings.TrimSuffix(scanner.Text(), "\r") + if line == "" { + if err := flush(); err != nil { + if errors.Is(err, errSSEStreamDone) { + break + } + return nil, err + } + continue + } + frame = append(frame, line) } if err := scanner.Err(); err != nil { return nil, err } + if terminalErr != nil { + return nil, terminalErr + } if !sawDone { return nil, fmt.Errorf("workbuddy stream ended before [DONE]") } @@ -99,10 +128,9 @@ func Aggregate(reader io.Reader) (map[string]any, error) { message["reasoning_content"] = reasoning.String() } if len(toolCalls) > 0 { - sort.Ints(order) calls := make([]any, 0, len(order)) - for _, index := range order { - calls = append(calls, toolCalls[index]) + for _, key := range order { + calls = append(calls, toolCalls[key]) } message["tool_calls"] = calls } @@ -120,7 +148,7 @@ func Aggregate(reader io.Reader) (map[string]any, error) { return result, nil } -func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMessage) { +func mergeToolCalls(merged map[string]map[string]any, indexToKey map[int]string, order *[]string, raw json.RawMessage) { var deltas []struct { Index int `json:"index"` ID string `json:"id"` @@ -134,11 +162,37 @@ func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMes return } for _, delta := range deltas { - call, exists := merged[delta.Index] + key := "" + if delta.ID != "" { + key = "id:" + delta.ID + } else if previous, ok := indexToKey[delta.Index]; ok { + key = previous + } else { + key = fmt.Sprintf("index:%d", delta.Index) + } + if delta.ID != "" { + if previous, ok := indexToKey[delta.Index]; ok && previous != key { + if call, exists := merged[previous]; exists && call["id"] == nil { + call["id"] = delta.ID + merged[key] = call + delete(merged, previous) + for i, orderedKey := range *order { + if orderedKey == previous { + (*order)[i] = key + break + } + } + } + } + indexToKey[delta.Index] = key + } else { + indexToKey[delta.Index] = key + } + call, exists := merged[key] if !exists { call = map[string]any{"index": delta.Index} - merged[delta.Index] = call - *order = append(*order, delta.Index) + merged[key] = call + *order = append(*order, key) } if delta.ID != "" { call["id"] = delta.ID @@ -152,7 +206,9 @@ func mergeToolCalls(merged map[int]map[string]any, order *[]int, raw json.RawMes function = map[string]any{} call["function"] = function } - function["name"] = delta.Function.Name + if name, _ := function["name"].(string); name == "" { + function["name"] = delta.Function.Name + } } if delta.Function.Arguments != "" { function, _ := call["function"].(map[string]any) @@ -192,30 +248,172 @@ func copySanitizedSSE(src io.Reader, dst io.Writer) error { scanner := bufio.NewScanner(src) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) sentRole := false - for scanner.Scan() { - line := strings.TrimSuffix(scanner.Text(), "\r") - if line == "" { - continue + var frame []string + flush := func() error { + if len(frame) == 0 { + return nil } - if !strings.HasPrefix(line, "data:") { - if _, err := fmt.Fprintf(dst, "%s\n", line); err != nil { + payload := sseDataPayload(frame) + original := strings.Join(frame, "\n") + "\n\n" + frame = nil + if payload == "" { + return nil + } + if payload == "[DONE]" { + if _, err := io.WriteString(dst, original); err != nil { return err } - continue + return errSSEStreamDone } - payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if payload == "" { - continue + // Preserve the upstream failure frame verbatim: the sanitizer used to + // drop a frame that carried only an error object, leaving the later + // [DONE] as the only terminal signal and turning a failure into success. + if terminal, ok := terminalSSEPayloadError(payload); ok { + if _, err := io.WriteString(dst, original); err != nil { + return err + } + return terminal } cleaned, ok := sanitizeSSEPayload(payload, &sentRole) if !ok { - continue + return nil } if _, err := fmt.Fprintf(dst, "data: %s\n\n", cleaned); err != nil { return err } + return nil + } + for scanner.Scan() { + line := strings.TrimSuffix(scanner.Text(), "\r") + if line == "" { + if err := flush(); err != nil { + if errors.Is(err, errSSEStreamDone) { + return nil + } + return err + } + continue + } + frame = append(frame, line) + } + if err := scanner.Err(); err != nil { + return err + } + if err := flush(); err != nil && !errors.Is(err, errSSEStreamDone) { + return err + } + return nil +} + +var errSSEStreamDone = errors.New("sse stream reached its terminal frame") + +// sseDataPayload joins every data: line in an SSE frame. The SSE specification +// concatenates multiple data lines with a newline before JSON decoding; treating +// each line as a separate payload made a legal multi-line error look like two +// unparseable chunks and let the following [DONE] become the only terminal frame. +func sseDataPayload(frame []string) string { + parts := make([]string, 0, len(frame)) + for _, line := range frame { + line = strings.TrimSuffix(line, "\r") + if !strings.HasPrefix(line, "data:") { + continue + } + value := strings.TrimPrefix(line, "data:") + if strings.HasPrefix(value, " ") { + value = value[1:] + } + parts = append(parts, value) + } + return strings.TrimSpace(strings.Join(parts, "\n")) +} + +// terminalSSEPayloadError reports whether a data payload is an upstream +// terminal failure rather than a chat chunk. WorkBuddy emits several error +// envelopes (OpenAI-shaped {"error":{...}}, {"type":"error",...}, and +// {"code":...,"msg":...}); all of them must stop the relay instead of being +// filtered out and replaced by the following [DONE]. +func terminalSSEPayloadError(payload string) (*providers.Error, bool) { + if payload == "" || payload == "[DONE]" { + return nil, false + } + var chunk map[string]any + if json.Unmarshal([]byte(payload), &chunk) != nil { + return nil, false + } + rawErr, hasError := chunk["error"] + hasError = hasError && rawErr != nil + typ, _ := chunk["type"].(string) + isErrorType := strings.EqualFold(strings.TrimSpace(typ), "error") || strings.EqualFold(strings.TrimSpace(typ), "response.failed") + _, hasChoices := chunk["choices"] + code := stringifySSECode(chunk["code"]) + message := firstSSEString(chunk, "message", "msg") + if !hasError && !isErrorType { + // A bare code/message object without choices is still an upstream + // failure; a normal chunk always carries choices or usage. + if hasChoices || chunk["usage"] != nil || code == "" || message == "" { + return nil, false + } + } + status := 0 + for _, key := range []string{"status", "status_code", "statusCode"} { + if value, ok := chunk[key].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + break + } + } + if status == 0 { + if value, ok := chunk["code"].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + } + } + inner, _ := rawErr.(map[string]any) + if inner != nil { + if message == "" { + message = firstSSEString(inner, "message", "msg") + } + if code == "" { + code = stringifySSECode(inner["code"]) + } + if typ == "" { + typ, _ = inner["type"].(string) + typ = strings.TrimSpace(typ) + } + if status == 0 { + if value, ok := inner["status"].(float64); ok && value >= 400 && value <= 599 { + status = int(value) + } + } + } + if message == "" { + message = strings.TrimSpace(payload) + } + if typ == "" { + typ = "error" + } + return &providers.Error{Status: status, Message: message, Code: code, Type: typ}, true +} + +func stringifySSECode(value any) string { + switch typed := value.(type) { + case string: + return strings.TrimSpace(typed) + case float64: + if typed == float64(int64(typed)) { + return fmt.Sprintf("%d", int64(typed)) + } + return fmt.Sprintf("%v", typed) + default: + return "" + } +} + +func firstSSEString(obj map[string]any, keys ...string) string { + for _, key := range keys { + if value, ok := obj[key].(string); ok && strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } } - return scanner.Err() + return "" } func sanitizeSSEPayload(payload string, sentRole *bool) (string, bool) { diff --git a/internal/providers/workbuddy/terminal_test.go b/internal/providers/workbuddy/terminal_test.go new file mode 100644 index 000000000..f96f7d937 --- /dev/null +++ b/internal/providers/workbuddy/terminal_test.go @@ -0,0 +1,148 @@ +package workbuddy + +import ( + "bytes" + "errors" + "net/http" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +// A 200 response whose only terminal signal is an error frame must never be +// aggregated into a successful completion, even when a [DONE] follows it. +func TestAggregateFailsOnErrorFrameBeforeDone(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"invalid_request_error","message":"bad input"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + _, err := Aggregate(strings.NewReader(stream)) + if err == nil { + t.Fatal("error frame was aggregated as success") + } + var providerErr *providers.Error + if !errors.As(err, &providerErr) || !strings.Contains(providerErr.Message, "bad input") { + t.Fatalf("err=%v", err) + } +} + +func TestAggregateFailsOnBareCodeMessageFrame(t *testing.T) { + stream := `data: {"code":11148,"msg":"tool calls do not match"}` + "\n\n" + `data: [DONE]` + "\n\n" + _, err := Aggregate(strings.NewReader(stream)) + if err == nil || !strings.Contains(err.Error(), "tool calls do not match") { + t.Fatalf("bare code/message frame was not terminal: %v", err) + } +} + +// The sanitizer must pass the failure frame through instead of dropping it and +// forwarding the later [DONE] as the only terminal signal. +func TestCopySanitizedSSEPreservesErrorFrame(t *testing.T) { + input := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"partial"}}]}`, + `data: {"error":{"type":"rate_limit_error","message":"slow down"}}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + var out bytes.Buffer + err := copySanitizedSSE(strings.NewReader(input), &out) + if err == nil { + t.Fatal("copySanitizedSSE must fail on an error frame") + } + if !strings.Contains(out.String(), "slow down") { + t.Fatalf("failure frame was dropped: %q", out.String()) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator was forwarded after a failure: %q", out.String()) + } +} + +func TestCopySanitizedSSEKeepsOrdinaryChunks(t *testing.T) { + input := `data: {"choices":[{"delta":{"content":"ok"}}]}` + "\n\n" + `data: [DONE]` + "\n\n" + var out bytes.Buffer + if err := copySanitizedSSE(strings.NewReader(input), &out); err != nil { + t.Fatalf("ordinary stream failed: %v", err) + } + if !strings.Contains(out.String(), `"ok"`) || strings.Count(out.String(), "[DONE]") != 1 { + t.Fatalf("ordinary stream was changed: %q", out.String()) + } +} + +func TestClassifiedErrorPreservesRetryAfterHeader(t *testing.T) { + headers := make(http.Header) + headers.Set("Retry-After", "7") + err := classifiedError(http.StatusTooManyRequests, []byte(`{"message":"slow down"}`), headers) + var providerErr *providers.Error + if !errors.As(err, &providerErr) { + t.Fatalf("err type = %T", err) + } + if providerErr.RetryAfter != 7*time.Second { + t.Fatalf("retry after = %v", providerErr.RetryAfter) + } +} + +// A legal SSE frame can split its JSON across multiple data: lines. Splitting +// the lines apart used to lose the error entirely and let a later [DONE] win. +func TestMultiLineErrorFrameStaysTerminal(t *testing.T) { + input := "data: {\"error\":{\"type\":\"invalid_request_error\",\n" + + "data: \"message\":\"bad input\"}}\n\n" + + "data: [DONE]\n\n" + if _, err := Aggregate(strings.NewReader(input)); err == nil || !strings.Contains(err.Error(), "bad input") { + t.Fatalf("aggregate lost a multi-line error frame: %v", err) + } + var out bytes.Buffer + if err := copySanitizedSSE(strings.NewReader(input), &out); err == nil { + t.Fatalf("sanitizer accepted a multi-line error frame: %q", out.String()) + } + if !strings.Contains(out.String(), "bad input") { + t.Fatalf("sanitizer dropped the multi-line error frame: %q", out.String()) + } + if strings.Contains(out.String(), "[DONE]") { + t.Fatalf("success terminator followed the multi-line error: %q", out.String()) + } +} + +func TestAggregateKeepsToolCallsByStableIDWhenIndexReused(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"first","arguments":"{\"a\":"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"1}"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_2","type":"function","function":{"name":"second","arguments":"{}"}}]}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + calls, _ := aggregate["choices"].([]map[string]any)[0]["message"].(map[string]any)["tool_calls"].([]any) + if len(calls) != 2 { + t.Fatalf("index reuse collapsed calls: %#v", calls) + } + first, _ := calls[0].(map[string]any) + second, _ := calls[1].(map[string]any) + if first["id"] != "call_1" || second["id"] != "call_2" { + t.Fatalf("call ids = %#v", calls) + } +} + +func TestAggregateAdoptsLateToolCallID(t *testing.T) { + stream := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"type":"function","function":{"name":"lookup","arguments":"{}"}}]}}]}`, + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_late"}]}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + aggregate, err := Aggregate(strings.NewReader(stream)) + if err != nil { + t.Fatal(err) + } + calls, _ := aggregate["choices"].([]map[string]any)[0]["message"].(map[string]any)["tool_calls"].([]any) + if len(calls) != 1 { + t.Fatalf("late id duplicated call: %#v", calls) + } + call, _ := calls[0].(map[string]any) + if call["id"] != "call_late" { + t.Fatalf("late id not adopted: %#v", call) + } +} diff --git a/internal/providers/zhipu/chat.go b/internal/providers/zhipu/chat.go index 24fd46e67..7b0be0e4a 100644 --- a/internal/providers/zhipu/chat.go +++ b/internal/providers/zhipu/chat.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -128,16 +129,25 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if err != nil { return providers.ChatOutcome{}, err } + sawDone, sawFinish := false, false for _, line := range strings.Split(string(raw), "\n") { line = strings.TrimSpace(line) if !strings.HasPrefix(line, "data:") { continue } data := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if data == "" || data == "[DONE]" { + if data == "" { + continue + } + if data == "[DONE]" { + sawDone = true continue } var chunk struct { + Error *struct { + Message string `json:"message"` + Code any `json:"code"` + } `json:"error"` Choices []struct { Delta struct { Content string `json:"content"` @@ -158,6 +168,13 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) if json.Unmarshal([]byte(data), &chunk) != nil { continue } + if chunk.Error != nil { + message := strings.TrimSpace(chunk.Error.Message) + if message == "" { + message = fmt.Sprintf("zhipu stream error (code %v)", chunk.Error.Code) + } + return providers.ChatOutcome{}, fmt.Errorf("zhipu stream: %s", message) + } if chunk.Usage.PromptTokens > 0 || chunk.Usage.CompletionTokens > 0 { agg.usage = chunk.Usage } @@ -166,6 +183,7 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) agg.reasoning.WriteString(choice.Delta.ReasoningContent) if choice.FinishReason != "" { agg.finish = choice.FinishReason + sawFinish = true } for _, call := range choice.Delta.ToolCalls { state := agg.tools[call.Index] @@ -184,6 +202,9 @@ func collectChatSSE(body io.Reader, model string) (providers.ChatOutcome, error) } } } + if !sawDone && !sawFinish { + return providers.ChatOutcome{}, fmt.Errorf("zhipu stream ended without a terminal frame") + } outcome := providers.ChatOutcome{ Model: model, Content: agg.content.String(), diff --git a/internal/providers/zhipu/zhipu_test.go b/internal/providers/zhipu/zhipu_test.go index 217eb0da1..4939906ee 100644 --- a/internal/providers/zhipu/zhipu_test.go +++ b/internal/providers/zhipu/zhipu_test.go @@ -229,3 +229,15 @@ func mustJSON(t *testing.T, value any) []byte { } return raw } + +func TestCollectChatSSERejectsErrorAndTruncatedStreams(t *testing.T) { + if _, err := collectChatSSE(strings.NewReader(`data: {"error":{"message":"quota exhausted","code":"1113"}}`+"\n\n"), "glm-5.2"); err == nil || !strings.Contains(err.Error(), "quota exhausted") { + t.Fatalf("error frame error = %v", err) + } + if _, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{"content":"partial"}}]}`+"\n\n"), "glm-5.2"); err == nil || !strings.Contains(err.Error(), "terminal") { + t.Fatalf("truncated stream error = %v", err) + } + if outcome, err := collectChatSSE(strings.NewReader(`data: {"choices":[{"delta":{},"finish_reason":"stop"}]}`+"\n\n"), "glm-5.2"); err != nil || outcome.FinishReason != "stop" { + t.Fatalf("finish-only stream outcome=%+v err=%v", outcome, err) + } +} From 29708f3ddd31754ba93f12b0c2835ffcded1b430 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:36:50 +0800 Subject: [PATCH 3/4] feat(accounts): track request state per attempt Each attempt now carries its kind, state, whether the request reached upstream, and the error code, so a failed round can say where it stopped instead of only that it failed. Aggregation pipelines are compiled together with the classifier so a logical model keeps its own target list and grant scope. --- changelog/unreleased/request-attempt-state.md | 9 + internal/accounts/aggregation.go | 138 +- internal/accounts/aggregation_grant_test.go | 2 + internal/accounts/aggregation_test.go | 89 ++ internal/accounts/grants.go | 2 +- internal/accounts/pipeline.go | 251 +-- internal/accounts/pipeline_test.go | 134 ++ internal/accounts/request_logs.go | 45 + internal/executor/aggregation_e2e_test.go | 18 +- internal/executor/aggregation_plan.go | 102 +- internal/executor/aggregation_preview.go | 63 + internal/executor/aggregation_preview_test.go | 120 ++ internal/executor/aggregation_priority.go | 410 +++++ .../executor/aggregation_priority_test.go | 195 +++ .../aggregation_route_contract_test.go | 98 ++ internal/executor/aggregation_seats.go | 334 ++-- internal/executor/aggregation_seats_test.go | 319 +++- .../executor/aggregation_strategy_test.go | 143 +- internal/executor/chat.go | 1340 ++--------------- internal/executor/chat_test.go | 40 +- internal/executor/classify.go | 148 +- internal/executor/classify_test.go | 48 +- internal/executor/dispatch.go | 599 ++++++++ internal/executor/error.go | 431 +++++- internal/executor/fefo.go | 65 +- internal/executor/fefo_test.go | 37 + internal/executor/native_responses_test.go | 146 ++ internal/executor/pool.go | 815 ++++++---- internal/executor/pool_model_feedback_test.go | 129 ++ internal/executor/pool_reservation_test.go | 319 ++++ internal/executor/pool_route_test.go | 4 +- internal/executor/prepare.go | 408 +++-- internal/executor/prepare_test.go | 395 ++++- internal/executor/probe.go | 217 +-- internal/executor/probe_test.go | 238 ++- internal/executor/providers_test.go | 65 +- internal/executor/public_error.go | 82 + internal/executor/public_error_test.go | 35 + .../route_integration_regression_test.go | 360 +++++ internal/executor/route_refactor_test.go | 143 ++ internal/executor/routing.go | 418 +++++ internal/executor/routing_tooling_test.go | 177 +++ internal/executor/session_affinity.go | 94 +- internal/executor/session_affinity_test.go | 99 ++ internal/executor/session_key_test.go | 6 +- .../executor/sticky_model_rejection_test.go | 227 +++ internal/executor/timeout_attribution_test.go | 76 + internal/executor/tooling.go | 147 ++ internal/executor/tooling_test.go | 120 ++ internal/executor/transport_failure_test.go | 11 +- internal/executor/upstream_align_test.go | 2 +- 51 files changed, 7578 insertions(+), 2335 deletions(-) create mode 100644 changelog/unreleased/request-attempt-state.md create mode 100644 internal/accounts/aggregation_test.go create mode 100644 internal/executor/aggregation_preview.go create mode 100644 internal/executor/aggregation_preview_test.go create mode 100644 internal/executor/aggregation_priority.go create mode 100644 internal/executor/aggregation_priority_test.go create mode 100644 internal/executor/aggregation_route_contract_test.go create mode 100644 internal/executor/dispatch.go create mode 100644 internal/executor/pool_model_feedback_test.go create mode 100644 internal/executor/pool_reservation_test.go create mode 100644 internal/executor/public_error.go create mode 100644 internal/executor/public_error_test.go create mode 100644 internal/executor/route_integration_regression_test.go create mode 100644 internal/executor/route_refactor_test.go create mode 100644 internal/executor/routing.go create mode 100644 internal/executor/routing_tooling_test.go create mode 100644 internal/executor/sticky_model_rejection_test.go create mode 100644 internal/executor/timeout_attribution_test.go create mode 100644 internal/executor/tooling.go create mode 100644 internal/executor/tooling_test.go diff --git a/changelog/unreleased/request-attempt-state.md b/changelog/unreleased/request-attempt-state.md new file mode 100644 index 000000000..6661bce2a --- /dev/null +++ b/changelog/unreleased/request-attempt-state.md @@ -0,0 +1,9 @@ +### English + +- Record per-attempt request state (`kind`, `state`, whether the request went upstream, and the error code) so a failed round explains where it stopped. +- Compile the aggregation pipeline with the classifier in one place, so a logical-model dispatch keeps its own target list and grant scope. + +### 中文 + +- 每次尝试记录请求状态(类型、状态、是否已发往上游、错误码),失败的一轮能说明停在哪一步。 +- 聚合管线与分类器在同一处编译,逻辑模型分发的目标列表与授权范围保持一致。 diff --git a/internal/accounts/aggregation.go b/internal/accounts/aggregation.go index a5994eb13..c78c8ea14 100644 --- a/internal/accounts/aggregation.go +++ b/internal/accounts/aggregation.go @@ -120,55 +120,111 @@ func NormalizeAggregationStrategy(value string) AggregationStrategy { } } +// SplitProviderModelPrefix separates the gateway's reserved provider selector +// from a model ID. The remaining model may itself have slash-separated parts. +// Prefixes are case-sensitive; lookup in the registry alone is not. +func SplitProviderModelPrefix(model string) (provider, region, bare string) { + model = strings.TrimSpace(model) + prefix, bare, found := strings.Cut(model, "/") + if !found { + return "", "", model + } + family := func(segment string) string { + descriptor, ok := providers.Get(segment) + if ok && (segment == descriptor.ID || segment == "muse") { + return descriptor.ID + } + return "" + } + if provider = family(prefix); provider != "" { + return provider, "", bare + } + if i := strings.LastIndexByte(prefix, '-'); i >= 0 { + switch prefix[i+1:] { + case "cn": + region = "cn" + case "gl": + region = "global" + case "auto": + // No explicit region pin. + default: + return "", "", model + } + if provider = family(prefix[:i]); provider != "" { + return provider, region, bare + } + } + return "", "", model +} + // BareAggregationModel strips a provider or provider-region prefix that // belongs to this member. A foreign prefix stays intact. func BareAggregationModel(provider, region, model string) string { - return normalizeAggregationModel(provider, region, model) + bare, _ := splitAggregationTarget(provider, region, model) + return bare } -// normalizeAggregationModel stores the concrete upstream model without the -// provider or provider-region prefix a client-facing model list may have -// added. A foreign prefix, including Command's org-scoped ids, stays intact. -// An empty provider does not inherit the qoder default, so an unnamed member -// cannot strip a qoder/ prefix by accident. - -func normalizeAggregationModel(provider, region, model string) string { +// splitAggregationTarget recognizes a prefix belonging to the target's own +// provider. A foreign prefix, including Command's org-scoped IDs, stays intact. +// The region result is a hard pin implied by an explicit region qualifier. +func splitAggregationTarget(provider, region, model string) (bare, impliedRegion string) { model = strings.TrimSpace(model) - if model == "" { - return "" - } first, rest, found := strings.Cut(model, "/") - if !found { - return model - } - candidate := strings.ToLower(strings.TrimSpace(first)) raw := strings.ToLower(strings.TrimSpace(provider)) - if raw == "" || strings.TrimSpace(rest) == "" { - return model + rest = strings.TrimSpace(rest) + if !found || raw == "" || rest == "" { + return model, "" } + prefix := strings.ToLower(strings.TrimSpace(first)) family := NormalizeProviderFamily(raw) - names := []string{family} - if raw != family { - names = append(names, raw) + sameFamily := func(name string) bool { + return name != "" && NormalizeProviderFamily(name) == family + } + if sameFamily(prefix) { + return rest, "" + } + if i := strings.LastIndexByte(prefix, '-'); i >= 0 && sameFamily(prefix[:i]) { + switch suffix := prefix[i+1:]; suffix { + case "cn", "gl", "global": + return rest, NormalizeRegion(suffix) + case "auto": + return rest, "" + default: + // Legacy explicit region spelling (e.g. opencode-go). Do not + // infer unrecognized region qualifiers without a matching pin. + if suffix != "" && suffix == strings.ToLower(strings.TrimSpace(region)) { + return rest, "" + } + } } + return model, "" +} + +func normalizeAggregationTarget(provider, region, model string) (bare, targetRegion string, err error) { region = strings.ToLower(strings.TrimSpace(region)) - for _, name := range names { - if name == "" { - continue + bare = strings.TrimSpace(model) + // Remove all own-provider wrappers in one pass so serializing and parsing + // a document again cannot discover a different model or region. + for { + next, impliedRegion := splitAggregationTarget(provider, region, bare) + if next == bare { + return bare, region, nil } - if candidate == name || (region != "" && candidate == name+"-"+region) { - return strings.TrimSpace(rest) - } - for _, suffix := range []string{"-cn", "-gl", "-global", "-auto"} { - if candidate == name+suffix { - return strings.TrimSpace(rest) + if impliedRegion != "" { + if region == "" || region == "auto" { + region = impliedRegion + } else if NormalizeRegion(region) != impliedRegion { + return "", "", fmt.Errorf("model %q specifies region %q, which conflicts with region %q", strings.TrimSpace(model), impliedRegion, region) } } + bare = next } - return model } -func normalizeAggregationMembers(members []AggregationMember) ([]AggregationMember, error) { +// normalizeAggregationMembers validates and orders the compatibility member +// list. Normalize targets on flat writes; a pipeline has already normalized +// its own leaves and may contain unchanged flat members from a legacy child. +func normalizeAggregationMembers(members []AggregationMember, normalizeTargets bool) ([]AggregationMember, error) { if len(members) == 0 { return nil, fmt.Errorf("aggregation requires at least one member") } @@ -185,6 +241,13 @@ func normalizeAggregationMembers(members []AggregationMember) ([]AggregationMemb if provider == "" || model == "" { return nil, fmt.Errorf("aggregation member requires provider and model") } + if normalizeTargets { + var err error + model, region, err = normalizeAggregationTarget(provider, region, model) + if err != nil { + return nil, err + } + } if len(accountID) > 256 { return nil, fmt.Errorf("aggregation member account id is too long") } @@ -318,6 +381,15 @@ func PrepareCreateAggregation(input CreateAggregation) (CreateAggregation, error if !validAggregationID(id) { return CreateAggregation{}, fmt.Errorf("aggregation id required (lowercase letters, digits, '-' and '/')") } + if strings.HasPrefix(id, "/") || strings.HasSuffix(id, "/") || strings.Contains(id, "//") { + return CreateAggregation{}, fmt.Errorf("aggregation id must not contain an empty path segment") + } + if id == "new" { + return CreateAggregation{}, fmt.Errorf("aggregation id %q uses a reserved editor path", id) + } + if provider, _, _ := SplitProviderModelPrefix(id); provider != "" { + return CreateAggregation{}, fmt.Errorf("aggregation id %q uses a reserved provider prefix", id) + } name := strings.TrimSpace(input.Name) if name == "" { name = id @@ -327,7 +399,7 @@ func PrepareCreateAggregation(input CreateAggregation) (CreateAggregation, error } var members []AggregationMember if strings.TrimSpace(input.Document) == "" { - normalized, err := normalizeAggregationMembers(input.Members) + normalized, err := normalizeAggregationMembers(input.Members, true) if err != nil { return CreateAggregation{}, err } @@ -391,7 +463,7 @@ func ApplyAggregationUpdate(current Aggregation, input UpdateAggregation) (Aggre current.Document = strings.TrimSpace(*input.Document) } if input.Members != nil && strings.TrimSpace(current.Document) == "" { - members, err := normalizeAggregationMembers(*input.Members) + members, err := normalizeAggregationMembers(*input.Members, true) if err != nil { return Aggregation{}, err } diff --git a/internal/accounts/aggregation_grant_test.go b/internal/accounts/aggregation_grant_test.go index a8ea64299..906d84eda 100644 --- a/internal/accounts/aggregation_grant_test.go +++ b/internal/accounts/aggregation_grant_test.go @@ -24,6 +24,8 @@ func TestIsAggregationOnly(t *testing.T) { {[]string{"aggregation"}, true}, {[]string{"aggregation", "aggregation"}, true}, {[]string{"aggregation", "qoder"}, false}, + {[]string{" aggregation "}, false}, + {[]string{"aggregation", " aggregation"}, false}, {[]string{"qoder"}, false}, {nil, false}, } diff --git a/internal/accounts/aggregation_test.go b/internal/accounts/aggregation_test.go new file mode 100644 index 000000000..02e8e3b9f --- /dev/null +++ b/internal/accounts/aggregation_test.go @@ -0,0 +1,89 @@ +package accounts + +import ( + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func TestSplitProviderModelPrefix(t *testing.T) { + for _, entry := range providers.List() { + for _, variant := range []struct{ suffix, region string }{ + {"", ""}, {"-cn", "cn"}, {"-gl", "global"}, {"-auto", ""}, + } { + model := entry.ID + variant.suffix + "/namespace/upstream" + if provider, region, bare := SplitProviderModelPrefix(model); provider != entry.ID || region != variant.region || bare != "namespace/upstream" { + t.Errorf("SplitProviderModelPrefix(%q) = %q, %q, %q", model, provider, region, bare) + } + } + } + for _, tc := range []struct{ model, provider, region, bare string }{ + {" muse-cn/upstream ", "meta", "cn", "upstream"}, + {"qoder/", "qoder", "", ""}, + {"qoder-cn/ model", "qoder", "cn", " model"}, + {" Qoder-cn/model ", "", "", "Qoder-cn/model"}, + {"qoder /model", "", "", "qoder /model"}, + {"qoder-global/model", "", "", "qoder-global/model"}, + {"team/model", "", "", "team/model"}, + {"qoder", "", "", "qoder"}, + {" ", "", "", ""}, + } { + if provider, region, bare := SplitProviderModelPrefix(tc.model); provider != tc.provider || region != tc.region || bare != tc.bare { + t.Errorf("SplitProviderModelPrefix(%q) = %q, %q, %q; want %q, %q, %q", tc.model, provider, region, bare, tc.provider, tc.region, tc.bare) + } + } +} + +func TestPrepareCreateAggregationReservesOnlyDirectModelPrefixes(t *testing.T) { + input := CreateAggregation{Members: []AggregationMember{{Provider: "qoder", Model: "upstream"}}} + for _, id := range []string{" qOdEr/upstream ", "workbuddy-cn/upstream", "muse-gl/upstream", "codex-auto/name"} { + input.ID = id + if _, err := PrepareCreateAggregation(input); err == nil || !strings.Contains(err.Error(), "reserved provider prefix") { + t.Errorf("Create with reserved ID %q returned %v", id, err) + } + } + for _, id := range []string{"qoder", "team/review", "qoder-global/review", "review/qoder", "preview", "team/new"} { + input.ID = id + if got, err := PrepareCreateAggregation(input); err != nil || got.ID != id { + t.Errorf("Create with ID %q returned %q, %v", id, got.ID, err) + } + } +} + +func TestPrepareCreateAggregationRejectsUnmanageablePaths(t *testing.T) { + for _, id := range []string{" new ", "/", "/team", "team/", "team//review"} { + input := CreateAggregation{ID: id, Members: []AggregationMember{{Provider: "qoder", Model: "upstream"}}} + if _, err := PrepareCreateAggregation(input); err == nil { + t.Errorf("Create with ID %q succeeded", id) + } + } +} + +func TestFlatAggregationMemberProviderPrefixKeepsItsRegion(t *testing.T) { + for _, tc := range []struct { + provider, region, model string + wantRegion, wantModel string + }{ + {"qoder", "", " QODER-CN/upstream ", "cn", "upstream"}, + {"qoder", "GL", "qoder-global/upstream", "gl", "upstream"}, + {"qoder", "cn", "qoder-auto/upstream", "cn", "upstream"}, + {"meta", "", "muse-gl/upstream", "global", "upstream"}, + {"command", "", "command/org/upstream", "", "org/upstream"}, + {"command", "", "qoder-cn/upstream", "", "qoder-cn/upstream"}, + {"opencode", "go", "opencode-go/upstream", "go", "upstream"}, + } { + member := AggregationMember{Provider: tc.provider, Region: tc.region, Model: tc.model} + got, err := PrepareCreateAggregation(CreateAggregation{ID: "logical", Members: []AggregationMember{member}}) + if err != nil || len(got.Members) != 1 || got.Members[0].Region != tc.wantRegion || got.Members[0].Model != tc.wantModel { + t.Errorf("member %+v normalized to %+v, %v; want model %q and region %q", member, got.Members, err, tc.wantModel, tc.wantRegion) + } + } + conflict := []AggregationMember{{Provider: "qoder", Region: "global", Model: "qoder-cn/upstream"}} + if _, err := PrepareCreateAggregation(CreateAggregation{ID: "logical", Members: conflict}); err == nil || !strings.Contains(err.Error(), "conflicts") { + t.Fatalf("creation accepted conflicting region: %v", err) + } + if _, err := ApplyAggregationUpdate(Aggregation{ID: "logical"}, UpdateAggregation{Members: &conflict}); err == nil || !strings.Contains(err.Error(), "conflicts") { + t.Fatalf("update accepted conflicting region: %v", err) + } +} diff --git a/internal/accounts/grants.go b/internal/accounts/grants.go index aef22cb4c..2ae3c81d5 100644 --- a/internal/accounts/grants.go +++ b/internal/accounts/grants.go @@ -121,7 +121,7 @@ func IsAggregationOnly(allowed []string) bool { return false } for _, entry := range allowed { - grant, err := ParseProviderGrant(strings.TrimSpace(entry)) + grant, err := ParseProviderGrant(entry) if err != nil || grant.Provider != AggregationProvider { return false } diff --git a/internal/accounts/pipeline.go b/internal/accounts/pipeline.go index b847cf96d..de879886a 100644 --- a/internal/accounts/pipeline.go +++ b/internal/accounts/pipeline.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "strings" + + "github.com/caigee-cmd/cli2api/internal/providers" ) const ( @@ -83,11 +85,12 @@ func CollectPipeline(id, document string, catalog map[string]Aggregation) (strin return "", nil, err } var seq int - members, err := collectSteps(id, doc.Steps, 0, map[string]bool{id: true}, catalog, &seq) + id = strings.ToLower(strings.TrimSpace(id)) + members, err := collectSteps(id, doc.Steps, 0, map[string]bool{id: true}, catalog, &seq, collectSubmitted) if err != nil { return "", nil, err } - members, err = normalizeAggregationMembers(members) + members, err = normalizeAggregationMembers(members, false) if err != nil { return "", nil, err } @@ -98,10 +101,56 @@ func CollectPipeline(id, document string, catalog map[string]Aggregation) (strin return string(raw), members, nil } +// PipelineCatalogMembers enumerates the members reachable through the current +// group snapshot. Unlike saving or compiling a request, it neither rewrites +// the document nor chooses or dispatches a classifier. Broken alternatives +// do not mask other valid intent paths, but a broken required step does. +func PipelineCatalogMembers(agg Aggregation, catalog map[string]Aggregation) ([]AggregationMember, error) { + if strings.TrimSpace(agg.Document) == "" { + return agg.Members, nil + } + doc, err := parsePipeline(agg.Document) + if err != nil { + return nil, err + } + var seq int + id := strings.ToLower(strings.TrimSpace(agg.ID)) + return collectSteps(id, doc.Steps, 0, map[string]bool{id: true}, catalog, &seq, collectCatalog) +} + // CompilePipeline selects one path and builds the seats for a single request. // labels maps ClassifierTarget.Key to the label a classifier returned. An // empty label falls through to keywords and then the fallback path. func CompilePipeline(agg Aggregation, catalog map[string]Aggregation, text string, labels map[string]string, allowed map[string]bool) (Aggregation, []RouteSeat, string, error) { + return compilePipeline(agg, catalog, text, allowed, func(c *pipelineClassifier) (string, error) { + return labels[c.target().Key()], nil + }) +} + +// CompilePipelineWithClassifier resolves labels only for branch steps reached +// on the selected path, including branches in selected groups. The callback +// is synchronous and called once per distinct target in this compile. An +// empty result keeps the same keyword and fallback rules as CompilePipeline. +func CompilePipelineWithClassifier(agg Aggregation, catalog map[string]Aggregation, text string, allowed map[string]bool, classify func(ClassifierTarget) string) (Aggregation, []RouteSeat, string, error) { + labels := make(map[string]string) + return compilePipeline(agg, catalog, text, allowed, func(c *pipelineClassifier) (string, error) { + if classify == nil { + return "", nil + } + target := c.target() + key := target.Key() + label, ok := labels[key] + if !ok { + label = classify(target) + labels[key] = label + } + return label, nil + }) +} + +type pipelineClassifierLookup func(*pipelineClassifier) (string, error) + +func compilePipeline(agg Aggregation, catalog map[string]Aggregation, text string, allowed map[string]bool, lookup pipelineClassifierLookup) (Aggregation, []RouteSeat, string, error) { if strings.TrimSpace(agg.Document) == "" { return agg, nil, "", nil } @@ -109,9 +158,10 @@ func CompilePipeline(agg Aggregation, catalog map[string]Aggregation, text strin if err != nil { return Aggregation{}, nil, "", err } - chosen, path := selectSteps(doc.Steps, text, labels) + var path string var seq int - seats, members, err := seatSteps(agg.ID, chosen, 0, map[string]bool{agg.ID: true}, catalog, text, labels, &seq) + id := strings.ToLower(strings.TrimSpace(agg.ID)) + seats, members, err := seatSteps(id, doc.Steps, 0, map[string]bool{id: true}, catalog, text, lookup, &seq, &path) if err != nil { return Aggregation{}, nil, "", err } @@ -139,6 +189,7 @@ func ClassifierTargets(id, document string, catalog map[string]Aggregation) ([]C } var out []ClassifierTarget seen := map[string]bool{} + id = strings.ToLower(strings.TrimSpace(id)) if err := walkClassifiers(id, doc.Steps, 0, map[string]bool{id: true}, catalog, seen, &out); err != nil { return nil, err } @@ -163,40 +214,17 @@ func parsePipeline(document string) (pipelineDoc, error) { return doc, nil } -// normalizePipelineSteps makes the stored document and the live compiler -// agree on provider, region, and model spelling, and turns a multi-account -// member into one seat per checked account. A hand-written document can -// otherwise carry "Qoder" or "qoder/glm" and compile to a seat no account -// can serve, or keep only the first checked account and widen the rest of -// the route to the whole provider. +// normalizePipelineSteps expands a multi-account member into one seat per +// checked account. Model selectors are normalized when each leaf is reached, +// so a stored invalid leaf on an unselected branch does not block routing. func normalizePipelineSteps(steps []pipelineStep) []pipelineStep { steps = expandMemberAccounts(steps) for i := range steps { step := &steps[i] switch step.Kind { - case "member": - rawProvider := strings.ToLower(strings.TrimSpace(step.Provider)) - if rawProvider != "" { - step.Provider = NormalizeProviderFamily(rawProvider) - } - step.Region = strings.ToLower(strings.TrimSpace(step.Region)) - if strings.TrimSpace(step.Model) != "" { - step.Model = normalizeAggregationModel(rawProvider, step.Region, step.Model) - } - step.AccountID = strings.TrimSpace(step.AccountID) case "group": step.AggregationID = strings.ToLower(strings.TrimSpace(step.AggregationID)) case "branch": - if step.Classifier != nil { - rawProvider := strings.ToLower(strings.TrimSpace(step.Classifier.Provider)) - if rawProvider != "" { - step.Classifier.Provider = NormalizeProviderFamily(rawProvider) - } - step.Classifier.Region = strings.ToLower(strings.TrimSpace(step.Classifier.Region)) - if strings.TrimSpace(step.Classifier.Model) != "" { - step.Classifier.Model = normalizeAggregationModel(rawProvider, step.Classifier.Region, step.Classifier.Model) - } - } for j := range step.Paths { step.Paths[j].Steps = normalizePipelineSteps(step.Paths[j].Steps) } @@ -266,18 +294,28 @@ func selectedAccountIDs(step pipelineStep) []string { return ids } -func collectSteps(self string, steps []pipelineStep, depth int, stack map[string]bool, catalog map[string]Aggregation, seq *int) ([]AggregationMember, error) { +type pipelineCollectMode uint8 + +const ( + collectSubmitted pipelineCollectMode = iota + collectStored + collectCatalog +) + +func collectSteps(self string, steps []pipelineStep, depth int, stack map[string]bool, catalog map[string]Aggregation, seq *int, mode pipelineCollectMode) ([]AggregationMember, error) { var out []AggregationMember - for _, step := range steps { + for i := range steps { + step := &steps[i] switch step.Kind { case "member": - member, err := leafMember(step, seq) + member, err := leafMember(*step, seq) if err != nil { return nil, err } + step.Provider, step.Region, step.Model, step.AccountID = member.Provider, member.Region, member.Model, member.AccountID out = append(out, member) case "group": - nested, err := openGroup(self, step, depth, stack, catalog) + nested, err := openGroup(self, *step, depth, stack, catalog) if err != nil { return nil, err } @@ -294,7 +332,13 @@ func collectSteps(self string, steps []pipelineStep, depth int, stack map[string return nil, err } stack[nested.ID] = true - inner, err := collectSteps(nested.ID, doc.Steps, depth+1, stack, catalog, seq) + // Only the submitted document is rewritten. A referenced legacy + // child retains the same first-default semantics as live compile. + nestedMode := mode + if nestedMode == collectSubmitted { + nestedMode = collectStored + } + inner, err := collectSteps(nested.ID, doc.Steps, depth+1, stack, catalog, seq, nestedMode) delete(stack, nested.ID) if err != nil { return nil, err @@ -304,20 +348,28 @@ func collectSteps(self string, steps []pipelineStep, depth int, stack map[string if err := validateClassifier(step.Classifier, catalog); err != nil { return nil, err } - paths := step.Paths - if len(step.Fallback) > 0 { - paths = append(paths, pipelinePath{ID: step.ID + "-fallback", Label: "Default", Fallback: true, Steps: step.Fallback}) + paths, err := pipelinePaths(*step, mode == collectSubmitted) + if err != nil { + return nil, err } if len(paths) == 0 { return nil, fmt.Errorf("branch %s has no paths", step.ID) } + validPath := false for _, path := range paths { - inner, err := collectSteps(self, path.Steps, depth, stack, catalog, seq) + inner, err := collectSteps(self, path.Steps, depth, stack, catalog, seq, mode) if err != nil { + if mode == collectCatalog { + continue + } return nil, err } + validPath = true out = append(out, inner...) } + if !validPath { + return nil, fmt.Errorf("branch %s has no valid path", step.ID) + } default: return nil, fmt.Errorf("unknown pipeline step %q", step.Kind) } @@ -325,7 +377,7 @@ func collectSteps(self string, steps []pipelineStep, depth int, stack map[string return out, nil } -func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bool, catalog map[string]Aggregation, text string, labels map[string]string, seq *int) ([]RouteSeat, []AggregationMember, error) { +func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bool, catalog map[string]Aggregation, text string, lookup pipelineClassifierLookup, seq *int, path *string) ([]RouteSeat, []AggregationMember, error) { var seats []RouteSeat var members []AggregationMember for _, step := range steps { @@ -345,9 +397,11 @@ func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bo seat := RouteSeat{ID: step.ID, Kind: "group", Priority: *seq, Weight: weightOf(step.Weight), GroupID: nested.ID, GroupStrategy: nested.Strategy} if strings.TrimSpace(nested.Document) == "" { for _, member := range nested.Members { + // Keep the child's configured tier for group scheduling. Only + // the compatibility member list uses the parent traversal order. + seat.GroupMembers = append(seat.GroupMembers, member) member.Priority = *seq *seq++ - seat.GroupMembers = append(seat.GroupMembers, member) members = append(members, member) } } else { @@ -355,9 +409,8 @@ func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bo if err != nil { return nil, nil, err } - chosen, _ := selectSteps(doc.Steps, text, labels) stack[nested.ID] = true - innerSeats, innerMembers, err := seatSteps(nested.ID, chosen, depth+1, stack, catalog, text, labels, seq) + innerSeats, innerMembers, err := seatSteps(nested.ID, doc.Steps, depth+1, stack, catalog, text, lookup, seq, nil) delete(stack, nested.ID) if err != nil { return nil, nil, err @@ -374,8 +427,22 @@ func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bo } seats = append(seats, seat) case "branch": - chosen, _ := selectSteps([]pipelineStep{step}, text, labels) - innerSeats, innerMembers, err := seatSteps(self, chosen, depth, stack, catalog, text, labels, seq) + var label string + if step.Classifier != nil { + if err := validateClassifier(step.Classifier, catalog); err != nil { + return nil, nil, err + } + var err error + label, err = lookup(step.Classifier) + if err != nil { + return nil, nil, err + } + } + chosen, pathLabel := choosePath(step, text, label) + if path != nil && *path == "" { + *path = pathLabel + } + innerSeats, innerMembers, err := seatSteps(self, chosen, depth, stack, catalog, text, lookup, seq, nil) if err != nil { return nil, nil, err } @@ -388,37 +455,42 @@ func seatSteps(self string, steps []pipelineStep, depth int, stack map[string]bo return seats, members, nil } -func selectSteps(steps []pipelineStep, text string, labels map[string]string) ([]pipelineStep, string) { - var out []pipelineStep - path := "" - for _, step := range steps { - if step.Kind != "branch" { - out = append(out, step) - continue +// pipelinePaths uses the first explicit default for legacy documents, just +// as routing always has. Reject duplicate defaults only in new writes. +func pipelinePaths(step pipelineStep, validateDefaults bool) ([]pipelinePath, error) { + paths := make([]pipelinePath, 0, len(step.Paths)+1) + seenDefault := false + for _, path := range step.Paths { + if path.Fallback { + if seenDefault { + if validateDefaults { + return nil, fmt.Errorf("branch %s has more than one fallback path", step.ID) + } + continue + } + seenDefault = true } - chosen, label := choosePath(step, text, labels) - if path == "" { - path = label + paths = append(paths, path) + } + if len(step.Fallback) > 0 { + if !seenDefault { + paths = append(paths, pipelinePath{Label: "Default", Fallback: true, Steps: step.Fallback}) + } else if validateDefaults { + return nil, fmt.Errorf("branch %s has more than one fallback path", step.ID) } - out = append(out, chosen...) } - return out, path + return paths, nil } -func choosePath(step pipelineStep, text string, labels map[string]string) ([]pipelineStep, string) { - paths := step.Paths - if len(step.Fallback) > 0 { - paths = append(paths, pipelinePath{Label: "Default", Fallback: true, Steps: step.Fallback}) - } - if step.Classifier != nil && labels != nil { - if label := strings.TrimSpace(labels[classifierKey(*step.Classifier)]); label != "" { - for _, path := range paths { - if path.Fallback { - continue - } - if strings.EqualFold(path.Intent, label) || strings.EqualFold(path.Label, label) { - return path.Steps, path.Label - } +func choosePath(step pipelineStep, text, classifierLabel string) ([]pipelineStep, string) { + paths, _ := pipelinePaths(step, false) + if label := strings.TrimSpace(classifierLabel); label != "" { + for _, path := range paths { + if path.Fallback { + continue + } + if strings.EqualFold(path.Intent, label) || strings.EqualFold(path.Label, label) { + return path.Steps, path.Label } } } @@ -470,11 +542,14 @@ func leafMember(step pipelineStep, seq *int) (AggregationMember, error) { if rawProvider == "" || model == "" { return AggregationMember{}, fmt.Errorf("member step %s needs a provider and a model", step.ID) } - region := strings.ToLower(strings.TrimSpace(step.Region)) + model, region, err := normalizeAggregationTarget(rawProvider, step.Region, model) + if err != nil { + return AggregationMember{}, fmt.Errorf("member step %s: %w", step.ID, err) + } member := AggregationMember{ Provider: NormalizeProviderFamily(rawProvider), Region: region, - Model: normalizeAggregationModel(rawProvider, region, model), + Model: model, AccountID: strings.TrimSpace(step.AccountID), Priority: *seq, Weight: weightOf(step.Weight), @@ -500,24 +575,28 @@ func validateClassifier(c *pipelineClassifier, catalog map[string]Aggregation) e return fmt.Errorf("classifier needs a provider and a model") } provider := NormalizeProviderFamily(rawProvider) - if provider == AggregationProvider || rawProvider == AggregationProvider { + if provider == AggregationProvider { return fmt.Errorf("classifier must be a concrete model") } - if _, ok := catalog[rawProvider]; ok { - return fmt.Errorf("classifier must be a concrete model") + // A registered provider denotes a direct target even if a logical + // aggregation happens to share its name. + if _, registered := providers.Get(provider); !registered { + if _, logical := catalog[provider]; logical { + return fmt.Errorf("classifier must be a concrete model") + } } - if _, ok := catalog[provider]; ok { - return fmt.Errorf("classifier must be a concrete model") + model, region, err := normalizeAggregationTarget(rawProvider, c.Region, model) + if err != nil { + return fmt.Errorf("classifier: %w", err) } - region := strings.ToLower(strings.TrimSpace(c.Region)) c.Provider = provider - c.Model = normalizeAggregationModel(rawProvider, region, model) + c.Model = model c.Region = region return nil } -func classifierKey(c pipelineClassifier) string { - return ClassifierTarget{Provider: c.Provider, Region: c.Region, Model: c.Model}.Key() +func (c pipelineClassifier) target() ClassifierTarget { + return ClassifierTarget{Provider: c.Provider, Region: c.Region, Model: c.Model} } func walkClassifiers(self string, steps []pipelineStep, depth int, stack map[string]bool, catalog map[string]Aggregation, seen map[string]bool, out *[]ClassifierTarget) error { @@ -528,20 +607,18 @@ func walkClassifiers(self string, steps []pipelineStep, depth int, stack map[str return err } if step.Classifier != nil { - target := ClassifierTarget{Provider: step.Classifier.Provider, Region: step.Classifier.Region, Model: step.Classifier.Model} + target := step.Classifier.target() if !seen[target.Key()] { seen[target.Key()] = true *out = append(*out, target) } } - for _, path := range step.Paths { + paths, _ := pipelinePaths(step, false) + for _, path := range paths { if err := walkClassifiers(self, path.Steps, depth, stack, catalog, seen, out); err != nil { return err } } - if err := walkClassifiers(self, step.Fallback, depth, stack, catalog, seen, out); err != nil { - return err - } case "group": nested, err := openGroup(self, step, depth, stack, catalog) if err != nil { diff --git a/internal/accounts/pipeline_test.go b/internal/accounts/pipeline_test.go index e154afcce..10d5c18db 100644 --- a/internal/accounts/pipeline_test.go +++ b/internal/accounts/pipeline_test.go @@ -72,6 +72,49 @@ func TestPipelineFallbackWhenClassifierMisses(t *testing.T) { } } +func TestPipelineClassifierVisitsOnlySelectedBranchesAndCachesLabels(t *testing.T) { + const doc = `{"version":1,"steps":[ + {"id":"root","kind":"branch","classifier":{"provider":"qoder","model":"classify-root"},"paths":[ + {"id":"chosen","label":"Chosen","intent":"choose","steps":[ + {"id":"inner","kind":"group","aggregation_id":"inner"} + ]}, + {"id":"fallback","label":"Fallback","fallback":true,"steps":[ + {"id":"unused","kind":"branch","classifier":{"provider":"qoder","model":"classify-unused"},"fallback":[ + {"id":"leaf","kind":"member","provider":"qoder","model":"unused"} + ]} + ]} + ]}, + {"id":"repeat","kind":"branch","classifier":{"provider":"qoder","model":"classify-root"},"fallback":[ + {"id":"tail","kind":"member","provider":"qoder","model":"tail"} + ]} + ]}` + const innerDoc = `{"version":1,"steps":[ + {"id":"inner","kind":"branch","classifier":{"provider":"workbuddy","region":"cn","model":"classify-inner"},"paths":[ + {"id":"match","label":"Match","keywords":["plan"],"steps":[ + {"id":"leaf","kind":"member","provider":"qoder","model":"chosen"} + ]} + ],"fallback":[{"id":"default","kind":"member","provider":"qoder","model":"default"}]} + ]}` + catalog := map[string]Aggregation{"inner": {ID: "inner", Enabled: true, Document: innerDoc}} + var visited []string + agg, _, path, err := CompilePipelineWithClassifier(Aggregation{ID: "outer", Document: doc}, catalog, "please plan", nil, func(target ClassifierTarget) string { + visited = append(visited, target.Key()) + if target.Model == "classify-root" { + return "choose" + } + return "" + }) + if err != nil { + t.Fatal(err) + } + if got := strings.Join(visited, ","); got != "qoder||classify-root,workbuddy|cn|classify-inner" { + t.Fatalf("classifier visits = %s, want only selected and deduplicated targets", got) + } + if path != "Chosen" || len(agg.Members) != 2 || agg.Members[0].Model != "chosen" || agg.Members[1].Model != "tail" { + t.Fatalf("compiled path=%q members=%+v", path, agg.Members) + } +} + func TestPipelineNestedGroupKeepsInnerOrder(t *testing.T) { inner := `{ "version": 1, @@ -105,6 +148,32 @@ func TestPipelineNestedGroupKeepsInnerOrder(t *testing.T) { } } +func TestPipelineKeepsLegacyGroupTiersWithoutChangingFlatOrder(t *testing.T) { + const doc = `{"version":1,"steps":[{"id":"group","kind":"group","aggregation_id":"inner"},{"id":"tail","kind":"member","provider":"qoder","model":"tail"}]}` + inner := Aggregation{ID: "inner", Enabled: true, Strategy: AggregationPriority, Members: []AggregationMember{ + {Provider: "qoder", Model: "a", Priority: 4}, + {Provider: "qoder", Model: "b", Priority: 4}, + {Provider: "qoder", Model: "c", Priority: 7}, + }} + agg, seats, _, err := CompilePipeline(Aggregation{ID: "outer", Document: doc, Strategy: AggregationPriority}, map[string]Aggregation{inner.ID: inner}, "", nil, nil) + if err != nil { + t.Fatal(err) + } + if len(seats) != 2 || len(seats[0].GroupMembers) != 3 || len(agg.Members) != 4 { + t.Fatalf("seats = %+v, members = %+v", seats, agg.Members) + } + for i, want := range []int{4, 4, 7} { + if got := seats[0].GroupMembers[i].Priority; got != want { + t.Fatalf("group member %d priority = %d, want %d", i, got, want) + } + } + for i, want := range []string{"a", "b", "c", "tail"} { + if got := agg.Members[i]; got.Model != want || got.Priority != i { + t.Fatalf("flat member %d = %+v, want %s at sequence %d", i, got, want, i) + } + } +} + func TestPipelineNormalizesRawMemberSpelling(t *testing.T) { doc := `{"version":1,"steps":[{"id":"m","kind":"member","provider":"Qoder","region":"GL","model":"qoder/model-a"},{"id":"c","kind":"branch","classifier":{"provider":"Qoder","model":"qoder/small"},"paths":[{"id":"p","label":"Plan","intent":"plan","steps":[{"id":"pm","kind":"member","provider":"WorkBuddy","model":"workbuddy/model-b"}]}]}]}` canonical, members, err := CollectPipeline("mine", doc, nil) @@ -165,3 +234,68 @@ func TestPipelineRejectsCycleDepthAndLogicalClassifier(t *testing.T) { t.Fatal("expected concrete classifier") } } + +func TestPipelineRegionSelectorsAgreeBetweenSaveAndCompile(t *testing.T) { + const raw = `{"steps":[{"id":"intent","kind":"branch", + "classifier":{"provider":"Qoder","model":"qoder/qoder-global/label"}, + "paths":[{"id":"cn","label":"China","intent":"cn","steps":[ + {"id":"member","kind":"member","provider":"workbuddy","model":"workbuddy-cn/upstream","account_ids":["cn-b","cn-a"]}]}], + "fallback":[{"id":"def","kind":"member","provider":"command","model":"command/org/upstream"}]}]}` + // A group sharing a provider name cannot turn a concrete classifier into + // a reference to the group (even if that group is disabled). + catalog := map[string]Aggregation{"qoder": {ID: "qoder"}} + canonical, members, err := CollectPipeline("team/review", raw, catalog) + if err != nil || len(members) != 3 || members[0].Region != "cn" || members[0].Model != "upstream" || members[2].Model != "org/upstream" { + t.Fatalf("stored model targets = %+v, %v", members, err) + } + for _, doc := range []string{raw, canonical} { + group := Aggregation{ID: "team/review", Document: doc} + got, _, path, err := CompilePipelineWithClassifier(group, catalog, "hi", nil, func(target ClassifierTarget) string { + if target.Key() != "qoder|global|label" { + t.Errorf("classifier target = %+v", target) + } + return "cn" + }) + if err != nil || path != "China" || len(got.Members) != 2 || got.Members[0] != members[0] || got.Members[1] != members[1] { + t.Fatalf("path = %q, targets = %+v, %v", path, got.Members, err) + } + if _, _, _, err := CompilePipeline(group, catalog, "hi", map[string]string{"qoder|global|label": "cn"}, map[string]bool{"command": true}); err == nil { + t.Fatal("filtered selected path fell through to a different branch") + } + } + + for _, conflict := range []string{ + strings.Replace(raw, `"model":"qoder/qoder-global/label"`, `"model":"qoder-cn/qoder-global/label"`, 1), + strings.Replace(raw, `"model":"workbuddy-cn/upstream"`, `"region":"global","model":"workbuddy-cn/upstream"`, 1), + } { + if _, _, err := CollectPipeline("team/review", conflict, catalog); err == nil || !strings.Contains(err.Error(), "conflicts") { + t.Fatalf("saved conflicting target: %v", err) + } + if _, _, _, err := CompilePipeline(Aggregation{ID: "team/review", Document: conflict}, catalog, "hi", map[string]string{"qoder|global|label": "cn"}, nil); err == nil || !strings.Contains(err.Error(), "conflicts") { + t.Fatalf("compiled conflicting target: %v", err) + } + } +} + +func TestPipelineConflictingDefaultsRejectNewWritesButKeepLegacyRoute(t *testing.T) { + const mixed = `{"steps":[{"id":"choose","kind":"branch","paths":[ + {"id":"old","label":"First","fallback":true,"steps":[{"kind":"member","provider":"qoder","model":"first"}]}], + "fallback":[{"kind":"member","provider":"qoder","model":"unreachable"}]}]}` + const repeated = `{"steps":[{"id":"choose","kind":"branch","paths":[ + {"id":"old","label":"First","fallback":true,"steps":[{"kind":"member","provider":"qoder","model":"first"}]}, + {"id":"second","label":"Second","fallback":true,"steps":[{"kind":"member","provider":"qoder","model":"unreachable"}]}]}]}` + for _, doc := range []string{mixed, repeated} { + if _, _, err := CollectPipeline("child", doc, nil); err == nil || !strings.Contains(err.Error(), "more than one fallback path") { + t.Fatalf("saved duplicate defaults: %v", err) + } + child := Aggregation{ID: "child", Document: doc, Enabled: true} + compiled, _, path, err := CompilePipeline(child, nil, "hi", nil, nil) + if err != nil || path != "First" || len(compiled.Members) != 1 || compiled.Members[0].Model != "first" { + t.Fatalf("legacy defaults changed: %q, %+v, %v", path, compiled.Members, err) + } + _, members, err := CollectPipeline("parent", `{"steps":[{"kind":"group","aggregation_id":"child"}]}`, map[string]Aggregation{"child": child}) + if err != nil || len(members) != 1 || members[0].Model != "first" { + t.Fatalf("legacy child leaked an unreachable default into parent: %+v, %v", members, err) + } + } +} diff --git a/internal/accounts/request_logs.go b/internal/accounts/request_logs.go index 3fd0d9100..d4fd3cb16 100644 --- a/internal/accounts/request_logs.go +++ b/internal/accounts/request_logs.go @@ -50,6 +50,15 @@ type RequestLog struct { ErrorCode string `json:"error_code,omitempty"` ErrorMessage string `json:"error_message,omitempty"` AttemptCount int `json:"attempt_count"` + // UpstreamTerminal records what the upstream sent (done/error/eof/none). + // DownstreamTerminal records whether the protocol terminal frame was written + // (done/error/none) and FlushState whether its flush succeeded. They are + // separate facts: an upstream [DONE] arrives before the relay writes anything. + UpstreamTerminal string `json:"upstream_terminal,omitempty"` + DownstreamTerminal string `json:"downstream_terminal,omitempty"` + FlushState string `json:"flush_state,omitempty"` + // RequestState is the final send fact of the last routed attempt. + RequestState string `json:"request_state,omitempty"` // DetailExpired marks a log whose detail rows and detail-only columns were // cleared by retention. The aggregate columns (tokens, credits, latency, // status, model) are still present, so usage totals stay exact; only the @@ -102,6 +111,25 @@ type RequestAttempt struct { PromptTokens *int `json:"prompt_tokens,omitempty"` CompletionTokens *int `json:"completion_tokens,omitempty"` UsageSource string `json:"usage_source,omitempty"` + + // Decision fields. They explain why the route did what it did instead of + // forcing an operator to reconstruct it from free-text error messages. + ErrorCode string `json:"error_code,omitempty"` + Model string `json:"model,omitempty"` + Phase string `json:"phase,omitempty"` + RequestSent bool `json:"request_sent,omitempty"` + CooldownScope string `json:"cooldown_scope,omitempty"` + StopReason string `json:"stop_reason,omitempty"` + InternalRetries int `json:"internal_retries,omitempty"` + // RequestState is the authoritative send fact: not_sent, maybe_sent, sent, + // or unknown. It distinguishes "dial failed" from "the request may be on + // the wire" so a retry cannot duplicate a request. + RequestState string `json:"request_state,omitempty"` + // Sequence orders attempts across classifier sub-calls and the main route; + // AttemptIndex alone restarts at zero for each route loop. + Sequence int64 `json:"sequence,omitempty"` + // AttemptKind separates a classifier probe from the routed chat attempt. + AttemptKind string `json:"attempt_kind,omitempty"` } type RequestLogFilter struct { @@ -141,6 +169,7 @@ type RequestStats struct { Accounts []RequestStatsNamed `json:"accounts"` Providers []RequestStatsNamed `json:"providers"` Series []RequestStatsPoint `json:"series"` + Quality RequestStatsQuality `json:"quality"` } type RequestStatsWindow struct { @@ -165,6 +194,22 @@ type RequestStatsLatency struct { P50Ms *int `json:"p50_ms,omitempty"` P95Ms *int `json:"p95_ms,omitempty"` TTFBAvgMs *int `json:"ttfb_avg_ms,omitempty"` + TTFTP50Ms *int `json:"ttft_p50_ms,omitempty"` + TTFTP95Ms *int `json:"ttft_p95_ms,omitempty"` +} + +// RequestStatsQuality is the availability / loss / throughput view derived +// from persisted terminal facts. Loss counts truncated, upstream-EOF, and +// delivery-lost outcomes; client cancellations are excluded. +type RequestStatsQuality struct { + Requests int `json:"requests"` + OK int `json:"ok"` + Errored int `json:"errored"` + Lost int `json:"lost"` + SuccessRate float64 `json:"success_rate"` + ErrorRate float64 `json:"error_rate"` + LossRate float64 `json:"loss_rate"` + AvgOutputTPS float64 `json:"avg_output_tps"` } type RequestStatsTokens struct { diff --git a/internal/executor/aggregation_e2e_test.go b/internal/executor/aggregation_e2e_test.go index 3b80f5515..dc9c413f3 100644 --- a/internal/executor/aggregation_e2e_test.go +++ b/internal/executor/aggregation_e2e_test.go @@ -45,7 +45,7 @@ func TestAggregateFailoverSettingsDriveAttempts(t *testing.T) { if err != nil { t.Fatalf("prepare: %v", err) } - loop := e.newRouteLoop(prepared.Context, "", "", prepared.Request) + loop := e.newRouteLoop(prepared.Route, prepared.Request.Model, nil) if loop.attempts != 1 { t.Fatalf("allow_fallbacks=false must cap attempts to 1, got %d", loop.attempts) } @@ -63,7 +63,7 @@ func TestAggregateFailoverSettingsDriveAttempts(t *testing.T) { if err != nil { t.Fatalf("prepare: %v", err) } - loop = e.newRouteLoop(prepared.Context, "", "", prepared.Request) + loop = e.newRouteLoop(prepared.Route, prepared.Request.Model, nil) if loop.attempts != 2 { t.Fatalf("max_attempts=2 must cap attempts to 2, got %d", loop.attempts) } @@ -95,23 +95,21 @@ func TestAggregatePrepareToRoute(t *testing.T) { if resolver.hit != 1 { t.Fatalf("resolver called %d times, want 1 (snapshot once)", resolver.hit) } - plan := aggregatePlanFrom(prepared.Context) + plan := prepared.Route.AggregatePlan if plan == nil || plan.ID != "my-model" { - t.Fatalf("plan not attached to context: %+v", plan) + t.Fatalf("plan not present in explicit route: %+v", plan) } // The loop must not pin a provider for an aggregated request and must route // only to members. - loop := e.newRouteLoop(prepared.Context, "", "", prepared.Request) - if loop.resolver == nil { - t.Fatal("route loop missing aggregate resolver") - } counts := map[string]int{} for i := 0; i < 10; i++ { - item, _, err := loop.pickNext(e, "my-model") + loop := e.newRouteLoop(prepared.Route, prepared.Request.Model, nil) + target, _, err := loop.pickNextReserved(e) if err != nil { t.Fatalf("pick: %v", err) } - counts[item.ID]++ + counts[target.item.ID]++ + e.releaseInFlight(prepared.RequestID, target.item.ID) } if counts["trae"] != 0 || counts["qoder"]+counts["workbuddy"] != 10 { t.Fatalf("unexpected aggregate routing: %v", counts) diff --git a/internal/executor/aggregation_plan.go b/internal/executor/aggregation_plan.go index bbb998f7c..55bb814e8 100644 --- a/internal/executor/aggregation_plan.go +++ b/internal/executor/aggregation_plan.go @@ -8,10 +8,8 @@ import ( ) // AggregatePlan is an immutable per-request snapshot of one logical model. -// It is resolved once in Prepare (before any Pool lock) and stored in the -// request context. Everything downstream treats it as read-only, so parallel -// requests never share mutable state and configuration updates cannot change -// the candidate set mid-flight. +// Prepare resolves it before taking the Pool lock and passes it in RouteInput. +// Routing treats the snapshot as read-only for the duration of the request. type AggregatePlan struct { ID string Strategy accounts.AggregationStrategy @@ -43,13 +41,18 @@ func NewAggregatePlan(agg accounts.Aggregation) *AggregatePlan { MaxAttempts: agg.MaxAttempts, ReasoningEffort: agg.ReasoningEffort, Members: agg.Members, - byProvider: make(map[string][]accounts.AggregationMember, len(agg.Members)), + byProvider: indexAggregateMembers(agg.Members), } - for _, member := range agg.Members { + return plan +} + +func indexAggregateMembers(members []accounts.AggregationMember) map[string][]accounts.AggregationMember { + index := make(map[string][]accounts.AggregationMember, len(members)) + for _, member := range members { key := aggregateMemberProvider(member.Provider) - plan.byProvider[key] = append(plan.byProvider[key], member) + index[key] = append(index[key], member) } - return plan + return index } // aggregateMemberProvider gives the same provider family for stored legacy @@ -81,16 +84,9 @@ func aggregatePlanFrom(ctx context.Context) *AggregatePlan { return plan } -// resolver returns a pure function that maps an Item to the concrete real -// model it should serve for this plan. The function: -// - reads only the immutable plan snapshot and the passed-in Item; -// - never calls Pool methods, the facade, DB, network, or channels; -// - is O(candidates for provider), typically O(1), with no allocation. -// -// It is safe to invoke while Pool.mu is held. If a member's region filter is -// set, only items in that region are considered; an empty region matches any. -// matchMember returns the member this item resolves to. Shared by resolver, -// priorityResolver and weightResolver so all three agree on the same member. +// matchMember is the single-model compatibility resolver. Request scheduling +// evaluates each concrete member independently; an account may serve more than +// one member and its first match need not be the one that is ready to dispatch. func (p *AggregatePlan) matchMember(item Item) (accounts.AggregationMember, bool) { if p == nil { return accounts.AggregationMember{}, false @@ -99,13 +95,7 @@ func (p *AggregatePlan) matchMember(item Item) (accounts.AggregationMember, bool region := NormalizeRegion(itemRegion(item)) var wildcard *accounts.AggregationMember for _, member := range candidates { - if member.AccountID != "" && member.AccountID != item.ID { - continue - } - if member.Region != "" && NormalizeRegion(member.Region) != region { - continue - } - if !itemHasModel(item, member.Model) { + if !aggregateMemberInScope(item.ID, region, member) || !itemHasModel(item, member.Model) { continue } // A deployment pinned to this exact account is more specific than a @@ -126,66 +116,32 @@ func (p *AggregatePlan) matchMember(item Item) (accounts.AggregationMember, bool return accounts.AggregationMember{}, false } +func aggregateMemberInScope(accountID, region string, member accounts.AggregationMember) bool { + return routeModel(member.Model) != "" && (member.AccountID == "" || member.AccountID == accountID) && + (member.Region == "" || NormalizeRegion(member.Region) == region) +} + // CanServeAccount reports whether this account can serve at least one member // of the logical model. Sticky routing uses it because the public model is a // virtual ID that is intentionally absent from every account catalog. func (p *AggregatePlan) CanServeAccount(item Item) bool { - _, ok := p.matchMember(item) - return ok -} - -// Priority returns the configured priority of the member this account serves. -func (p *AggregatePlan) Priority(item Item) (int, bool) { - member, ok := p.matchMember(item) - if !ok { - return 0, false - } - return member.Priority, true -} - -// PriorityTierCount counts distinct configured priority tiers. It is used to -// give each tier its own retry budget instead of spending the whole budget on -// sibling accounts of the first provider. -func (p *AggregatePlan) PriorityTierCount() int { if p == nil { - return 1 + return false } - seen := make(map[int]struct{}, len(p.Members)) if len(p.Seats) > 0 { - collectSeatPriorities(p.Seats, seen) - } else { - for _, member := range p.Members { - seen[member.Priority] = struct{}{} - } - } - if len(seen) == 0 { - if len(p.Seats) > 0 { - return len(p.Seats) - } - return 1 + return seatsCanServeAccount(p.Seats, item) } - return len(seen) -} - -// collectSeatPriorities mirrors noteTierFailure: a picked account is graded -// by the leaf member it matched, so a top-level group seat with several -// inner priorities has to count all of them. -func collectSeatPriorities(seats []accounts.RouteSeat, seen map[int]struct{}) { - for _, seat := range seats { - switch seat.Kind { - case "member": - seen[seat.Member.Priority] = struct{}{} - case "group": - if len(seat.GroupSeats) > 0 { - collectSeatPriorities(seat.GroupSeats, seen) - } - for _, member := range seat.GroupMembers { - seen[member.Priority] = struct{}{} - } + region := itemRegion(item) + for _, member := range p.byProvider[itemProvider(item)] { + if aggregateMemberInScope(item.ID, region, member) && itemCouldServeModel(item, member.Model) { + return true } } + return false } +// resolver maps one account to its historical default member for consumers +// that need a single model. It is not used to resolve a reserved target. func (p *AggregatePlan) resolver() func(Item) string { if p == nil || len(p.Members) == 0 { return nil diff --git a/internal/executor/aggregation_preview.go b/internal/executor/aggregation_preview.go new file mode 100644 index 000000000..7eabb2b45 --- /dev/null +++ b/internal/executor/aggregation_preview.go @@ -0,0 +1,63 @@ +package executor + +import ( + "context" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +// AggregatePreviewCandidate describes only the next candidate visible in the +// current pool snapshot. It intentionally omits the account ID and does not +// describe later attempts, API-key grants, request pins, or session affinity. +type AggregatePreviewCandidate struct { + ID string `json:"id"` + Model string `json:"model"` + Provider string `json:"provider"` + Region string `json:"region,omitempty"` + Status string `json:"status"` + Reason string `json:"reason,omitempty"` +} + +// CompileAggregationPreview uses the same lazy pipeline compiler and intent +// classifier as request preparation. The classifier is invoked only for branch +// steps reached while compiling the selected path. +func (e ChatExecutor) CompileAggregationPreview(ctx context.Context, agg accounts.Aggregation, catalog map[string]accounts.Aggregation, text string) (*AggregatePlan, string, error) { + classify := e.intentClassifier(ctx, text, RouteInput{}) + return CompileAggregatePreview(agg, catalog, text, classify) +} + +// CompileAggregatePreview is the shared pure pipeline compilation step. The +// callback may classify a branch target, and is called lazily only for reached +// branches by CompilePipelineWithClassifier. +func CompileAggregatePreview(agg accounts.Aggregation, catalog map[string]accounts.Aggregation, text string, classify func(accounts.ClassifierTarget) string) (*AggregatePlan, string, error) { + compiled, seats, path, err := accounts.CompilePipelineWithClassifier(agg, catalog, text, nil, classify) + if err != nil { + return nil, "", err + } + plan := NewAggregatePlan(compiled) + plan.Seats = seats + return plan, path, nil +} + +// PreviewAggregate returns the same immediate candidate as production aggregate +// routing without reserving a slot or committing any rotation cursor. A cooling +// member may be returned as a skipped retry hint; no candidate is returned when +// the current pool has no route it can identify. +func (p *Pool) PreviewAggregate(plan *AggregatePlan, q RouteQuery) (AggregatePreviewCandidate, bool) { + result := p.selectAggregate(plan, q, false) + if result.Item.ID == "" || result.Member.Model == "" { + return AggregatePreviewCandidate{}, false + } + attempt := AggregatePreviewCandidate{ + ID: result.Member.Provider + "/" + result.Member.Model, + Model: result.Member.Model, + Provider: result.Member.Provider, + Region: result.Member.Region, + Status: "candidate", + } + if !result.Available { + attempt.Status = "skipped" + attempt.Reason = "no ready account" + } + return attempt, true +} diff --git a/internal/executor/aggregation_preview_test.go b/internal/executor/aggregation_preview_test.go new file mode 100644 index 000000000..c064262f3 --- /dev/null +++ b/internal/executor/aggregation_preview_test.go @@ -0,0 +1,120 @@ +package executor + +import ( + "maps" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +func TestCompileAggregatePreviewClassifiesOnlyReachedBranches(t *testing.T) { + const outerDoc = `{"version":1,"steps":[ + {"id":"root","kind":"branch","classifier":{"provider":"qoder","model":"root-classifier"},"paths":[ + {"id":"chosen","label":"Chosen","steps":[ + {"id":"nested","kind":"group","aggregation_id":"inner"} + ]}, + {"id":"unused","label":"Unused","steps":[ + {"id":"unused-branch","kind":"branch","classifier":{"provider":"workbuddy","model":"unused-classifier"},"fallback":[ + {"id":"unused-member","kind":"member","provider":"workbuddy","model":"unused-model"} + ]} + ]} + ]} + ]}` + const innerDoc = `{"version":1,"steps":[ + {"id":"inner-branch","kind":"branch","classifier":{"provider":"qoder","model":"inner-classifier"},"paths":[ + {"id":"match","label":"Match","intent":"match","steps":[ + {"id":"selected-member","kind":"member","provider":"qoder","model":"selected-model"} + ]} + ],"fallback":[{"id":"inner-fallback","kind":"member","provider":"qoder","model":"fallback-model"}]} + ]}` + catalog := map[string]accounts.Aggregation{ + "inner": {ID: "inner", Enabled: true, Document: innerDoc}, + } + var visits []string + plan, path, err := CompileAggregatePreview( + accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationPriority, Document: outerDoc}, + catalog, "request", func(target accounts.ClassifierTarget) string { + visits = append(visits, target.Key()) + if target.Model == "root-classifier" { + return "Chosen" + } + if target.Model == "inner-classifier" { + return "Match" + } + return "" + }, + ) + if err != nil { + t.Fatal(err) + } + if path != "Chosen" { + t.Fatalf("path = %q, want Chosen", path) + } + if len(visits) != 2 || visits[0] != "qoder||root-classifier" || visits[1] != "qoder||inner-classifier" { + t.Fatalf("classifier visits = %v, want only reached root and nested branches", visits) + } + if plan == nil || len(plan.Members) != 1 || plan.Members[0].Model != "selected-model" || len(plan.Seats) != 1 || plan.Seats[0].Kind != "group" { + t.Fatalf("compiled plan = %+v, want selected nested member path", plan) + } +} + +func TestPreviewAggregateUsesCurrentNestedFEFOCandidateWithoutMutation(t *testing.T) { + pool := NewPool(nil, nil) + now := time.Now() + for id, expiry := range map[string]time.Duration{"late": 72 * time.Hour, "early": 24 * time.Hour} { + pool.Upsert(Item{ + ID: id, Provider: "qoder", Models: []string{id}, + Quota: &accounts.QuotaSnapshot{Packages: []accounts.QuotaPackage{{ + Scope: accounts.QuotaPackageScopeAccountFEFO, Unit: "credits", Remain: 1, EndsAt: now.Add(expiry).Unix(), + }}}, + }) + } + pool.Upsert(Item{ID: "outer-fallback", Provider: "workbuddy", Models: []string{"outer-fallback"}}) + pool.lastPicked = make(map[string]string) + pool.lastPicked["sentinel"] = "unchanged" + plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationPriority}) + plan.Seats = []accounts.RouteSeat{ + { + ID: "nested-fefo", Kind: "group", Priority: 0, GroupStrategy: accounts.AggregationFEFOStrategy, + GroupMembers: []accounts.AggregationMember{ + {Provider: "qoder", Model: "early", Priority: 0}, + {Provider: "qoder", Model: "late", Priority: 1}, + }, + }, + {ID: "fallback", Kind: "member", Priority: 1, Member: accounts.AggregationMember{Provider: "workbuddy", Model: "outer-fallback"}}, + } + q := RouteQuery{PublicModel: plan.ID} + beforePicked := maps.Clone(pool.lastPicked) + beforeEarly, _ := pool.ByID("early") + beforeLate, _ := pool.ByID("late") + expected := pool.selectAggregate(plan, q, false) + candidate, ok := pool.PreviewAggregate(plan, q) + if !ok || candidate.Status != "candidate" || candidate.ID != "qoder/early" || candidate.Model != expected.Member.Model || !expected.Available { + t.Fatalf("candidate=%+v ok=%v expected=%+v", candidate, ok, expected) + } + if expected.Member.Model != "early" { + t.Fatalf("FEFO candidate = %+v, want early", expected) + } + afterEarly, _ := pool.ByID("early") + afterLate, _ := pool.ByID("late") + if beforeEarly.InFlight != afterEarly.InFlight || beforeLate.InFlight != afterLate.InFlight || !maps.Equal(beforePicked, pool.lastPicked) { + t.Fatalf("preview mutated slots/cursors: early %d→%d late %d→%d picked=%v", beforeEarly.InFlight, afterEarly.InFlight, beforeLate.InFlight, afterLate.InFlight, pool.lastPicked) + } +} + +func TestPreviewAggregateReturnsCoolingHintWithoutReservation(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "cooling", Provider: "qoder", Models: []string{"model"}}) + pool.MarkClassified("cooling", Classified{Kind: KindRateLimit, Model: "model", Cooldown: time.Minute}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "model"}}}) + before, _ := pool.ByID("cooling") + candidate, ok := pool.PreviewAggregate(plan, RouteQuery{PublicModel: plan.ID}) + after, _ := pool.ByID("cooling") + if !ok || candidate.Status != "skipped" || candidate.Reason != "no ready account" || candidate.Model != "model" { + t.Fatalf("cooling hint = %+v ok=%v", candidate, ok) + } + if before.InFlight != after.InFlight { + t.Fatalf("cooling preview changed in-flight count: %d → %d", before.InFlight, after.InFlight) + } +} diff --git a/internal/executor/aggregation_priority.go b/internal/executor/aggregation_priority.go new file mode 100644 index 000000000..74544c706 --- /dev/null +++ b/internal/executor/aggregation_priority.go @@ -0,0 +1,410 @@ +package executor + +import ( + "math" + "strconv" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +// aggregateRouteResult keeps the selected member and miss evidence from the +// same pool snapshot. A cooling hint has an item and a member but no slot. +type aggregateRouteResult struct { + Item Item + Member accounts.AggregationMember + Available bool + FEFO bool // the selected path uses FEFO at one or more levels + RetryAfter time.Duration + HasRoute bool + Saturated bool + QuotaBlocked bool + Scoped bool +} + +// ReserveAggregate selects the best concrete member/account and reserves one +// account slot atomically. When only cooling candidates match, found is true +// and reserved is false; the returned member describes the retry hint. +func (p *Pool) ReserveAggregate(plan *AggregatePlan, q RouteQuery) (item Item, member accounts.AggregationMember, found, reserved bool) { + result := p.selectAggregate(plan, q, true) + return result.Item, result.Member, result.Available || result.RetryAfter > 0, result.Available +} + +// HasAggregateRoute probes whether the requested route has a capable member +// without consulting cooldowns, quota, the capacity limit, or rotation state. +func (p *Pool) HasAggregateRoute(plan *AggregatePlan, q RouteQuery) bool { + if p == nil || plan == nil { + return false + } + root := buildAggregateNode(plan) + scope := aggregateScope(q) + p.mu.Lock() + defer p.mu.Unlock() + for _, item := range p.items { + if routeReadyAndScoped(item, scope) && root.hasMember(item, q.ExcludedModels) { + return true + } + } + return false +} + +// selectAggregate examines the entire strategy tree, adjusts in-flight count, +// and commits the selected path's cursors under one lock. Preview does not +// initialize rotation state or advance any cursor. +func (p *Pool) selectAggregate(plan *AggregatePlan, q RouteQuery, reserve bool) aggregateRouteResult { + if p == nil || plan == nil { + return aggregateRouteResult{} + } + root := buildAggregateNode(plan) + p.mu.Lock() + defer p.mu.Unlock() + + now := time.Now() + q.StrategyOverride = string(root.strategy) + q, _ = p.configureRouteLocked(q, now) + scan := aggregateScan{pool: p, query: q, now: now} + scope := aggregateScope(q) + var scoped []int + var preferred []int + for i, item := range p.items { + if routeReadyAndScoped(item, scope) { + scoped = append(scoped, i) + if q.PreferAccount != "" && q.PreferAccount == item.ID { + preferred = append(preferred, i) + } + } + } + if len(scoped) == 0 { + return aggregateRouteResult{} + } + + key := rotationKey(q) + "|aggregate|" + strconv.Quote(plan.ID) + if len(preferred) > 0 { + choice := scan.choose(root, preferred, key, false) + if choice != nil { + // Like an ordinary account pin, taking a preferred slot does not + // move strategy cursors used by non-preferred traffic. + return scan.finish(choice, reserve, false) + } + } + choice := scan.choose(root, scoped, key, false) + return scan.finish(choice, reserve, true) +} + +// ExcludedModels is tested with the resolved member model, never with the +// virtual name. Other scoping (provider, region, grants, account exclusion, +// protocol) is common to all leaves and checked once per pool item. +func aggregateScope(q RouteQuery) RouteQuery { + q.ExcludedModels = nil + return q +} + +type aggregateCandidate struct { + index int + member accounts.AggregationMember + key string + expiry int64 + fefo bool +} + +type aggregateChoice struct { + target aggregateCandidate + cursors []aggregateCursor +} + +type aggregateCursor struct { + key string + value string +} + +type aggregateScan struct { + pool *Pool + query RouteQuery + now time.Time + result aggregateRouteResult + cooling aggregateCandidate + resume time.Time +} + +func (s *aggregateScan) finish(choice *aggregateChoice, reserve, rotate bool) aggregateRouteResult { + result := s.result + result.Scoped = true + if choice != nil { + item := &s.pool.items[choice.target.index] + if reserve { + acquireItemLocked(item, s.now) + if rotate { + for _, cursor := range choice.cursors { + s.pool.ensureRotationKey(cursor.key) + s.pool.lastPicked[cursor.key] = cursor.value + } + } + } + result.Item, result.Member, result.Available = item.clone(), choice.target.member, true + result.FEFO = choice.target.fefo + } else if !s.resume.IsZero() { + result.Item = s.pool.items[s.cooling.index].clone() + result.Member = s.cooling.member + result.RetryAfter = s.resume.Sub(s.now) + } + return result +} + +func (n *aggregateNode) hasMember(item Item, excluded map[routeModelKey]struct{}) bool { + for _, seat := range n.seats { + if seat.node.hasMember(item, excluded) { + return true + } + } + region := itemRegion(item) + for _, member := range n.members[itemProvider(item)] { + if _, ok := n.memberKey(item, region, member, excluded); ok { + return true + } + } + return false +} + +// An account-specific member overrides a provider-wide member only for the +// same concrete account/model, not for every other model the account serves. +// Its configured priority and weight still win even if the wildcard comes +// first. Both sides honor the item's alias when identifying the real model. +func (n *aggregateNode) memberKey(item Item, region string, member accounts.AggregationMember, excluded map[routeModelKey]struct{}) (routeModelKey, bool) { + if !aggregateMemberInScope(item.ID, region, member) || !itemCouldServeModel(item, member.Model) { + return routeModelKey{}, false + } + key := accountRouteModelKey(item, member.Model) + if _, skip := excluded[key]; skip { + return routeModelKey{}, false + } + if member.AccountID == "" { + for _, pin := range n.pins[item.ID] { + if aggregateMemberProvider(pin.Provider) == aggregateMemberProvider(member.Provider) && + aggregateMemberInScope(item.ID, region, pin) && accountRouteModelKey(item, pin.Model) == key && + itemCouldServeModel(item, pin.Model) { + return routeModelKey{}, false + } + } + } + return key, true +} + +func (s *aggregateScan) choose(node *aggregateNode, scoped []int, key string, fefo bool) *aggregateChoice { + fefo = fefo || node.strategy == accounts.AggregationFEFOStrategy + if len(node.seats) > 0 { + return s.chooseSeat(node, scoped, key, fefo) + } + var available []aggregateCandidate + q := s.query + q.ModelResolver = nil + q.fefoNow = time.Time{} + if fefo { + q.fefoNow = s.now + } + for _, i := range scoped { + item := s.pool.items[i] + region := itemRegion(item) + for _, member := range node.members[itemProvider(item)] { + target, ok := node.memberKey(item, region, member, q.ExcludedModels) + if !ok { + continue + } + s.result.HasRoute = true + q.PublicModel = member.Model + if !fefo { + // Price the actual model, not the configured alias spelling. + // The FEFO gate already resolves aliases, so passing the + // target there could follow a second alias by accident. + q.PublicModel = AccountModelID(item, member.Model) + } + if routeQuotaExceeded(item, q) { + s.result.QuotaBlocked = true + continue + } + q.PublicModel = member.Model // resumeAt resolves the cooldown key itself + candidate := aggregateCandidate{index: i, member: member, key: item.ID + "\x00" + target.Model, fefo: fefo} + if until := resumeAt(item, q); until.After(s.now) { + if s.resume.IsZero() || until.Before(s.resume) { + s.cooling, s.resume = candidate, until + } + continue + } + if itemSaturated(item) { + s.result.Saturated = true + continue + } + if fefo { + candidate.expiry, _ = fefoExpiry(item, member.Model, s.now) + } + available = append(available, candidate) + } + } + if len(available) == 0 { + return nil + } + return s.chooseMember(node.strategy, available, key) +} + +func (s *aggregateScan) chooseMember(strategy accounts.AggregationStrategy, available []aggregateCandidate, key string) *aggregateChoice { + switch strategy { + case accounts.AggregationPriority: + tier := available[0].member.Priority + for _, candidate := range available[1:] { + if candidate.member.Priority < tier { + tier = candidate.member.Priority + } + } + available = filterAggregateMembers(available, func(c aggregateCandidate) bool { return c.member.Priority == tier }) + key += "/priority/" + strconv.Itoa(tier) + case accounts.AggregationFillFirst: + best := available[0] + for _, candidate := range available[1:] { + if candidate.member.Weight > best.member.Weight || + (candidate.member.Weight == best.member.Weight && candidate.key < best.key) { + best = candidate + } + } + return &aggregateChoice{target: best} + case accounts.AggregationFEFOStrategy: + // As in the ordinary pool, compare billing days within each provider + // but let different providers share the route. + earliest := make(map[string]int64) + for _, candidate := range available { + if candidate.expiry == 0 { + continue + } + family := itemProvider(s.pool.items[candidate.index]) + if day := fefoCreditDay(candidate.expiry); earliest[family] == 0 || day < earliest[family] { + earliest[family] = day + } + } + available = filterAggregateMembers(available, func(c aggregateCandidate) bool { + day := earliest[itemProvider(s.pool.items[c.index])] + return day == 0 || (c.expiry > 0 && fefoCreditDay(c.expiry) == day) + }) + case accounts.AggregationLeastQuotaFirst, accounts.AggregationMostQuotaFirst: + var best float64 + var known bool + most := strategy == accounts.AggregationMostQuotaFirst + for _, candidate := range available { + if ratio, ok := s.quotaRatio(candidate); ok && (!known || betterRatio(ratio, best, most)) { + best, known = ratio, true + } + } + if known { + available = filterAggregateMembers(available, func(c aggregateCandidate) bool { + ratio, ok := s.quotaRatio(c) + return ok && ratio == best + }) + } + } + + // The cursor is per tier. A temporarily unavailable member does not + // reseat the rotation: resume from the lexical successor of its key. + last := s.pool.lastPicked[key] + first := available[0] + var next aggregateCandidate + for _, candidate := range available { + if candidate.key < first.key { + first = candidate + } + if candidate.key > last && (next.key == "" || candidate.key < next.key) { + next = candidate + } + } + if next.key == "" { + next = first + } + return &aggregateChoice{target: next, cursors: []aggregateCursor{{key: key, value: next.key}}} +} + +func betterRatio(a, b float64, most bool) bool { + if most { + return a > b + } + return a < b +} + +func (s *aggregateScan) quotaRatio(candidate aggregateCandidate) (float64, bool) { + ratio, known := quotaRemainingRatio(s.pool.items[candidate.index]) + return ratio, known && !math.IsNaN(ratio) +} + +func filterAggregateMembers(candidates []aggregateCandidate, keep func(aggregateCandidate) bool) []aggregateCandidate { + out := candidates[:0] + for _, c := range candidates { + if keep(c) { + out = append(out, c) + } + } + return out +} + +func (s *aggregateScan) chooseSeat(node *aggregateNode, scoped []int, key string, fefo bool) *aggregateChoice { + var best *aggregateChoice + bestIndex := -1 + cursorKey := key + "/seats" + for i, seat := range node.seats { + child := s.choose(seat.node, scoped, key+"/"+strconv.Quote(seat.key), fefo) + if child == nil { + continue + } + if best == nil || s.betterSeat(node, cursorKey, i, child.target, bestIndex, best.target) { + bestIndex, best = i, child + } + } + if best != nil { + seat := node.seats[bestIndex] + switch node.strategy { + case accounts.AggregationPriority: + cursorKey += "/priority/" + strconv.Itoa(seat.seat.Priority) + fallthrough + case accounts.AggregationRoundRobin: + best.cursors = append(best.cursors, aggregateCursor{key: cursorKey, value: seat.key}) + } + } + return best +} + +func (s *aggregateScan) betterSeat(node *aggregateNode, cursorKey string, i int, left aggregateCandidate, j int, right aggregateCandidate) bool { + a, b := node.seats[i].seat, node.seats[j].seat + switch node.strategy { + case accounts.AggregationFillFirst: + if a.Weight != b.Weight { + return a.Weight > b.Weight + } + return a.ID < b.ID + case accounts.AggregationLeastQuotaFirst, accounts.AggregationMostQuotaFirst: + // Compare the account the child would dispatch, not some other + // account in the child whose quota looks preferable. + l, lOK := s.quotaRatio(left) + r, rOK := s.quotaRatio(right) + if lOK != rOK { + return lOK + } + if lOK && l != r { + return betterRatio(l, r, node.strategy == accounts.AggregationMostQuotaFirst) + } + case accounts.AggregationFEFOStrategy: + if left.expiry != right.expiry { + return left.expiry > 0 && (right.expiry == 0 || left.expiry < right.expiry) + } + case accounts.AggregationPriority: + if a.Priority != b.Priority { + return a.Priority < b.Priority + } + cursorKey += "/priority/" + strconv.Itoa(a.Priority) + fallthrough + case accounts.AggregationRoundRobin: + last := s.pool.lastPicked[cursorKey] + for k, seat := range node.seats { + if seat.key == last { + // Configured order remains stable even when the last selected + // seat has no ready account on this request. + return (i-k-1+len(node.seats))%len(node.seats) < (j-k-1+len(node.seats))%len(node.seats) + } + } + return i < j + } + return a.Priority < b.Priority +} diff --git a/internal/executor/aggregation_priority_test.go b/internal/executor/aggregation_priority_test.go new file mode 100644 index 000000000..d176f93f3 --- /dev/null +++ b/internal/executor/aggregation_priority_test.go @@ -0,0 +1,195 @@ +package executor + +import ( + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +func TestAggregateFlatPriorityRotatesOnlyWithinAvailableTier(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "a-top", Provider: "qoder", Models: []string{"top"}}) + pool.Upsert(Item{ID: "b-top", Provider: "qoder", Models: []string{"top"}}) + pool.Upsert(Item{ID: "0-lower", Provider: "qoder", Models: []string{"lower"}}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "top", Priority: 0}, + {Provider: "qoder", Model: "lower", Priority: 1}, + }}) + q := RouteQuery{PublicModel: "logical"} + assertAccount := func(want string) { + t.Helper() + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != want { + t.Fatalf("pick = %q, want %q", item.ID, want) + } + } + for _, want := range []string{"a-top", "b-top", "a-top", "b-top"} { + assertAccount(want) + } + for _, id := range []string{"a-top", "b-top"} { + pool.MarkClassified(id, Classified{Kind: KindRateLimit, Model: "top", Cooldown: time.Minute}) + } + assertAccount("0-lower") + for _, id := range []string{"a-top", "b-top"} { + pool.MarkOK(id, "top") + } + assertAccount("a-top") +} + +func TestAggregateFlatSelectsSecondModelOnSameAccount(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "shared", Provider: "qoder", Models: []string{"model-a", "model-b"}}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "model-a", Priority: 0}, + {Provider: "qoder", Model: "model-b", Priority: 1}, + }}) + q := RouteQuery{PublicModel: "logical"} + a, memberA := reserveAggregateTest(t, pool, plan, q) + if memberA.Model != "model-a" { + t.Fatalf("first pick = %+v, want model-a", memberA) + } + q.ExcludedModels = map[routeModelKey]struct{}{accountRouteModelKey(a, memberA.Model): {}} + b, memberB := reserveAggregateTest(t, pool, plan, q) + if b.ID != a.ID || memberB.Model != "model-b" { + t.Fatalf("after excluding model-a pick = %s/%s, want %s/model-b", b.ID, memberB.Model, a.ID) + } + q.ExcludedModels = nil + pool.MarkClassified(a.ID, Classified{Kind: KindRateLimit, Model: "model-a", Cooldown: 10 * time.Minute}) + b, memberB = reserveAggregateTest(t, pool, plan, q) + if b.ID != a.ID || memberB.Model != "model-b" { + t.Fatalf("with model-a cooling pick = %s/%s, want %s/model-b", b.ID, memberB.Model, a.ID) + } + pool.MarkClassified(b.ID, Classified{Kind: KindRateLimit, Model: "model-b", Cooldown: time.Minute}) + peek := pool.selectAggregate(plan, q, true) + if peek.Available || peek.Item.ID != a.ID || peek.Member.Model != "model-b" || peek.RetryAfter <= 0 || peek.RetryAfter > time.Minute || peek.Item.InFlight != 0 { + t.Fatalf("cooling hint = %+v, want model-b's earlier release and no slot", peek) + } + if !pool.HasAggregateRoute(plan, q) { + t.Fatal("cooldowns must not hide aggregate capability") + } +} + +func TestAggregateAccountSpecificMemberRetainsPriorityForAliasTarget(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "a", Provider: "qoder", Models: []string{"model-a"}, ModelAliases: map[string]string{"alias-a": "model-a"}}) + pool.Upsert(Item{ID: "b", Provider: "qoder", Models: []string{"model-b"}}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "alias-a", Priority: 0, Weight: 100}, + {Provider: "qoder", Model: "model-b", Priority: 1, Weight: 100}, + {Provider: "qoder", Model: "model-a", AccountID: "a", Priority: 2, Weight: 400}, + }}) + q := RouteQuery{PublicModel: "logical"} + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "b" { + t.Fatalf("pick = %q, want b before a's account-specific tier", item.ID) + } + q.ExcludedModels = map[routeModelKey]struct{}{{AccountID: "b", Model: "model-b"}: {}} + item, member := reserveAggregateTest(t, pool, plan, q) + if item.ID != "a" || member.Model != "model-a" || member.Priority != 2 || member.Weight != 400 { + t.Fatalf("selected = %s %+v, want account-specific member", item.ID, member) + } + q.ExcludedModels[accountRouteModelKey(item, "alias-a")] = struct{}{} + if pool.HasAggregateRoute(plan, q) { + t.Fatal("an alternate spelling must not reintroduce the already tried account/model") + } +} + +func TestAggregateFlatRoundRobinCountsAliasTargetOncePerAccount(t *testing.T) { + pool := NewPool(nil, nil) + aliases := map[string]string{"alias": "model-a", "alternate": "model-a"} + pool.Upsert(Item{ID: "a", Provider: "qoder", Models: []string{"model-a", "model-b"}, ModelAliases: aliases}) + pool.Upsert(Item{ID: "b", Provider: "qoder", Models: []string{"model-a"}, ModelAliases: aliases}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationRoundRobin, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "alias"}, + {Provider: "qoder", Model: "alternate"}, + {Provider: "qoder", Model: "model-a", AccountID: "a"}, + {Provider: "qoder", Model: "model-b", AccountID: "a"}, + }}) + q := RouteQuery{PublicModel: plan.ID} + for i, want := range []string{"a/model-a", "a/model-b", "b/alias", "a/model-a", "a/model-b", "b/alias"} { + item, member := reserveAggregateTest(t, pool, plan, q) + if got := item.ID + "/" + member.Model; got != want { + t.Fatalf("pick %d = %q, want %q", i, got, want) + } + } + a, _ := pool.ByID("a") + b, _ := pool.ByID("b") + q.ExcludedModels = map[routeModelKey]struct{}{accountRouteModelKey(a, "alias"): {}, accountRouteModelKey(b, "alternate"): {}} + item, member := reserveAggregateTest(t, pool, plan, q) + if item.ID != "a" || member.Model != "model-b" { + t.Fatalf("with model-a excluded for both accounts, picked %s/%s, want a/model-b", item.ID, member.Model) + } +} + +func TestAggregatePriorityBudgetDoesNotSkipRemainingTierMembers(t *testing.T) { + pool := NewPool(nil, nil) + for _, id := range []string{"a-top", "b-top", "c-top"} { + pool.Upsert(Item{ID: id, Provider: "qoder", Region: "global", Models: []string{"top"}}) + } + pool.Upsert(Item{ID: "lower", Provider: "qoder", Region: "global", Models: []string{"lower"}}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "top", Priority: 0}, + {Provider: "qoder", Model: "lower", Priority: 1}, + }}) + ex := NewChatExecutor(pool, "") + loop := ex.newRouteLoop(RouteInput{AggregatePlan: plan, PublicModel: "logical"}, "logical", nil) + for i, want := range []string{"a-top", "b-top"} { + target, attempt, err := loop.pickNextReserved(ex) + if err != nil { + t.Fatal(err) + } + ex.releaseInFlight("", target.item.ID) + if attempt != i || target.item.ID != want || target.memberModel != "top" { + t.Fatalf("attempt %d = %s/%s (index %d), want %s/top", i, target.item.ID, target.memberModel, attempt, want) + } + if retry := loop.failover(ex, target, target.item.ID, Classified{Failover: true}, nil); retry != (i == 0) { + t.Fatalf("attempt %d retry=%t, cap must remain 2 across all tiers", i, retry) + } + } + if item, _ := reserveAggregateTest(t, pool, plan, RouteQuery{PublicModel: "logical"}); item.ID != "c-top" { + t.Fatalf("next request picks %q, want untried c-top in the best tier", item.ID) + } +} + +func TestAggregateSharedAccountCapacityIsAtomicAcrossMembers(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "shared", Provider: "qoder", Models: []string{"a", "b"}, MaxInFlight: 1}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationRoundRobin}) + for _, model := range []string{"a", "b"} { + plan.Seats = append(plan.Seats, accounts.RouteSeat{ID: model, Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: model}}) + } + q := RouteQuery{PublicModel: "logical"} + const n = 16 + results := make(chan aggregateRouteResult, n) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + results <- pool.selectAggregate(plan, q, true) + }() + } + close(start) + wg.Wait() + close(results) + winners := 0 + for result := range results { + if result.Available { + if result.Member.Model != "a" { + t.Fatalf("winning initial model = %q, want a", result.Member.Model) + } + winners++ + } else if !result.Saturated { + t.Fatalf("losing reservation should report capacity, got %+v", result) + } + } + if item, _ := pool.ByID("shared"); winners != 1 || item.InFlight != 1 { + t.Fatalf("winners=%d, account in-flight=%d; want one atomic reservation", winners, item.InFlight) + } + pool.Release("shared") + if _, member := reserveAggregateTest(t, pool, plan, q); member.Model != "b" { + t.Fatalf("failed reservations moved the cursor: pick = %q, want b", member.Model) + } +} diff --git a/internal/executor/aggregation_route_contract_test.go b/internal/executor/aggregation_route_contract_test.go new file mode 100644 index 000000000..8e7850859 --- /dev/null +++ b/internal/executor/aggregation_route_contract_test.go @@ -0,0 +1,98 @@ +package executor + +import ( + "errors" + "io" + "net/http" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func TestPreparedAggregateStreamRespectsExplicitNoFailover(t *testing.T) { + for _, tc := range []struct { + name, event, payload string + retryAfter time.Duration + }{ + {"worker-event", "error", `{"error":{"status":429,"message":"busy","code":"limited","failover":false}}`, time.Minute}, + {"nested-envelope", "", `{"statusCode":429,"retry_after":95,"failover":false,"body":{"error":{"message":"busy","code":"limited"}}}`, 95 * time.Second}, + } { + t.Run(tc.name, func(t *testing.T) { + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: "primary", Provider: "qoder", Region: "cn", Models: []string{"primary-model"}}, func(w http.ResponseWriter, _ routeRegressionHit) { + w.Header().Set("Content-Type", "text/event-stream") + nl := string(rune(10)) + _, _ = io.WriteString(w, ": warming up"+nl+nl+"data:"+nl+nl) + if tc.event != "" { + _, _ = io.WriteString(w, "event: "+tc.event+nl) + } + _, _ = io.WriteString(w, "data: "+tc.payload+nl+nl) + }) + wire.add(t, pool, Item{ID: "backup", Provider: "workbuddy", Region: "cn", Models: []string{"backup-model"}}, nil) + ex := NewChatExecutor(pool, "") + resolver := &aggResolverStub{agg: accounts.Aggregation{ID: "no-switch", Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "qoder", Region: "cn", Model: "primary-model", Priority: 0}, + {Provider: "workbuddy", Region: "cn", Model: "backup-model", Priority: 1}, + }}} + p := routeRegressionPrepare(t, ex, PrepareInput{Request: translate.ChatRequest{Model: "no-switch", Stream: true}, Aggregations: resolver}) + _, attempts, err := routeRegressionExecute(t, ex, p) + got := ClassifyError(err) + if err == nil || attempts != 1 || got.Status != 429 || got.Code != "limited" || got.Failover || got.RetryAfter != tc.retryAfter { + t.Fatalf("attempts=%d failure=%+v err=%v", attempts, got, err) + } + wire.require(t, routeRegressionDispatchTo("primary", "primary-model", true)) + for _, id := range []string{"primary", "backup"} { + if item, _ := pool.ByID(id); item.InFlight != 0 { + t.Errorf("slot leaked for %s: %d", id, item.InFlight) + } + } + }) + } +} + +func TestPreparedAggregationKeyDoesNotRouteAliasToSameNamedRawModel(t *testing.T) { + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: "a-raw", Provider: "qoder", Region: "cn", Models: []string{"friendly"}}, nil) + wire.add(t, pool, Item{ID: "b-global-alias", Provider: "qoder", Region: "global", Models: []string{"real"}, ModelAliases: map[string]string{"friendly": "real"}}, nil) + wire.add(t, pool, Item{ID: "z-granted-alias", Provider: "qoder", Region: "cn", Models: []string{"real"}, ModelAliases: map[string]string{"friendly": "real"}}, nil) + ex := NewChatExecutor(pool, "") + identity := auth.KeyIdentity(accounts.APIKey{ID: "agg-key", Enabled: true, ModelAggregation: true, Providers: []string{"qoder:cn"}}) + p := routeRegressionPrepare(t, ex, PrepareInput{Request: translate.ChatRequest{Model: "friendly"}, Identity: identity, ModelAggregation: true, PreferAccount: "a-raw"}) + if _, attempts, err := routeRegressionExecute(t, ex, p); err != nil || attempts != 1 { + t.Fatalf("attempts=%d err=%v", attempts, err) + } + wire.require(t, routeRegressionDispatchTo("z-granted-alias", "real", false)) +} + +func TestPreparedAggregationKeyDispatchesNamespacedGroupOnlyInGrantedRegion(t *testing.T) { + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: "global", Provider: "qoder", Region: "global", Models: []string{"global-model"}}, nil) + wire.add(t, pool, Item{ID: "cn", Provider: "qoder", Region: "cn", Models: []string{"cn-model", "team/not-a-group"}}, nil) + ex := NewChatExecutor(pool, "") + resolver := &aggResolverStub{agg: accounts.Aggregation{ID: "team/review", Enabled: true, Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Region: "global", Model: "global-model", Priority: 0}, + {Provider: "qoder", Region: "cn", Model: "cn-model", Priority: 1}, + }}} + identity := auth.KeyIdentity(accounts.APIKey{ID: "agg-key", Enabled: true, ModelAggregation: true, Providers: []string{"qoder:cn"}}) + in := PrepareInput{Context: t.Context(), Request: translate.ChatRequest{Model: "team/review"}, Identity: identity, ModelAggregation: true, Aggregations: resolver} + p, err := ex.Prepare(in) + if err != nil { + t.Fatal(err) + } + if _, attempts, err := routeRegressionExecute(t, ex, p); err != nil || attempts != 1 { + t.Fatalf("attempts=%d err=%v", attempts, err) + } + in.Request.Model = "team/not-a-group" + _, err = ex.Prepare(in) + var rejected *PrepareError + if !errors.As(err, &rejected) || rejected.Code != "model_not_aggregated" { + t.Fatalf("unexpected result for non-group: %v", err) + } + wire.require(t, routeRegressionDispatchTo("cn", "cn-model", false)) +} diff --git a/internal/executor/aggregation_seats.go b/internal/executor/aggregation_seats.go index 274c8a8f4..b8f5ddf70 100644 --- a/internal/executor/aggregation_seats.go +++ b/internal/executor/aggregation_seats.go @@ -1,246 +1,144 @@ package executor import ( - "errors" "sort" "strconv" "strings" - "time" "github.com/caigee-cmd/cli2api/internal/accounts" ) -func (e ChatExecutor) pickSeats(requestID, prefer, providerFilter, regionFilter, publicModel string, allowed []string, excluded map[string]struct{}, eligible func(Item) bool, plan *AggregatePlan) (Item, error) { - order := e.orderedSeats(plan, publicModel, allowed, excluded, eligible, len(excluded) == 0) - var first error - for _, seat := range order { - child := planForSeat(plan, seat) - item, err := e.pick(requestID, prefer, providerFilter, regionFilter, publicModel, allowed, excluded, eligible, child) - if err == nil { - return item, nil - } - if first == nil { - first = err - } - if !seatMiss(err) { - return Item{}, err - } - } - if first != nil { - return Item{}, first - } - return Item{}, noAccountsError("no accounts available") +// aggregateNode is the query tree evaluated against one pool state. A flat +// node evaluates concrete members; an outer node orders seats, with each +// group seat retaining its own child strategy. +type aggregateNode struct { + strategy accounts.AggregationStrategy + members map[string][]accounts.AggregationMember + pins map[string][]accounts.AggregationMember + seats []aggregateSeat } -func (e ChatExecutor) orderedSeats(plan *AggregatePlan, publicModel string, allowed []string, excluded map[string]struct{}, eligible func(Item) bool, advance bool) []accounts.RouteSeat { - seats := append([]accounts.RouteSeat(nil), plan.Seats...) - switch plan.Strategy { - case accounts.AggregationFillFirst: - sort.SliceStable(seats, func(i, j int) bool { - if seats[i].Weight != seats[j].Weight { - return seats[i].Weight > seats[j].Weight - } - return seats[i].ID < seats[j].ID - }) - case accounts.AggregationLeastQuotaFirst, accounts.AggregationMostQuotaFirst: - ready := e.readyFor(plan, publicModel, allowed, excluded, eligible) - most := plan.Strategy == accounts.AggregationMostQuotaFirst - sort.SliceStable(seats, func(i, j int) bool { - left, leftOK := seatRatio(seats[i], ready) - right, rightOK := seatRatio(seats[j], ready) - if leftOK != rightOK { - return leftOK - } - if leftOK && left != right { - if most { - return left > right - } - return left < right - } - return seats[i].Priority < seats[j].Priority - }) - case accounts.AggregationFEFOStrategy: - ready := e.readyFor(plan, publicModel, allowed, excluded, eligible) - now := time.Now() - sort.SliceStable(seats, func(i, j int) bool { - left, leftOK := seatExpiry(seats[i], ready, now) - right, rightOK := seatExpiry(seats[j], ready, now) - if leftOK != rightOK { - return leftOK - } - if leftOK && left != right { - return left < right - } - return seats[i].Priority < seats[j].Priority - }) - case accounts.AggregationRoundRobin: - sort.SliceStable(seats, func(i, j int) bool { return seats[i].Priority < seats[j].Priority }) - // Seat ids come from the editable document and are not guaranteed - // unique. Rotate a stable key so a duplicate id cannot collapse two - // seats onto the map's last value. The list index is added only when - // two seats are otherwise identical, so reordering distinct seats - // does not move the cursor. - base := make([]string, len(seats)) - count := make(map[string]int, len(seats)) - for i, seat := range seats { - base[i] = seatRotationKey(seat) - count[base[i]]++ - } - keys := make([]string, len(seats)) - byKey := make(map[string]accounts.RouteSeat, len(seats)) - dup := make(map[string]int, len(seats)) - for i, seat := range seats { - key := base[i] - if count[key] > 1 { - n := dup[key] - dup[key]++ - key = key + "#" + strconv.Itoa(n) - } - keys[i] = key - byKey[key] = seat - } - if e.Pool != nil { - keys = e.Pool.RotateIDs(plan.ID+"|seats", keys, advance) - } - rotated := make([]accounts.RouteSeat, 0, len(keys)) - for _, key := range keys { - rotated = append(rotated, byKey[key]) - } - return rotated - default: - sort.SliceStable(seats, func(i, j int) bool { - if seats[i].Priority != seats[j].Priority { - return seats[i].Priority < seats[j].Priority - } - return seats[i].ID < seats[j].ID - }) - } - return seats +type aggregateSeat struct { + seat accounts.RouteSeat + key string + node *aggregateNode } -func (e ChatExecutor) readyFor(plan *AggregatePlan, publicModel string, allowed []string, excluded map[string]struct{}, eligible func(Item) bool) []Item { - if e.Pool == nil { - return nil - } - flat := *plan - flat.Seats = nil - return e.Pool.ReadyItems(e.routeQuery("", "", "", publicModel, allowed, excluded, eligible, &flat)) +func buildAggregateNode(plan *AggregatePlan) *aggregateNode { + return newAggregateNode(plan.Strategy, plan.byProvider, plan.Members, plan.Seats) } -func planForSeat(parent *AggregatePlan, seat accounts.RouteSeat) *AggregatePlan { - leaves := seatLeaves(seat) - id := parent.ID - strategy := accounts.AggregationPriority - if seat.Kind == "group" { - id = seat.GroupID - strategy = seat.GroupStrategy +func newAggregateNode(strategy accounts.AggregationStrategy, byProvider map[string][]accounts.AggregationMember, members []accounts.AggregationMember, seats []accounts.RouteSeat) *aggregateNode { + node := &aggregateNode{strategy: accounts.NormalizeAggregationStrategy(string(strategy))} + if len(seats) == 0 { + if byProvider == nil { + byProvider = indexAggregateMembers(members) + } + node.members = byProvider + for _, member := range members { + node.addPin(member) + } + return node } - plan := NewAggregatePlan(accounts.Aggregation{ - ID: id, Strategy: strategy, AllowFallbacks: parent.AllowFallbacks, MaxAttempts: parent.MaxAttempts, - ReasoningEffort: parent.ReasoningEffort, Members: leaves, + + ordered := append([]accounts.RouteSeat(nil), seats...) + sort.SliceStable(ordered, func(i, j int) bool { + if ordered[i].Priority != ordered[j].Priority { + return ordered[i].Priority < ordered[j].Priority + } + return node.strategy == accounts.AggregationPriority && ordered[i].ID < ordered[j].ID }) - if seat.Kind == "group" && len(seat.GroupSeats) > 0 { - plan.Seats = seat.GroupSeats - plan.Strategy = seat.GroupStrategy + for _, seat := range ordered { + if seat.Kind == "member" { + node.addPin(seat.Member) + } } - return plan -} -func seatLeaves(seat accounts.RouteSeat) []accounts.AggregationMember { - if seat.Kind == "member" { - return []accounts.AggregationMember{seat.Member} - } - if len(seat.GroupMembers) > 0 { - return append([]accounts.AggregationMember(nil), seat.GroupMembers...) - } - var out []accounts.AggregationMember - for _, child := range seat.GroupSeats { - out = append(out, seatLeaves(child)...) + // User-authored seat IDs are not guaranteed unique. Use the configured + // target and stable occurrence of identical seats, not just their IDs. + duplicates := make(map[string]int, len(ordered)) + for _, seat := range ordered { + base := seatRotationKey(seat) + occurrence := duplicates[base] + duplicates[base]++ + key := base + "#" + strconv.Itoa(occurrence) + var child *aggregateNode + switch seat.Kind { + case "member": + strategy := accounts.AggregationPriority + switch node.strategy { + case accounts.AggregationFEFOStrategy, accounts.AggregationLeastQuotaFirst, accounts.AggregationMostQuotaFirst: + // Direct seats have no child policy of their own. Rank their + // eligible accounts before comparing against other seats. + strategy = node.strategy + } + child = newAggregateNode(strategy, nil, []accounts.AggregationMember{seat.Member}, nil) + child.pins = node.pins + case "group": + child = newAggregateNode(seat.GroupStrategy, nil, seat.GroupMembers, seat.GroupSeats) + default: + continue + } + node.seats = append(node.seats, aggregateSeat{seat: seat, key: key, node: child}) } - return out + return node } -func seatRatio(seat accounts.RouteSeat, ready []Item) (float64, bool) { - plan := NewAggregatePlan(accounts.Aggregation{Members: seatLeaves(seat)}) - best := 0.0 - ok := false - for _, item := range ready { - if !plan.CanServeAccount(item) { - continue - } - ratio, known := quotaRemainingRatio(item) - if !known { - continue - } - if !ok || ratio < best { - best = ratio - ok = true - } +func (n *aggregateNode) addPin(member accounts.AggregationMember) { + if member.AccountID == "" { + return } - return best, ok + if n.pins == nil { + n.pins = make(map[string][]accounts.AggregationMember) + } + n.pins[member.AccountID] = append(n.pins[member.AccountID], member) } func seatRotationKey(seat accounts.RouteSeat) string { - switch seat.Kind { - case "member": + if seat.Kind == "member" { member := seat.Member return strings.Join([]string{ - "member", - seat.ID, - strings.TrimSpace(member.AccountID), - strings.ToLower(strings.TrimSpace(member.Provider)), - strings.ToLower(strings.TrimSpace(member.Region)), - strings.TrimSpace(member.Model), - strconv.Itoa(member.Priority), - }, "\x00") - default: - return strings.Join([]string{ - seat.Kind, - seat.ID, - seat.GroupID, - strconv.Itoa(seat.Priority), + "member", seat.ID, member.AccountID, aggregateMemberProvider(member.Provider), + member.Region, member.Model, strconv.Itoa(seat.Priority), strconv.Itoa(member.Priority), }, "\x00") } + return strings.Join([]string{seat.Kind, seat.ID, seat.GroupID, strconv.Itoa(seat.Priority)}, "\x00") } -func seatExpiry(seat accounts.RouteSeat, ready []Item, now time.Time) (int64, bool) { - plan := NewAggregatePlan(accounts.Aggregation{Members: seatLeaves(seat)}) - best := int64(0) - ok := false - for _, item := range ready { - member, matched := plan.matchMember(item) - if !matched { - continue - } - // FEFO packs are scoped to the concrete member model, not the logical - // aggregation id. The public logical model made a group seat look like - // it had no expiry at all. - expiry, depleted := fefoExpiry(item, member.Model, now) - if depleted || expiry == 0 { - continue - } - if !ok || expiry < best { - best = expiry - ok = true - } - } - return best, ok +func seatsCanServeAccount(seats []accounts.RouteSeat, item Item) bool { + return walkAggregateSeats(seats, func(member accounts.AggregationMember) bool { + return aggregateMemberProvider(member.Provider) == itemProvider(item) && + aggregateMemberInScope(item.ID, itemRegion(item), member) && itemCouldServeModel(item, member.Model) + }) } -func seatMiss(err error) bool { - var execution *ExecutionError - if !errors.As(err, &execution) { - return false - } - switch execution.Classified.Code { - case "model_not_available", "no_accounts_configured", "no_accounts", "rate_limit", "insufficient_quota": - return true - default: - return strings.Contains(execution.Classified.Message, "no accounts") +// walkAggregateSeats visits concrete leaves in configuration order and stops +// when visit returns true. GroupSeats is authoritative for nested groups. +func walkAggregateSeats(seats []accounts.RouteSeat, visit func(accounts.AggregationMember) bool) bool { + for _, seat := range seats { + switch seat.Kind { + case "member": + if visit(seat.Member) { + return true + } + case "group": + if len(seat.GroupSeats) > 0 { + if walkAggregateSeats(seat.GroupSeats, visit) { + return true + } + continue + } + for _, member := range seat.GroupMembers { + if visit(member) { + return true + } + } + } } + return false } -// PreviewAttempt is one concrete model in the order a request would try it. +// PreviewAttempt is one concrete model in the order configured for a route. type PreviewAttempt struct { ID string `json:"id"` Model string `json:"model"` @@ -251,7 +149,7 @@ type PreviewAttempt struct { } // ExplainSeats lists leaf members in seat order and marks leaves that have no -// ready account. +// ready account. Preview never reserves a slot or advances a rotation cursor. func ExplainSeats(pool *Pool, plan *AggregatePlan) []PreviewAttempt { if plan == nil { return nil @@ -263,24 +161,10 @@ func ExplainSeats(pool *Pool, plan *AggregatePlan) []PreviewAttempt { } return out } - var walk func(seats []accounts.RouteSeat) - walk = func(seats []accounts.RouteSeat) { - for _, seat := range seats { - switch seat.Kind { - case "member": - out = append(out, attemptFor(pool, plan, seat.Member)) - case "group": - if len(seat.GroupSeats) > 0 { - walk(seat.GroupSeats) - continue - } - for _, member := range seat.GroupMembers { - out = append(out, attemptFor(pool, plan, member)) - } - } - } - } - walk(plan.Seats) + walkAggregateSeats(plan.Seats, func(member accounts.AggregationMember) bool { + out = append(out, attemptFor(pool, plan, member)) + return false + }) return out } @@ -292,7 +176,7 @@ func attemptFor(pool *Pool, plan *AggregatePlan, member accounts.AggregationMemb return attempt } one := NewAggregatePlan(accounts.Aggregation{ID: plan.ID, Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{member}}) - if len(pool.ReadyItems(RouteQuery{PublicModel: plan.ID, ModelResolver: one.resolver()})) == 0 { + if selected := pool.selectAggregate(one, RouteQuery{PublicModel: plan.ID}, false); !selected.Available { attempt.Status = "skipped" attempt.Reason = "no ready account" } diff --git a/internal/executor/aggregation_seats_test.go b/internal/executor/aggregation_seats_test.go index 635b41178..d60be16bf 100644 --- a/internal/executor/aggregation_seats_test.go +++ b/internal/executor/aggregation_seats_test.go @@ -2,39 +2,36 @@ package executor import ( "testing" + "time" "github.com/caigee-cmd/cli2api/internal/accounts" ) -func TestPriorityTierCountCountsNestedGroupLeaves(t *testing.T) { - plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationPriority}) - plan.Members = []accounts.AggregationMember{ - {Provider: "qoder", Model: "a", Priority: 0}, - {Provider: "qoder", Model: "b", Priority: 1}, - {Provider: "qoder", Model: "c", Priority: 2}, - } - plan.Seats = []accounts.RouteSeat{{ - ID: "group", Kind: "group", GroupStrategy: accounts.AggregationRoundRobin, - GroupMembers: plan.Members, - }} - if got := plan.PriorityTierCount(); got != 3 { - t.Fatalf("tier count = %d, want 3 leaf priorities", got) +func reserveAggregateTest(t *testing.T, pool *Pool, plan *AggregatePlan, q RouteQuery) (Item, accounts.AggregationMember) { + t.Helper() + item, member, found, reserved := pool.ReserveAggregate(plan, q) + if !found || !reserved { + t.Fatalf("aggregate reservation = %q/%q found=%t reserved=%t", item.ID, member.Model, found, reserved) } + pool.Release(item.ID) + return item, member } func TestRoundRobinKeepsDuplicateSeatIDs(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "shared", Provider: "qoder", Region: "global", Models: []string{"a", "b"}}) plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationRoundRobin}) - plan.Members = []accounts.AggregationMember{ - {Provider: "qoder", Model: "a", Priority: 0}, - {Provider: "qoder", Model: "b", Priority: 1}, - } plan.Seats = []accounts.RouteSeat{ - {ID: "same", Kind: "member", Member: plan.Members[0]}, - {ID: "same", Kind: "member", Member: plan.Members[1]}, + {ID: "same", Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: "a"}}, + {ID: "same", Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: "b"}}, + {ID: "same", Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: "a"}}, } - order := (ChatExecutor{}).orderedSeats(plan, "outer", nil, nil, nil, true) - if len(order) != 2 || order[0].Member.Model != "a" || order[1].Member.Model != "b" { - t.Fatalf("duplicate seat IDs collapsed the rotation: %+v", order) + q := RouteQuery{PublicModel: "outer"} + for i, want := range []string{"a", "b", "a", "a", "b", "a"} { + item, member := reserveAggregateTest(t, pool, plan, q) + if item.ID != "shared" || member.Model != want { + t.Fatalf("pick %d = %s/%s, want shared/%s", i, item.ID, member.Model, want) + } } } @@ -53,13 +50,277 @@ func TestSeatOrderDoesNotFlattenToModelName(t *testing.T) { {ID: "first", Kind: "member", Priority: 0, Weight: 100, Member: plan.Members[0]}, {ID: "second", Kind: "member", Priority: 1, Weight: 100, Member: plan.Members[1]}, } - exec := ChatExecutor{Pool: pool} - item, err := exec.pick("req", "", "", "", "outer", nil, map[string]struct{}{}, nil, plan) - if err != nil || item.ID != "z" { - t.Fatalf("first pick = %+v %v", item, err) + q := RouteQuery{PublicModel: "outer"} + item, member := reserveAggregateTest(t, pool, plan, q) + if item.ID != "z" || member.Model != "model-z" { + t.Fatalf("first pick = %s/%s", item.ID, member.Model) + } + q.ExcludedModels = map[routeModelKey]struct{}{accountRouteModelKey(item, member.Model): {}} + item, member = reserveAggregateTest(t, pool, plan, q) + if item.ID != "a" || member.Model != "model-a" { + t.Fatalf("second pick = %s/%s", item.ID, member.Model) + } +} + +func TestCompiledPriorityGroupRotatesWithinItsTier(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "z-top-a", Provider: "qoder", Models: []string{"a"}}) + pool.Upsert(Item{ID: "y-top-b", Provider: "qoder", Models: []string{"b"}}) + pool.Upsert(Item{ID: "a-low-c", Provider: "qoder", Models: []string{"c"}}) + pool.Upsert(Item{ID: "tail", Provider: "workbuddy", Models: []string{"tail"}}) + const doc = `{"version":1,"steps":[{"id":"group","kind":"group","aggregation_id":"inner"},{"id":"fallback","kind":"member","provider":"workbuddy","model":"tail"}]}` + inner := accounts.Aggregation{ID: "inner", Enabled: true, Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "a", Priority: 4}, + {Provider: "qoder", Model: "b", Priority: 4}, + {Provider: "qoder", Model: "c", Priority: 7}, + }} + agg, seats, _, err := accounts.CompilePipeline(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationPriority, Document: doc}, map[string]accounts.Aggregation{inner.ID: inner}, "", nil, nil) + if err != nil { + t.Fatal(err) + } + plan := NewAggregatePlan(agg) + plan.Seats = seats + q := RouteQuery{PublicModel: "outer"} + for i, want := range []string{"b", "a", "b", "a"} { + _, member := reserveAggregateTest(t, pool, plan, q) + if member.Model != want || member.Priority != 4 { + t.Fatalf("pick %d = %+v, want member %s from tier 4", i, member, want) + } + } + q.ExcludedModels = map[routeModelKey]struct{}{{AccountID: "z-top-a", Model: "a"}: {}, {AccountID: "y-top-b", Model: "b"}: {}} + _, member := reserveAggregateTest(t, pool, plan, q) + if member.Model != "c" || member.Priority != 7 { + t.Fatalf("after tier 4 depletion picked %+v, want inner tier 7", member) + } + q.ExcludedModels[routeModelKey{AccountID: "a-low-c", Model: "c"}] = struct{}{} + _, member = reserveAggregateTest(t, pool, plan, q) + if member.Model != "tail" { + t.Fatalf("after exhausting the inner group picked %+v, want outer fallback", member) + } +} + +func TestAggregateSeatCursorAdvancesOnlyForAvailableReservations(t *testing.T) { + pool := NewPool(nil, nil) + for _, id := range []string{"a", "b", "c"} { + pool.Upsert(Item{ID: id, Provider: "qoder", Models: []string{id}, MaxInFlight: 1}) + } + plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationRoundRobin}) + for _, id := range []string{"a", "b", "c"} { + plan.Seats = append(plan.Seats, accounts.RouteSeat{ID: id, Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: id}}) + } + q := RouteQuery{PublicModel: "outer"} + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "a" { + t.Fatalf("first pick = %q, want a", item.ID) + } + for _, id := range []string{"a", "b", "c"} { + if !pool.Acquire(id) { + t.Fatalf("could not fill %s", id) + } + } + if miss := pool.selectAggregate(plan, q, true); miss.Available || !miss.Saturated || !miss.HasRoute { + t.Fatalf("saturated reservation = %+v", miss) + } + if !pool.HasAggregateRoute(plan, q) { + t.Fatal("saturation must not hide capability") + } + pool.Release("c") + if probe := pool.selectAggregate(plan, q, false); !probe.Available || probe.Item.ID != "c" || probe.Item.InFlight != 0 { + t.Fatalf("read-only probe = %+v", probe) + } + pool.Release("b") + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "b" { + t.Fatalf("after miss and probes pick = %q, want b after a", item.ID) + } + pool.Release("a") +} + +func TestAggregateSeatCursorCommitsTheWinnerNotTheStart(t *testing.T) { + pool := NewPool(nil, nil) + plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationRoundRobin}) + for _, id := range []string{"a", "b", "c"} { + pool.Upsert(Item{ID: id, Provider: "qoder", Models: []string{id}, MaxInFlight: 1}) + plan.Seats = append(plan.Seats, accounts.RouteSeat{ID: id, Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: id}}) + } + q := RouteQuery{PublicModel: "outer"} + if !pool.Acquire("a") { + t.Fatal("could not saturate a") + } + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "b" { + t.Fatalf("with a saturated pick = %q, want b", item.ID) + } + pool.Release("a") + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "c" { + t.Fatalf("after b was reserved pick = %q, want c", item.ID) + } +} + +func TestCompiledMultiAccountFillFirstKeepsSelectedScope(t *testing.T) { + const memberStep = `{"id":"selected","kind":"member","provider":"qoder","model":"model","weight":450,"account_ids":["z-checked","a-checked","z-checked"]}` + inner := accounts.Aggregation{ID: "inner", Enabled: true, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "no-ready-model"}}} + for _, tc := range []struct { + name string + steps string + }{ + {name: "flat", steps: memberStep}, + {name: "nested", steps: memberStep + `,{"id":"group","kind":"group","aggregation_id":"inner"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + pool := NewPool(nil, nil) + for _, id := range []string{"a-checked", "z-checked", "0-unchecked"} { + pool.Upsert(Item{ID: id, Provider: "qoder", Models: []string{"model"}, MaxInFlight: 1}) + } + compiled, seats, _, err := accounts.CompilePipeline(accounts.Aggregation{ + ID: "logical", Strategy: accounts.AggregationFillFirst, Document: `{"version":1,"steps":[` + tc.steps + `]}`, + }, map[string]accounts.Aggregation{inner.ID: inner}, "", nil, nil) + if err != nil { + t.Fatal(err) + } + plan := NewAggregatePlan(compiled) + plan.Seats = seats + q := RouteQuery{PublicModel: plan.ID} + first, _ := reserveAggregateTest(t, pool, plan, q) + if first.ID != "a-checked" && first.ID != "z-checked" { + t.Fatalf("picked unchecked account %s", first.ID) + } + if item, member := reserveAggregateTest(t, pool, plan, q); item.ID != first.ID || member.Weight != 450 { + t.Fatalf("equal-weight fill-first did not retain its winner and configured weight: %s, %+v", item.ID, member) + } + fill := func(id string) { + if !pool.Acquire(id) { + t.Fatalf("could not fill %s", id) + } + t.Cleanup(func() { pool.Release(id) }) + } + fill(first.ID) + second, _ := reserveAggregateTest(t, pool, plan, q) + if second.ID == first.ID || (second.ID != "a-checked" && second.ID != "z-checked") { + t.Fatalf("with %s full, got %s instead of the other checked account", first.ID, second.ID) + } + fill(second.ID) + if result := pool.selectAggregate(plan, q, true); result.Available || !result.Saturated || !result.HasRoute { + t.Fatalf("saturated selected accounts must not broaden the route: %+v", result) + } + }) + } +} + +func compileAggregateSeatTest(t *testing.T, strategy accounts.AggregationStrategy) *AggregatePlan { + t.Helper() + const doc = `{"version":1,"steps":[{"id":"group","kind":"group","aggregation_id":"inner"},{"id":"direct","kind":"member","provider":"qoder","model":"direct"}]}` + inner := accounts.Aggregation{ID: "inner", Enabled: true, Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "chosen", Priority: 0}, + {Provider: "qoder", Model: "unchosen", Priority: 1}, + }} + compiled, seats, _, err := accounts.CompilePipeline(accounts.Aggregation{ID: "outer", Strategy: strategy, Document: doc}, map[string]accounts.Aggregation{inner.ID: inner}, "", nil, nil) + if err != nil { + t.Fatal(err) + } + plan := NewAggregatePlan(compiled) + plan.Seats = seats + return plan +} + +func TestAggregateNestedQuotaRanksTheChildStrategyWinner(t *testing.T) { + pool := NewPool(nil, nil) + for model, remaining := range map[string]float64{"chosen": 90, "unchosen": 10, "direct": 50} { + pool.Upsert(Item{ID: model, Provider: "qoder", Models: []string{model}, Quota: &accounts.QuotaSnapshot{Total: 100, Remaining: remaining}}) + } + for strategy, want := range map[accounts.AggregationStrategy]string{ + accounts.AggregationLeastQuotaFirst: "direct", + accounts.AggregationMostQuotaFirst: "chosen", + } { + t.Run(string(strategy), func(t *testing.T) { + plan := compileAggregateSeatTest(t, strategy) + item, member := reserveAggregateTest(t, pool, plan, RouteQuery{PublicModel: "outer"}) + if item.ID != want || member.Model != want { + t.Fatalf("picked %s/%s, want %s from child strategy winners", item.ID, member.Model, want) + } + }) + } +} + +func TestAggregateNestedFEFORanksTheChildStrategyWinner(t *testing.T) { + pool := NewPool(nil, nil) + now := time.Now() + for model, in := range map[string]time.Duration{"chosen": 72 * time.Hour, "unchosen": 24 * time.Hour, "direct": 48 * time.Hour} { + pool.Upsert(Item{ID: model, Provider: "qoder", Models: []string{model}, Quota: &accounts.QuotaSnapshot{Packages: []accounts.QuotaPackage{ + {Scope: accounts.QuotaPackageScopeAccountFEFO, Unit: "credits", Remain: 1, EndsAt: now.Add(in).Unix()}, + }}}) + } + plan := compileAggregateSeatTest(t, accounts.AggregationFEFOStrategy) + q := RouteQuery{PublicModel: "outer"} + result := pool.selectAggregate(plan, q, true) + if !result.Available || !result.FEFO || result.Item.ID != "direct" || result.Member.Model != "direct" { + t.Fatalf("first pick = %+v, want direct in the outer FEFO path", result) + } + pool.Release(result.Item.ID) + q.ExcludedModels = map[routeModelKey]struct{}{accountRouteModelKey(result.Item, result.Member.Model): {}} + item, member := reserveAggregateTest(t, pool, plan, q) + if item.ID != "chosen" || member.Model != "chosen" { + t.Fatalf("next pick = %s/%s, want the child's top-priority member", item.ID, member.Model) + } +} + +func TestAggregateNestedQuotaAndFEFOConsiderEveryDirectAccount(t *testing.T) { + for _, tc := range []struct { + strategy accounts.AggregationStrategy + worst float64 + best float64 + }{ + {accounts.AggregationLeastQuotaFirst, 90, 10}, + {accounts.AggregationMostQuotaFirst, 10, 90}, + {accounts.AggregationFEFOStrategy, 50, 50}, + } { + t.Run(string(tc.strategy), func(t *testing.T) { + pool := NewPool(nil, nil) + now := time.Now() + add := func(id, model string, ratio float64, days time.Duration) { + pool.Upsert(Item{ID: id, Provider: "qoder", Models: []string{model}, MaxInFlight: 1, Quota: &accounts.QuotaSnapshot{ + Total: 100, Remaining: ratio, Packages: []accounts.QuotaPackage{fefoPack(1, now.Add(days*24*time.Hour).Unix())}, + }}) + } + add("a-direct", "direct", tc.worst, 3) + add("z-direct", "direct", tc.best, 1) + add("middle", "chosen", 50, 2) + plan := compileAggregateSeatTest(t, tc.strategy) + q := RouteQuery{PublicModel: plan.ID} + flat := *plan + flat.Seats = nil // same models and accounts, with no nested seat boundary + if result := pool.selectAggregate(&flat, q, false); !result.Available || result.Item.ID != "z-direct" { + t.Fatalf("flat picked %q, want z-direct", result.Item.ID) + } + for i := 0; i < 2; i++ { + item, _ := reserveAggregateTest(t, pool, plan, q) + if item.ID != "z-direct" { + t.Fatalf("nested pick %d = %s, want z-direct as in the flat route; a direct member has no separate child strategy", i, item.ID) + } + } + if !pool.Acquire("z-direct") { + t.Fatal("could not fill the best direct account") + } + t.Cleanup(func() { pool.Release("z-direct") }) + if item, _ := reserveAggregateTest(t, pool, plan, q); item.ID != "middle" { + t.Fatalf("with z-direct full, picked %s, want middle", item.ID) + } + }) + } +} + +func TestAggregateFEFOOnlyReportsTheSelectedChildPath(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "fefo", Provider: "qoder", Models: []string{"fefo"}}) + pool.Upsert(Item{ID: "direct", Provider: "qoder", Models: []string{"direct"}}) + plan := NewAggregatePlan(accounts.Aggregation{ID: "outer", Strategy: accounts.AggregationRoundRobin}) + plan.Seats = []accounts.RouteSeat{ + {ID: "group", Kind: "group", GroupID: "child", GroupStrategy: accounts.AggregationFEFOStrategy, GroupMembers: []accounts.AggregationMember{{Provider: "qoder", Model: "fefo"}}}, + {ID: "direct", Kind: "member", Member: accounts.AggregationMember{Provider: "qoder", Model: "direct"}}, } - item, err = exec.pick("req", "", "", "", "outer", nil, map[string]struct{}{"z": {}}, nil, plan) - if err != nil || item.ID != "a" { - t.Fatalf("second pick = %+v %v", item, err) + q := RouteQuery{PublicModel: "outer"} + for _, want := range []string{"fefo", "direct", "fefo"} { + result := pool.selectAggregate(plan, q, true) + if !result.Available || result.Member.Model != want || result.FEFO != (want == "fefo") { + t.Fatalf("pick = %+v, want %s and its own path's FEFO flag", result, want) + } + pool.Release(result.Item.ID) } } diff --git a/internal/executor/aggregation_strategy_test.go b/internal/executor/aggregation_strategy_test.go index 1faf09137..5b9970dfb 100644 --- a/internal/executor/aggregation_strategy_test.go +++ b/internal/executor/aggregation_strategy_test.go @@ -1,24 +1,12 @@ package executor import ( - "context" "testing" "time" "github.com/caigee-cmd/cli2api/internal/accounts" - "github.com/caigee-cmd/cli2api/internal/translate" ) -func aggRouteQuery(plan *AggregatePlan) RouteQuery { - return RouteQuery{ - PublicModel: "my-model", - ModelResolver: plan.resolver(), - StrategyOverride: string(plan.Strategy), - PriorityResolver: plan.priorityResolver(), - WeightResolver: plan.weightResolver(), - } -} - // A member with AccountID is a deployment pinned to that account rather than // the whole provider pool. Sibling accounts keep serving legacy members but // cannot satisfy this member. @@ -41,9 +29,9 @@ func TestAggregateMemberAccountPin(t *testing.T) { t.Fatalf("q2 member = %+v ok=%v", member, ok) } for i := 0; i < 5; i++ { - item, ok := p.PickRoute(aggRouteQuery(plan)) - if !ok || item.ID != "q2" { - t.Fatalf("pinned member pick %d = %+v ok=%v", i, item, ok) + item, _ := reserveAggregateTest(t, p, plan, RouteQuery{PublicModel: plan.ID}) + if item.ID != "q2" { + t.Fatalf("pinned member pick %d = %+v", i, item) } } } @@ -62,9 +50,9 @@ func TestAggregateExcludesUnknownCatalogOutsideMemberRegion(t *testing.T) { }, }) for i := 0; i < 10; i++ { - item, ok := p.PickRoute(aggRouteQuery(plan)) - if !ok || item.ID != "q-global" { - t.Fatalf("aggregate pick %d = %+v ok=%v, want q-global", i, item, ok) + item, _ := reserveAggregateTest(t, p, plan, RouteQuery{PublicModel: plan.ID}) + if item.ID != "q-global" { + t.Fatalf("aggregate pick %d = %+v, want q-global", i, item) } } } @@ -97,11 +85,11 @@ func TestAggregatePriorityAlwaysPicksHighestPriority(t *testing.T) { {Provider: "qoder", Model: "model-a", Priority: 1, Weight: 100}, }, }) - q := aggRouteQuery(plan) + q := RouteQuery{PublicModel: plan.ID} for i := 0; i < 10; i++ { - item, ok := p.PickRoute(q) - if !ok || item.ID != "workbuddy" { - t.Fatalf("priority strategy pick %d = %+v (%v), want workbuddy", i, item, ok) + item, _ := reserveAggregateTest(t, p, plan, q) + if item.ID != "workbuddy" { + t.Fatalf("priority strategy pick %d = %+v, want workbuddy", i, item) } } } @@ -117,10 +105,66 @@ func TestAggregatePriorityFallsToNextOnCooldown(t *testing.T) { }) // Cool the top-priority member's real model. top, _ := p.ByID("workbuddy") - p.MarkClassified("workbuddy", Classified{Kind: KindRateLimit, Model: effectiveModel(top, aggRouteQuery(plan)), Cooldown: time.Minute}) - item, ok := p.PickRoute(aggRouteQuery(plan)) - if !ok || item.ID != "qoder" { - t.Fatalf("after top-priority cooldown want qoder, got %+v ok=%v", item, ok) + p.MarkClassified("workbuddy", Classified{Kind: KindRateLimit, Model: cooldownModel(top, "model-b"), Cooldown: time.Minute}) + item, _ := reserveAggregateTest(t, p, plan, RouteQuery{PublicModel: plan.ID}) + if item.ID != "qoder" { + t.Fatalf("after top-priority cooldown want qoder, got %+v", item) + } +} + +func TestAggregateQuotaGateUsesResolvedAliasTarget(t *testing.T) { + for _, layout := range []string{"flat", "nested"} { + for _, strategy := range []accounts.AggregationStrategy{accounts.AggregationPriority, accounts.AggregationFEFOStrategy} { + for _, gate := range []struct { + name string + quota accounts.QuotaSnapshot + }{ + {name: "exhausted", quota: accounts.QuotaSnapshot{Exceeded: true}}, + {name: "credit-floor", quota: accounts.QuotaSnapshot{Unit: "credits", Remaining: 1}}, + } { + t.Run(layout+"/"+string(strategy)+"/"+gate.name, func(t *testing.T) { + pool := NewPool(nil, nil) + pool.SetDefaultCreditFloor(10) + pool.Upsert(Item{ + ID: "account", Provider: "qoder", Models: []string{"free", "paid"}, + // Dispatch resolves aliases exactly once. "free" used as + // a member name points at paid, not the free entry in the catalog. + ModelAliases: map[string]string{"free-alias": "free", "free": "paid"}, + FreeModels: []string{"free"}, Quota: &gate.quota, + }) + for _, tc := range []struct { + model string + available bool + }{ + {model: "free-alias", available: true}, + {model: "free", available: false}, + } { + t.Run(tc.model, func(t *testing.T) { + members := []accounts.AggregationMember{{Provider: "qoder", Model: tc.model, AccountID: "account"}} + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: strategy, Members: members}) + if layout == "nested" { + plan.Strategy = accounts.AggregationPriority + plan.Seats = []accounts.RouteSeat{{ID: "group", Kind: "group", GroupID: "inner", GroupStrategy: strategy, GroupMembers: members}} + } + q := RouteQuery{PublicModel: plan.ID} + if !pool.HasAggregateRoute(plan, q) { + t.Fatalf("quota must not hide the %q capability", tc.model) + } + result := pool.selectAggregate(plan, q, true) + if result.Available { + pool.Release(result.Item.ID) + } + if result.Available != tc.available || result.QuotaBlocked != !tc.available { + t.Fatalf("%q pick available=%t quotaBlocked=%t, want available=%t quotaBlocked=%t", tc.model, result.Available, result.QuotaBlocked, tc.available, !tc.available) + } + if result.Available && (result.Member.Model != tc.model || targetFor(result.Item, result.Member.Model).upstreamModel != "free") { + t.Fatalf("reservation must keep the configured spelling and dispatch the real free model, got %+v", result) + } + }) + } + }) + } + } } } @@ -137,8 +181,8 @@ func TestAggregateFillFirstUsesMemberWeight(t *testing.T) { p.items[1].Weight = 1 // workbuddy account weight tiny p.items[0].Weight = 200 // qoder account weight large for i := 0; i < 6; i++ { - item, ok := p.PickRoute(aggRouteQuery(plan)) - if !ok || item.ID != "workbuddy" { + item, _ := reserveAggregateTest(t, p, plan, RouteQuery{PublicModel: plan.ID}) + if item.ID != "workbuddy" { t.Fatalf("fill-first should use member weight, pick %d = %+v", i, item) } } @@ -154,13 +198,10 @@ func TestAggregateRoundRobinRotates(t *testing.T) { {Provider: "qoder", Model: "model-a", Priority: 1, Weight: 100}, }, }) - q := aggRouteQuery(plan) + q := RouteQuery{PublicModel: plan.ID} seen := map[string]bool{} for i := 0; i < 6; i++ { - item, ok := p.PickRoute(q) - if !ok { - t.Fatal("no route") - } + item, _ := reserveAggregateTest(t, p, plan, q) seen[item.ID] = true } if !seen["workbuddy"] || !seen["qoder"] { @@ -185,13 +226,10 @@ func TestAggregateRoundRobinDoesNotLatchRegion(t *testing.T) { {Provider: "workbuddy", Model: "shared", Priority: 0, Weight: 100}, }, }) - q := aggRouteQuery(plan) + q := RouteQuery{PublicModel: plan.ID} counts := map[string]int{} for i := 0; i < 20; i++ { - item, ok := p.PickRoute(q) - if !ok { - t.Fatal("no aggregate route") - } + item, _ := reserveAggregateTest(t, p, plan, q) counts[item.Provider]++ } if counts["qoder"] == 0 || counts["workbuddy"] == 0 { @@ -224,35 +262,38 @@ func TestAggregateFailoverCrossesMemberRegions(t *testing.T) { {Provider: "workbuddy", Region: "", Model: "shared", Priority: 1, Weight: 100}, }, }) - ctx := WithAggregatePlan(context.Background(), plan) e := ChatExecutor{Pool: p} - loop := e.newRouteLoop(ctx, "", "", translate.ChatRequest{Model: "my-model"}) + loop := e.newRouteLoop(RouteInput{AggregatePlan: plan, PublicModel: "my-model"}, "my-model", nil) - first, _, err := loop.pickNext(e, "my-model") + first, _, err := loop.pickNextReserved(e) if err != nil { t.Fatalf("first pick: %v", err) } - if got := NormalizeRegion(first.Region); got != "cn" { + if got := NormalizeRegion(first.item.Region); got != "cn" { t.Fatalf("first pick region=%q, want cn", got) } - if loop.regionFilter != "" { - t.Fatalf("aggregated loop must not pin a region, got %q", loop.regionFilter) + e.releaseInFlight("", first.item.ID) + if loop.working.RegionFilter != "" { + t.Fatalf("aggregated loop must not pin a region, got %q", loop.working.RegionFilter) } - if loop.attempts != 2 { - t.Fatalf("attempts after first pick=%d, want 2 (plan.MaxAttempts capped by candidates)", loop.attempts) + if loop.attempts != 3 { + t.Fatalf("attempts after first pick=%d, want 3 (plan.MaxAttempts is a total budget)", loop.attempts) } // A second attempt must be allowed to cross the member region. Excluding the // cn member leaves the global workbuddy member as the next candidate. - loop.excluded[first.ID] = struct{}{} - second, _, err := loop.pickNext(e, "my-model") + if !loop.failover(e, first, first.item.ID, Classified{Failover: true}, nil) { + t.Fatal("expected remaining attempt budget") + } + second, _, err := loop.pickNextReserved(e) if err != nil { t.Fatalf("failover should reach the global member: %v", err) } - if got := NormalizeRegion(second.Region); got != "global" { + e.releaseInFlight("", second.item.ID) + if got := NormalizeRegion(second.item.Region); got != "global" { t.Fatalf("failover region=%q, want global", got) } - if loop.attempts != 2 { - t.Fatalf("attempts after failover=%d, want 2 (plan.MaxAttempts must not be overwritten)", loop.attempts) + if loop.attempts != 3 { + t.Fatalf("attempts after failover=%d, want 3 (plan.MaxAttempts must not be overwritten)", loop.attempts) } } diff --git a/internal/executor/chat.go b/internal/executor/chat.go index 11116216e..6ea476a36 100644 --- a/internal/executor/chat.go +++ b/internal/executor/chat.go @@ -12,7 +12,6 @@ import ( "net/http" "sort" "strings" - "sync" "time" "github.com/caigee-cmd/cli2api/internal/accounts" @@ -55,11 +54,17 @@ type ChatResult struct { Credits *float64 ConsumedCredits *float64 AccountID string + PoolAccountID string Provider string AttemptCount int RawNote string Routing string ReasoningLevel string + // CooldownModel is the canonical account model key, never a virtual + // aggregate ID, per-account alias, or response model label. + CooldownModel string + AggregateFEFO bool + InternalRetries int } type StreamResult struct { @@ -74,26 +79,44 @@ type StreamResult struct { TTFBMs int Routing string ReasoningLevel string + // CooldownModel is the effective model key used by routing/cooldown. See + // ChatResult.CooldownModel. + CooldownModel string + AggregateFEFO bool + InternalRetries int // NativeResponses marks the body as an upstream OpenAI Responses SSE stream // that /v1/responses can relay verbatim instead of translating. NativeResponses bool + // RequestState is the send fact of the accepted attempt that opened this + // stream; a response head proves the request reached the upstream. + RequestState string + completion *streamCompletion } type NativeResponseResult struct { - Response json.RawMessage - AccountID string - Provider string - AttemptCount int - Routing string - ReasoningLevel string - FinishReason string - PromptTokens *int - OutputTokens *int - CachedTokens *int + Response json.RawMessage + // CompatResult is set when a named aggregate selects a Chat member + // for a request that also has a compatible Chat representation. + CompatResult *ChatResult + AccountID string + PoolAccountID string + Provider string + AttemptCount int + Routing string + ReasoningLevel string + FinishReason string + PromptTokens *int + OutputTokens *int + CachedTokens *int + CooldownModel string + AggregateFEFO bool + InternalRetries int } type requestIDKey struct{} +type entryRequestIDKey struct{} + func WithRequestID(ctx context.Context, id string) context.Context { if strings.TrimSpace(id) == "" { return ctx @@ -101,6 +124,25 @@ func WithRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, requestIDKey{}, id) } +// WithEntryRequestID marks the id as allocated by the HTTP entry before auth +// and parsing. Prepare reuses this one because a rejection must be +// correlatable; a generic WithRequestID value is not trusted for that role +// (older callers may carry a stale id). +func WithEntryRequestID(ctx context.Context, id string) context.Context { + if strings.TrimSpace(id) == "" { + return ctx + } + return context.WithValue(ctx, entryRequestIDKey{}, id) +} + +func EntryRequestIDFromContext(ctx context.Context) string { + if ctx == nil { + return "" + } + id, _ := ctx.Value(entryRequestIDKey{}).(string) + return id +} + func RequestIDFromContext(ctx context.Context) string { if ctx == nil { return "" @@ -172,14 +214,15 @@ type routingPlan struct { Source string SessionKey string BoundAccount string + BoundVersion uint64 PublicModel string } -func (e ChatExecutor) bindSession(plan routingPlan, accountID string) { +func (e ChatExecutor) bindSession(plan routingPlan, accountID string) uint64 { if plan.Source == routingPin || plan.SessionKey == "" || e.SessionAffinity == nil { - return + return 0 } - e.SessionAffinity.Bind(plan.SessionKey, accountID) + return e.SessionAffinity.bindVersion(plan.SessionKey, accountID) } func (e ChatExecutor) observeRouting(plan *routingPlan, accountID string) { @@ -239,62 +282,13 @@ func itemProvider(item Item) string { // the same model so regional escape still works, but does not let that // unknown catalog pin a later, different model (Devin → Deepseek compact). func stickyAccountCanServeModel(item Item, publicModel string) bool { - if item.Models != nil { - return ItemCouldServeModel(item, publicModel) - } - if strings.TrimSpace(publicModel) == "" { - return true - } - if len(item.ProvenModels) == 0 { - return true - } - probe := item - probe.Models = []string{} - return ItemCouldServeModel(probe, publicModel) -} - -func (e ChatExecutor) prepareRouting(ctx context.Context, prefer, providerFilter string, req translate.ChatRequest, plan *AggregatePlan) (string, string, string, routingPlan) { - prefer = strings.TrimSpace(prefer) - providerFilter = strings.ToLower(strings.TrimSpace(providerFilter)) - publicModel := req.Model - if prefer != "" { - return prefer, providerFilter, "", routingPlan{Source: routingPin, PublicModel: publicModel} - } - - planRoute := routingPlan{Source: routingPool, SessionKey: resolveSessionKey(ctx, req), PublicModel: publicModel} - if planRoute.SessionKey == "" || e.SessionAffinity == nil || e.Pool == nil { - return "", providerFilter, "", planRoute - } - accountID, ok := e.SessionAffinity.Get(planRoute.SessionKey) - if !ok { - return "", providerFilter, "", planRoute - } - item, ok := e.Pool.ByID(accountID) - if !ok { - e.SessionAffinity.RecordEscape("account_missing") - e.SessionAffinity.Forget(planRoute.SessionKey) - return "", providerFilter, "", planRoute - } - if providerFilter != "" && providerFilter != itemProvider(item) { - e.SessionAffinity.RecordEscape("provider_mismatch") - return "", providerFilter, "", planRoute - } - if !accounts.ProviderRegionAllowed(itemProvider(item), accounts.NormalizeRegion(item.Region), allowedProvidersFrom(ctx)) { - e.SessionAffinity.RecordEscape("provider_not_allowed") - return "", providerFilter, "", planRoute - } - if plan != nil { - if !plan.CanServeAccount(item) { - e.SessionAffinity.RecordEscape("model_unavailable") - return "", providerFilter, "", planRoute - } - } else if !stickyAccountCanServeModel(item, publicModel) { - e.SessionAffinity.RecordEscape("model_unavailable") - return "", providerFilter, "", planRoute - } - return item.ID, itemProvider(item), accounts.NormalizeRegion(item.Region), routingPlan{ - Source: routingSticky, SessionKey: planRoute.SessionKey, BoundAccount: item.ID, PublicModel: publicModel, + if item.Models == nil && len(item.ProvenModels) > 0 { + // A catalog is unknown, but the session has evidence for other models. + item.Models = []string{} } + // Even without positive evidence, an explicit rejection (including an + // alias target) or a model restriction must rule out sticky preference. + return ItemCouldServeModel(item, publicModel) } func NewChatExecutor(pool *Pool, workerKey string) ChatExecutor { @@ -324,30 +318,6 @@ func capacityError(err error) bool { return execution.Classified.Code == "rate_limit" && execution.Classified.Message == "all accounts at capacity" } -// providerHasCapacity reports whether any provider other than the pinned one -// can take this model right now. The caller's own provider filter is a -// constraint, so saturation inside it is not a reason to leave. -func (e ChatExecutor) providerHasCapacity(pinnedProvider, pinnedRegion, publicModel string, allowed []string, eligible func(Item) bool) bool { - if e.Pool == nil || pinnedProvider == "" { - return false - } - query := e.routeQuery("", "", "", publicModel, allowed, nil, func(item Item) bool { - if itemProvider(item) == pinnedProvider && (pinnedRegion == "" || accounts.NormalizeRegion(item.Region) == pinnedRegion) { - return false - } - // A cooling account is not a free slot. HasCapacity also rejects one, - // but only after routeMatches, and a model-scoped cooldown would - // otherwise look like capacity and make a full provider leave for an - // account the next pick cannot dispatch. - now := time.Now() - if itemDown(item, now) || itemModelDown(item, RouteQuery{PublicModel: publicModel}, now) { - return false - } - return eligible == nil || eligible(item) - }) - return e.Pool.HasCapacity(query) -} - func (e ChatExecutor) routeQuery(prefer, providerFilter, regionFilter, publicModel string, allowed []string, excluded map[string]struct{}, eligible func(Item) bool, plan ...*AggregatePlan) RouteQuery { q := RouteQuery{ PublicModel: publicModel, @@ -370,89 +340,6 @@ func (e ChatExecutor) routeQuery(prefer, providerFilter, regionFilter, publicMod return q } -func (e ChatExecutor) pick(requestID, prefer, providerFilter, regionFilter, publicModel string, allowed []string, excluded map[string]struct{}, eligible func(Item) bool, plan *AggregatePlan) (Item, error) { - if plan != nil && len(plan.Seats) > 0 { - return e.pickSeats(requestID, prefer, providerFilter, regionFilter, publicModel, allowed, excluded, eligible, plan) - } - query := e.routeQuery(prefer, providerFilter, regionFilter, publicModel, allowed, excluded, eligible, plan) - if e.Pool != nil { - if item, ok := e.Pool.PickRoute(query); ok { - if retryAfter := e.Pool.RetryAfter(item, publicModel, query.ModelResolver); retryAfter > 0 { - return Item{}, coolingPickError(item, publicModel, retryAfter) - } - return item, nil - } - // PickRoute returned false with an eligible route: every - // eligible account is concurrency-saturated (a cooling account - // would have been surfaced with ok=true for a retry-after hint). - // Sending the request would just round-trip into the worker's - // 429 busy, so fail fast with a rate-limit so the client gets a - // clean Retry-After. This must precede the model_not_available - // check: saturated means the model IS served, just at capacity. - if e.Pool.LenRoute(query) > 0 { - return Item{}, NewExecutionError(Classified{ - Kind: accounts.KindRateLimit, Status: 429, Code: "rate_limit", - Type: "api_error", Message: "all accounts at capacity", - Cooldown: 5 * time.Second, RetryAfter: 5 * time.Second, Failover: true, - }, nil) - } - // No eligible account is ready right now. Before blaming the model or - // reporting "no accounts available", check whether accounts that could - // serve this model are blocked only by an exhausted quota. A stale or - // genuinely exhausted snapshot leaves no routing hint, so without this - // the client sees a generic "no accounts available" instead of a quota - // error that explains the real cause. - if _, ok := e.Pool.QuotaBlockedForModel(query); ok { - retryAfter := NextLocalMidnightCooldown() - return Item{}, NewExecutionError(Classified{ - Kind: accounts.KindQuota, Status: 429, Code: "insufficient_quota", - Type: "insufficient_quota", Failover: false, - Cooldown: retryAfter, RetryAfter: retryAfter, - Message: quotaBlockedMessage(publicModel), - }, nil) - } - if publicModel != "" && publicModel != "auto" { - unfiltered := query - unfiltered.PublicModel = "" - if e.Pool.LenRoute(unfiltered) > 0 { - e.logModelRouteMiss(requestID, query) - return Item{}, NewExecutionError(Classified{ - Kind: accounts.KindModelNotAvailable, Status: http.StatusBadRequest, - Code: "model_not_available", Type: "invalid_request_error", Failover: false, - Message: fmt.Sprintf("model_not_available: %s is not available for the selected accounts", publicModel), - }, nil) - } - } - } - if len(allowed) > 0 && providerFilter != "" && !accounts.ProviderAllowed(providerFilter, allowed) { - return Item{}, NewExecutionError(Classified{ - Kind: accounts.KindAuth, Status: http.StatusForbidden, Code: "provider_not_allowed", - Type: "permission_error", Failover: false, - Message: fmt.Sprintf("api key cannot use provider %s", providerFilter), - }, nil) - } - if providerFilter != "" && regionFilter != "" { - return Item{}, noAccountsError(fmt.Sprintf("no %s/%s accounts available", providerFilter, regionFilter)) - } - if providerFilter != "" { - // A key whose grant list narrows this family to a single region - // should fail with that region in the message, even when the - // request itself did not pin one. - if regionFilter, narrowed := keyGrantedSingleRegion(providerFilter, allowed); narrowed { - return Item{}, noAccountsError(fmt.Sprintf("no %s/%s accounts available", providerFilter, regionFilter)) - } - return Item{}, noAccountsError(fmt.Sprintf("no %s accounts available", providerFilter)) - } - if len(allowed) > 0 { - return Item{}, noAccountsError("no accounts available for this api key") - } - return Item{}, NewExecutionError(Classified{ - Kind: accounts.KindUnavailable, Status: http.StatusServiceUnavailable, - Code: "no_accounts_configured", Type: "api_error", Failover: false, - Message: "no worker accounts configured", - }, nil) -} - // noAccountsRetryAfter mirrors runtime's workerReconcileInterval: the liveness // watchdog re-probes an unready worker at most once per this interval, so a // retry before then cannot observe a recovery and would just repeat the miss. @@ -555,7 +442,7 @@ func quotaBlockedMessage(publicModel string) string { return "all accounts are out of quota" } -func coolingPickError(item Item, publicModel string, retryAfter time.Duration) error { +func coolingPickError(item Item, publicModel, modelKey string, retryAfter time.Duration) error { failover := true kind := accounts.KindRateLimit code := "rate_limit" @@ -573,7 +460,7 @@ func coolingPickError(item Item, publicModel string, retryAfter time.Duration) e message = "all accounts are on quota cooldown" } } else if strings.TrimSpace(publicModel) != "" { - if until, ok := item.ModelDownUntil[accounts.CanonicalModelID(publicModel)]; ok && !until.IsZero() { + if until, ok := item.ModelDownUntil[modelKey]; ok && !until.IsZero() { message = fmt.Sprintf("model %s is cooling down on all available accounts", publicModel) } } @@ -608,13 +495,6 @@ func (e ChatExecutor) attemptsFor(providerFilter, regionFilter, publicModel stri return 1 } -func pinRegion(current, next string) string { - if current != "" { - return current - } - return accounts.NormalizeRegion(next) -} - // keyGrantedSingleRegion inspects an API key allowlist for one provider // family. It returns the single region the grants narrow the family to, with // narrowed=true. A bare family entry or an empty allowlist means every region @@ -663,7 +543,7 @@ func (e ChatExecutor) ObserveStreamFailure(accountID string, err error, model st if e.Pool == nil || accountID == "" || err == nil || requestContextDone(nil, err) { return } - classified := e.classifyInProcessError(err) + classified := ClassifyError(err) if classified.Kind == "" || classified.Kind == accounts.KindCanceled { return } @@ -696,90 +576,75 @@ type replayReadCloser struct { io.Closer } -// probeStreamBody waits for the first event of an upstream stream. Nothing has -// been sent to the client yet at this point, so a stream that dies or reports -// an error before the first event can still fail over to another account. -// Blank lines and comments (: keep-alive) are skipped; the bytes read while -// probing are replayed so the relay sees the stream from the first byte. -// The returned Classified is only meaningful when err != nil. A read that -// fails because the caller's request was canceled returns that context error, -// so the caller can report KindCanceled instead of treating the account as -// healthy. A body that merely wraps a context error while the request is still -// alive is an upstream failure and fails over. -func probeStreamBody(ctx context.Context, body io.ReadCloser) (io.ReadCloser, Classified, error) { +// probeStreamBody examines the first complete SSE event before anything is +// exposed. SSE can span multiple data lines; deciding on the first line can +// turn a retryable error into an already-committed stream. +func probeStreamBody(body io.ReadCloser) (io.ReadCloser, Classified, error) { if body == nil { return nil, Classify(0, errEmptyStream.Error(), "", accounts.KindUnavailable, ""), errEmptyStream } reader := bufio.NewReaderSize(body, 64*1024) var consumed bytes.Buffer - eventName := "" + var fieldData []string + var eventName string + var lineStart int + replay := func() io.ReadCloser { + return &replayReadCloser{Reader: io.MultiReader(&consumed, reader), Closer: body} + } for { - line, err := reader.ReadString('\n') - if line != "" { - consumed.WriteString(line) - text := strings.TrimSpace(strings.TrimRight(line, "\r\n")) - switch { - case text == "", strings.HasPrefix(text, ":"): - // Frame separator or keep-alive comment: keep waiting. - case strings.HasPrefix(text, "event:"): - eventName = strings.TrimSpace(strings.TrimPrefix(text, "event:")) - case strings.HasPrefix(text, "data:"): - data := strings.TrimSpace(strings.TrimPrefix(text, "data:")) - if classified, failed := probeFrameFailure(eventName, data); failed { - body.Close() - return nil, classified, fmt.Errorf("upstream stream failed before the first event: %s", classified.Message) - } - return &replayReadCloser{Reader: io.MultiReader(&consumed, reader), Closer: body}, Classified{}, nil - default: - // Non-SSE payload: let the relay surface it unchanged. - return &replayReadCloser{Reader: io.MultiReader(&consumed, reader), Closer: body}, Classified{}, nil - } + part, err := reader.ReadSlice('\n') + if consumed.Len()+len(part) > maxWorkerResponseBytes { + body.Close() + err := fmt.Errorf("upstream stream exceeded %d bytes before its first event", maxWorkerResponseBytes) + return nil, Classify(0, err.Error(), "", accounts.KindUnavailable, ""), err + } + consumed.Write(part) + if err == bufio.ErrBufferFull { + continue } - if err != nil { - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - // A context error is not an account failure. Hand back what was - // already read and let the relay decide: a canceled request is - // reported as a cancellation, and a body that wrapped - // context.Canceled while the request is still alive replays - // through the relay, which fails over without a pre-stream 502. - return &replayReadCloser{Reader: io.MultiReader(&consumed, reader), Closer: body}, Classified{}, nil + line := strings.TrimRight(string(consumed.Bytes()[lineStart:]), "\r\n") + lineStart = consumed.Len() + blank := strings.TrimSpace(line) == "" + field, value, _ := strings.Cut(line, ":") + switch { + case blank || field == "" || field == "id" || field == "retry": + case field == "event": + eventName = strings.TrimSpace(value) + case field == "data": + fieldData = append(fieldData, strings.TrimPrefix(value, " ")) + default: + // Compatibility: leave non-SSE responses to the relay. + return replay(), Classified{}, nil + } + if blank || err != nil { + data := strings.Join(fieldData, "\n") + if failure := ClassifyStreamEvent(eventName, data); failure != nil { + body.Close() + classified := ClassifyError(failure) + return nil, classified, fmt.Errorf("upstream stream failed before the first event: %w", failure) } - body.Close() - if errors.Is(err, io.EOF) { - return nil, Classify(0, errEmptyStream.Error(), "", accounts.KindUnavailable, ""), errEmptyStream + if strings.TrimSpace(data) != "" { + return replay(), Classified{}, nil } - return nil, Classify(0, err.Error(), "", accounts.KindUnavailable, ""), err + eventName = "" + fieldData = fieldData[:0] } + if err == nil { + continue + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + // Preserve the relay contract: context sentinels in an accepted + // response body surface as stream cancellation, not account health. + return replay(), Classified{}, nil + } + body.Close() + if errors.Is(err, io.EOF) { + return nil, Classify(0, errEmptyStream.Error(), "", accounts.KindUnavailable, ""), errEmptyStream + } + return nil, Classify(0, err.Error(), "", accounts.KindUnavailable, ""), err } } -// probeFrameFailure recognizes an SSE error frame, such as the structured -// "event: error" the worker emits when the upstream dies before streaming any -// token. Content frames (the ones carrying choices) are not failures. -func probeFrameFailure(eventName, data string) (Classified, bool) { - if data == "" { - return Classified{}, false - } - var payload map[string]any - if json.Unmarshal([]byte(data), &payload) != nil { - return Classified{}, false - } - if _, ok := payload["choices"]; ok { - return Classified{}, false - } - status := 0 - if value, ok := payload["status"].(float64); ok { - status = int(value) - } - if _, ok := payload["error"]; ok { - return Classify(status, data, "", "", ""), true - } - if strings.EqualFold(eventName, "error") { - return Classify(status, data, "", "", ""), true - } - return Classified{}, false -} - func (e ChatExecutor) handleModelAvailabilityFailure(requestID, source, accountID, model string, classified Classified) { if e.Pool == nil || accountID == "" { return @@ -826,16 +691,6 @@ func (e ChatExecutor) markClassified(id string, c Classified, model string) { e.Pool.MarkClassified(id, c) } -// markOK records a success scoped to the requested public model so a 200 -// on one model does not discard a cooldown recorded for another. Pass an -// empty model for a true account-level recovery. -func (e ChatExecutor) markOK(id, model string) { - if e.Pool == nil { - return - } - e.Pool.MarkOK(id, e.cooldownModel(id, model)) -} - // cooldownModel records the account's real catalog model when the client // used that account's alias, so the alias and the real name share one cooldown. func (e ChatExecutor) cooldownModel(id, model string) string { @@ -849,6 +704,30 @@ func (e ChatExecutor) cooldownModel(id, model string) string { return AccountModelID(item, model) } +type attemptKindKey struct{} + +const ( + AttemptKindRoute = "route" + AttemptKindClassifier = "classifier" +) + +// WithAttemptKind marks a nested dispatch (the aggregation intent classifier) +// so its attempt row is distinguishable from the main routed attempt. +func WithAttemptKind(ctx context.Context, kind string) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, attemptKindKey{}, kind) +} + +func attemptKindFromContext(ctx context.Context) string { + if ctx == nil { + return "" + } + kind, _ := ctx.Value(attemptKindKey{}).(string) + return kind +} + func (e ChatExecutor) recordAttempt(ctx context.Context, attempt accounts.RequestAttempt) { if e.OnAttempt == nil { return @@ -862,6 +741,12 @@ func (e ChatExecutor) recordAttempt(ctx context.Context, attempt accounts.Reques if attempt.RequestID == "" { return } + if attempt.AttemptKind == "" { + attempt.AttemptKind = attemptKindFromContext(ctx) + } + if attempt.AttemptKind == "" { + attempt.AttemptKind = AttemptKindRoute + } e.OnAttempt(attempt) } @@ -933,332 +818,6 @@ func classifyWorkerErr(resp *http.Response, body string) Classified { return Classify(status, body, retryAfter, kind, failover) } -type routeLoop struct { - requestID string - prefer string - providerFilter string - regionFilter string - routing routingPlan - excluded map[string]struct{} - lastErr error - allowed []string - attempts int - pinned string - index int - // regionPinned records that this request chose its region implicitly from - // the first picked account (not from a model prefix, grant, or explicit - // pin). A later failure releases that pin so failover can cross regions. - regionPinned bool - // eligible narrows candidates to one protocol capability; nil admits all. - eligible func(Item) bool - // resolver maps an item to its concrete aggregated model. Nil for normal - // (non-aggregated) requests. Pure and read-only; safe under Pool.mu. - resolver func(Item) string - // plan is the immutable per-request aggregate plan; nil for normal routes. - // It carries the per-model strategy/weights used by Pool.PickRoute. - plan *AggregatePlan - // tierAttempts and tierBudget apply only to priority aggregation. Each - // priority tier gets its own budget, so sibling accounts of the first - // provider cannot consume every retry before a lower-priority provider is - // reached. When a tier is exhausted its remaining accounts are added to - // excluded. - tierAttempts map[int]int - tierBudget int -} - -func (e ChatExecutor) newRouteLoop(ctx context.Context, prefer, providerFilter string, req translate.ChatRequest) routeLoop { - aggPlan := aggregatePlanFrom(ctx) - prefer, providerFilter, regionFilter, routing := e.prepareRouting(ctx, prefer, providerFilter, req, aggPlan) - allowed := allowedProvidersFrom(ctx) - // Capture the aggregate resolver once from the immutable per-request plan. - // If a plan exists, the public model is virtual and must not be pinned by a - // provider prefix; the plan's members already carry provider/region. - var resolver func(Item) string - if aggPlan != nil { - resolver = aggPlan.resolver() - providerFilter, regionFilter = "", "" - switch routing.Source { - case routingSticky: - // Keep the cache-affine binding. The public ID is virtual, so the - // account was already validated against the plan's members in - // prepareRouting; prefer selects it without re-imposing a provider. - prefer = routing.BoundAccount - case routingPin: - // An explicit pin is useful only when the pinned account can serve - // a member of this logical model. - if e.Pool != nil { - if pinned, ok := e.Pool.ByID(prefer); ok && aggPlan.CanServeAccount(pinned) { - break - } - } - prefer = "" - routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model} - default: - prefer = "" - routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model} - } - } - // A model-name region prefix (e.g. "workbuddy-cn/model") sets an explicit - // region that overrides sticky-session and pin-derived regions. It - // coexists with key grants: routeBaseMatches enforces both filters - // independently, so a prefix that conflicts with a grant yields no - // candidates and a clean error. - if modelRegion := regionFilterFromContext(ctx); modelRegion != "" { - regionFilter = modelRegion - } else if providerFilter != "" { - // A key whose grants narrow the selected family to exactly one region - // pre-seeds the region filter: scheduling never even considers accounts - // of other regions — including a pin to an out-of-grant account (the - // grant overrides the pinned account's region, so the pin falls back - // into the granted region) and every failover hop. - if granted, narrowed := keyGrantedSingleRegion(providerFilter, allowed); narrowed { - regionFilter = granted - } - } - if aggPlan == nil && regionFilter == "" && prefer != "" && e.Pool != nil { - if pinnedItem, ok := e.Pool.ByID(prefer); ok { - regionFilter = pinRegion("", pinnedItem.Region) - } - } - // Per-model failover settings win over the executor global attempt budget. - // AllowFallbacks=false means the single best account only; MaxAttempts caps - // how many distinct accounts/members may be tried for one logical model. - // - // Keep aggregated routes at the same single candidate scan as normal routes: - // attemptsFor already does that scan, so a plan must not call attemptsFor and - // then LenRoute again. Only count candidates here when failover is possible. - var attempts int - var tierBudget int - if aggPlan != nil { - attempts = aggPlan.MaxAttempts - if attempts <= 0 { - attempts = 1 - } - if !aggPlan.AllowFallbacks { - attempts = 1 - } else if aggPlan.Strategy == accounts.AggregationPriority { - // LiteLLM-style ordered fallback: each order tier gets its own - // retry budget before escalating to the next tier. A global budget - // would otherwise be spent entirely on sibling accounts of the - // first provider when MaxAttempts is smaller than that provider's - // account count. - tierBudget = attempts - attempts *= aggPlan.PriorityTierCount() - if e.Pool != nil { - query := e.routeQuery("", providerFilter, regionFilter, req.Model, allowed, nil, nil, aggPlan) - if n := e.Pool.LenRoute(query); n > 0 && n < attempts { - attempts = n - } - } - } else if e.Pool != nil { - query := e.routeQuery("", providerFilter, regionFilter, req.Model, allowed, nil, nil, aggPlan) - if n := e.Pool.LenRoute(query); n > 0 && n < attempts { - attempts = n - } - } - } else { - attempts = e.attemptsFor(providerFilter, regionFilter, req.Model, allowed, nil) - } - loop := routeLoop{ - requestID: RequestIDFromContext(ctx), - prefer: prefer, - providerFilter: providerFilter, - regionFilter: regionFilter, - routing: routing, - excluded: map[string]struct{}{}, - allowed: allowed, - resolver: resolver, - plan: aggPlan, - attempts: attempts, - } - if tierBudget > 0 { - loop.tierAttempts = make(map[int]int) - loop.tierBudget = tierBudget - } - if routing.Source == routingPin { - loop.pinned = prefer - } - return loop -} - -func (l *routeLoop) pickNext(e ChatExecutor, publicModel string) (Item, int, error) { - item, err := e.pick(l.requestID, l.prefer, l.providerFilter, l.regionFilter, publicModel, l.allowed, l.excluded, l.eligible, l.plan) - if err != nil { - // Sticky routing pins the bound provider and region before this pick. - // A capacity check made before the pick races the slot: another request - // can fill the last one in between, and the pin then turns a full - // provider into rate_limit while another provider still has room. - // Drop the pin only after the pick itself reports saturation, and only - // when this request did not ask for that provider. - if l.routing.Source == routingSticky && l.index == 0 && l.pinned == "" && capacityError(err) && e.providerHasCapacity(l.providerFilter, l.regionFilter, publicModel, l.allowed, l.eligible) { - if e.SessionAffinity != nil { - e.SessionAffinity.RecordEscape("concurrency_saturated") - } - l.routing.Source = routingPool - l.prefer = "" - l.providerFilter = "" - l.regionFilter = "" - l.regionPinned = false - l.attempts = e.attemptsFor(l.providerFilter, l.regionFilter, publicModel, l.allowed, l.eligible, l.resolver) - item, err = e.pick(l.requestID, l.prefer, l.providerFilter, l.regionFilter, publicModel, l.allowed, l.excluded, l.eligible, l.plan) - } - if err != nil { - return Item{}, l.index, err - } - } - attemptIndex := l.index - e.observeRouting(&l.routing, item.ID) - l.prefer = "" - // Pin the first pick's region so a mixed-region pool does not flip regions - // while rotating within one request. The attempt budget was computed over - // every eligible candidate before this pick and must not shrink here: - // shrinking it to the pinned region's account count can leave a failed - // request with no failover hop at all, even though another provider or - // region is healthy. A failure releases the pin in exclude/failover. - if l.plan == nil && l.regionFilter == "" { - l.regionFilter = pinRegion(l.regionFilter, item.Region) - l.regionPinned = true - } - l.index++ - return item, attemptIndex, nil -} - -// attemptModel returns the concrete model used for this item. It is the -// resolved real model for aggregated requests, otherwise the public model. -// Cooldowns must be recorded against this value so different providers/models -// behind one virtual ID do not share a cooldown. -func (l routeLoop) attemptModel(item Item, req translate.ChatRequest) string { - if l.resolver != nil { - if model := l.resolver(item); model != "" { - return model - } - } - return req.Model -} - -// dispatchRequest returns the request for this attempt with an aggregated -// virtual model resolved to the concrete model chosen for this item. It only -// touches the local copy of the request; the shared Item is never modified. -func (l routeLoop) dispatchRequest(item Item, req translate.ChatRequest) translate.ChatRequest { - req.Model = l.attemptModel(item, req) - return req -} - -func (l routeLoop) canFailover(classified Classified) bool { - return classified.Failover && l.index < l.attempts -} - -func (l *routeLoop) exclude(item Item) { - l.excluded[item.ID] = struct{}{} - // A cross-provider route (no explicit provider filter) must be able to - // leave the region its first pick happened to choose; otherwise a bare - // model shared by several providers stays pinned to one supplier. - // - // A provider-scoped route keeps its region pin: Qoder global and CN are - // isolated upstreams (different catalogs/quota pools), and existing - // behavior explicitly forbids global -> CN failover. Aggregated routes - // carry their own provider/region per member and never pin here. - if l.regionPinned && l.providerFilter == "" { - l.regionFilter = "" - l.regionPinned = false - } -} - -// failover records an upstream failure and excludes the account. On a -// cross-provider route exclude also releases the implicit region pin, so the -// next pick can leave the first supplier's region. Provider-scoped routes keep -// their region pin. -// -// A sticky binding is invalidated on failover (401/429/5xx and other -// failover-classified failures), including after a sticky escape. The next -// request then rebinds to a healthy account instead of retrying the dead one -// first; a successfully retried request rebinds through bindSession. This -// mirrors mature gateways' session affinity: sticky on the cache-hit path, -// failover invalidates the binding. -func (l *routeLoop) failover(e ChatExecutor, item Item) { - l.exclude(item) - l.noteTierFailure(e, item) - // Any non-pin route that already carries a session key can have a stale - // binding (including a sticky-escape that started on another account). - // Invalidate it so the next turn does not retry the failed account first. - if l.routing.Source != routingPin && l.routing.SessionKey != "" && e.SessionAffinity != nil { - e.SessionAffinity.Forget(l.routing.SessionKey) - } -} - -// noteTierFailure gives each priority tier its own retry budget. Once the -// budget is consumed, the remaining accounts in that tier are excluded so the -// next pick can reach a lower-priority provider instead of retrying every -// sibling account of the same provider. -func (l *routeLoop) noteTierFailure(e ChatExecutor, item Item) { - if l.plan == nil || l.plan.Strategy != accounts.AggregationPriority || l.tierAttempts == nil || e.Pool == nil { - return - } - tier, ok := l.plan.Priority(item) - if !ok { - return - } - l.tierAttempts[tier]++ - if l.tierAttempts[tier] < l.tierBudget { - return - } - for _, candidate := range e.Pool.Items() { - if candidateTier, ok := l.plan.Priority(candidate); ok && candidateTier == tier { - l.excluded[candidate.ID] = struct{}{} - } - } -} - -func (l routeLoop) headerAccount(item Item, attemptIndex int) string { - if attemptIndex == 0 && l.pinned != "" { - return l.pinned - } - return item.ID -} - -func (l routeLoop) resultProvider(item Item) string { - return firstNonEmpty(item.Provider, "qoder") -} - -func (l routeLoop) pickFailure(err error) (int, string, string, error) { - if l.lastErr != nil { - return l.index, lastAccountID(l.excluded), l.providerFilter, l.lastErr - } - return 0, "", "", err -} - -// releaseCloser runs release exactly once when the body is closed, so a -// successful stream keeps its Acquire until the caller finishes reading. -type releaseCloser struct { - io.ReadCloser - once sync.Once - release func() -} - -func (c *releaseCloser) Close() error { - err := c.ReadCloser.Close() - if c.release != nil { - c.once.Do(c.release) - } - return err -} - -func (e ChatExecutor) acquireInFlight(requestID, id string) bool { - if e.Pool == nil { - if e.OnInFlightAcquire != nil && requestID != "" && id != "" { - e.OnInFlightAcquire(requestID, id) - } - return true - } - if !e.Pool.Acquire(id) { - return false - } - if e.OnInFlightAcquire != nil && requestID != "" { - e.OnInFlightAcquire(requestID, id) - } - return true -} - func (e ChatExecutor) releaseInFlight(requestID, id string) { if e.Pool != nil { e.Pool.Release(id) @@ -1268,342 +827,18 @@ func (e ChatExecutor) releaseInFlight(requestID, id string) { } } -// attachInFlightRelease transfers an acquired slot to the response body. -// Close releases the pool id that was Acquired (not a rewritten account id). -func (e ChatExecutor) attachInFlightRelease(resp *http.Response, requestID, poolID string) *http.Response { - if resp == nil || resp.Body == nil { - e.releaseInFlight(requestID, poolID) - return resp - } - resp.Body = &releaseCloser{ReadCloser: resp.Body, release: func() { e.releaseInFlight(requestID, poolID) }} - return resp -} - -func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result ChatResult, returnErr error) { - loop := e.newRouteLoop(ctx, prefer, providerFilter, req) - defer func() { result.Routing = loop.routing.Source }() - for loop.index < loop.attempts { - item, i, err := loop.pickNext(e, req.Model) - if err != nil { - attempts, accountID, provider, pickErr := loop.pickFailure(err) - if loop.lastErr != nil { - return ChatResult{AttemptCount: attempts, AccountID: accountID, Provider: provider}, pickErr - } - return ChatResult{}, pickErr - } - // Acquire with the pool id before any rewrite of item.ID (X-Qoder-Account). - poolID := item.ID - if !e.acquireInFlight(loop.requestID, poolID) { - loop.exclude(item) - continue - } - release := func() { e.releaseInFlight(loop.requestID, poolID) } - if isInProcessItem(item) || e.qoderDirect(item) { - result, classified, err := e.chatInProcessNonStreamAttempt(ctx, item, loop.dispatchRequest(item, req), i) - if err == nil { - result.AttemptCount = i + 1 - e.observeRouting(&loop.routing, poolID) - // Bind the pool account, not the upstream-reported label. A - // worker response may rewrite X-Qoder-Account, but session - // affinity and future Pool.ByID lookups are keyed by the pool ID. - e.bindSession(loop.routing, poolID) - release() - return result, nil - } - loop.lastErr = err - if requestContextDone(ctx, err) { - release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - if loop.canFailover(classified) { - release() - loop.failover(e, item) - continue - } - release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - payload, err := json.Marshal(buildWorkerChatPayload(sanitizeForItem(item, loop.dispatchRequest(item, req)), false)) - if err != nil { - release() - return ChatResult{}, err - } - headerAccount := loop.headerAccount(item, i) - httpReq, err := e.newWorkerRequest(ctx, item, payload, headerAccount) - if err != nil { - release() - return ChatResult{}, err - } - started := time.Now() - resp, err := e.HTTPClient.Do(httpReq) - if err != nil { - if requestContextDone(ctx, err) { - latency := int(time.Since(started).Milliseconds()) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: ptrTime(time.Now().UTC()), - Status: accounts.AttemptStatusError, ErrorKind: accounts.KindUnavailable, ErrorMessage: err.Error(), LatencyMs: &latency, - }) - release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - classified := Classify(0, err.Error(), "", accounts.KindUnavailable, "") - loop.lastErr = NewExecutionError(classified, fmt.Errorf("worker %s request failed: %w", item.ID, err)) - e.markClassified(item.ID, classified, loop.attemptModel(item, req)) - latency := int(time.Since(started).Milliseconds()) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: ptrTime(time.Now().UTC()), - Status: accounts.AttemptStatusFailover, ErrorKind: classified.Kind, ErrorMessage: loop.lastErr.Error(), LatencyMs: &latency, - }) - release() - loop.failover(e, item) - continue - } - // Non-stream worker responses are buffered whole; cap them so a - // pathological upstream cannot pin unbounded memory per request. - body, _ := io.ReadAll(io.LimitReader(resp.Body, maxWorkerResponseBytes)) - resp.Body.Close() - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - if account := resp.Header.Get("X-Qoder-Account"); account != "" { - item.ID = account - } - poolItem := item - poolItem.ID = poolID - if resp.StatusCode >= 300 { - msg := strings.TrimSpace(string(body)) - classified := classifyWorkerErr(resp, msg) - loop.lastErr = NewExecutionError(classified, nil) - if classified.Kind == accounts.KindModelNotAvailable { - e.handleModelAvailabilityFailure(RequestIDFromContext(ctx), "worker_non_stream", poolID, loop.attemptModel(item, req), classified) - } - e.markClassified(poolID, classified, loop.attemptModel(item, req)) - status := accounts.AttemptStatusError - if loop.canFailover(classified) { - status = accounts.AttemptStatusFailover - loop.failover(e, poolItem) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(msg), LatencyMs: &latency, - }) - release() - continue - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(msg), LatencyMs: &latency, - }) - release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, loop.lastErr - } - result, err := decodeChatResult(req, body) - if err != nil { - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: accounts.AttemptStatusError, HTTPStatus: ptrInt(resp.StatusCode), - ErrorKind: accounts.KindUnavailable, ErrorMessage: truncateErr(err.Error()), LatencyMs: &latency, - }) - release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, err - } - result.AccountID = item.ID - result.Provider = loop.resultProvider(item) - result.AttemptCount = i + 1 - result.ReasoningLevel = RequestedReasoningLevel(req) - if result.ReasoningLevel != "" { - logResolvedReasoning(ctx, "chat_non_stream", item, req.Model, result.ReasoningLevel) - } - e.observeRouting(&loop.routing, poolID) - e.bindSession(loop.routing, poolID) - e.markOK(poolID, loop.attemptModel(item, req)) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: accounts.AttemptStatusOK, HTTPStatus: ptrInt(resp.StatusCode), LatencyMs: &latency, - PromptTokens: ptrInt(result.PromptTokens), CompletionTokens: ptrInt(result.CompletionTokens), - UsageSource: result.UsageSource, - }) - release() - return result, nil - } - if loop.lastErr == nil { - loop.lastErr = fmt.Errorf("no worker accounts available") - } - return ChatResult{AttemptCount: loop.attempts}, loop.lastErr +// sanitizeForItem also resolves the native spelling for explicit probes. +func sanitizeForItem(item Item, req translate.ChatRequest) translate.ChatRequest { + return targetFor(item, req.Model).request(req) } -// sanitizeForItem applies the account-level system-prompt policy. Provider -// families with upstream content screening (WorkBuddy) strip caller system -// prompts when the account opts in; Qoder workers intentionally preserve them. -// WorkBuddy still needs a leading system slot after the strip (code 11128); -// the adapter inserts an empty placeholder, this helper only drops caller text. -func sanitizeForItem(item Item, req translate.ChatRequest) translate.ChatRequest { - req.Model = AccountModelID(item, req.Model) - if native := NativeModelID(item, req.Model); native != "" { - req.Model = native - } +func sanitizeChatForItem(item Item, req translate.ChatRequest) translate.ChatRequest { if item.DropSystemPrompt && itemProvider(item) != "qoder" { - return translate.DropSystemMessages(req) + req = translate.DropSystemMessages(req) } return req } -func (e ChatExecutor) chatInProcessNonStreamAttempt(ctx context.Context, item Item, req translate.ChatRequest, attemptIndex int) (ChatResult, Classified, error) { - adapter, _ := e.Providers.Get(itemProvider(item)) - if adapter.Chat == nil { - return ChatResult{}, Classified{}, fmt.Errorf("provider %s does not implement chat", item.Provider) - } - started := time.Now() - outcome, err := adapter.Chat.ChatNonStream(ctx, item.ID, sanitizeForItem(item, req)) - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - if err == nil { - logResolvedReasoning(ctx, "chat_non_stream", item, req.Model, outcome.ReasoningLevel) - } - if err != nil { - if requestContextDone(ctx, err) { - return ChatResult{AccountID: item.ID, Provider: item.Provider}, Classified{Kind: accounts.KindUnavailable, Message: err.Error()}, err - } - classified := e.classifyInProcessError(err) - if classified.Kind == accounts.KindModelNotAvailable { - e.handleModelAvailabilityFailure(RequestIDFromContext(ctx), "provider_non_stream", item.ID, req.Model, classified) - } - e.markClassified(item.ID, classified, req.Model) - status := accounts.AttemptStatusError - if classified.Failover { - status = accounts.AttemptStatusFailover - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: attemptIndex, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, ErrorKind: classified.Kind, ErrorMessage: truncateErr(err.Error()), LatencyMs: &latency, - }) - return ChatResult{AccountID: item.ID, Provider: item.Provider}, classified, NewExecutionError(classified, err) - } - e.markOK(item.ID, req.Model) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: attemptIndex, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: accounts.AttemptStatusOK, LatencyMs: &latency, - PromptTokens: ptrInt(outcome.PromptTokens), CompletionTokens: ptrInt(outcome.CompletionTokens), - UsageSource: outcome.UsageSource, - }) - return ChatResult{ - Model: outcome.Model, - Content: outcome.Content, - Reasoning: outcome.Reasoning, - ToolCalls: outcome.ToolCalls, - FinishReason: outcome.FinishReason, - PromptTokens: outcome.PromptTokens, - CompletionTokens: outcome.CompletionTokens, - CacheReadTokens: outcome.CacheReadTokens, - CacheWriteTokens: outcome.CacheWriteTokens, - CachedTokens: outcome.CacheReadTokens, - UsageSource: outcome.UsageSource, - ConsumedCredits: outcome.Credits, - AccountID: item.ID, - Provider: item.Provider, - ReasoningLevel: outcome.ReasoningLevel, - }, Classified{}, nil -} - -func (e ChatExecutor) chatInProcessStreamAttempt(ctx context.Context, item Item, req translate.ChatRequest, native *translate.NativeResponsesRequest, attemptIndex int, preferNativeResponses bool) (StreamResult, Classified, error) { - adapter, ok := e.Providers.Get(itemProvider(item)) - if !ok { - return StreamResult{}, Classified{}, fmt.Errorf("provider %s is not registered", item.Provider) - } - if !preferNativeResponses && adapter.Chat == nil { - return StreamResult{}, Classified{}, fmt.Errorf("provider %s does not implement chat", item.Provider) - } - if preferNativeResponses && native != nil && adapter.NativeResponses == nil { - return StreamResult{}, Classified{}, providers.ErrUnsupported - } - started := time.Now() - var resp *http.Response - var resolved providers.ResolvedChat - var err error - nativeResponses := false - if preferNativeResponses && native != nil && adapter.NativeResponses != nil { - options := providers.RequestOptions{ - Model: NativeModelID(item, AccountModelID(item, req.Model)), - DropSystemPrompt: item.DropSystemPrompt && itemProvider(item) != "qoder", - } - resp, resolved, err = adapter.NativeResponses.ResponsesStream(ctx, item.ID, native, options) - nativeResponses = err == nil - } else { - resp, resolved, err = adapter.Chat.ChatStream(ctx, item.ID, sanitizeForItem(item, req)) - } - if err == nil { - logResolvedReasoning(ctx, "chat_stream", item, req.Model, resolved.ReasoningLevel) - } - if err != nil { - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - if errors.Is(err, providers.ErrUnsupported) { - return StreamResult{AccountID: item.ID, Provider: item.Provider}, Classified{Kind: accounts.KindInvalidRequest, Message: err.Error()}, err - } - if requestContextDone(ctx, err) { - - return StreamResult{AccountID: item.ID, Provider: item.Provider}, Classified{Kind: accounts.KindUnavailable, Message: err.Error()}, err - } - classified := e.classifyInProcessError(err) - if classified.Kind == accounts.KindModelNotAvailable { - e.handleModelAvailabilityFailure(RequestIDFromContext(ctx), "provider_stream", item.ID, req.Model, classified) - } - e.markClassified(item.ID, classified, req.Model) - status := accounts.AttemptStatusError - if classified.Failover { - status = accounts.AttemptStatusFailover - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: attemptIndex, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, ErrorKind: classified.Kind, ErrorMessage: truncateErr(err.Error()), LatencyMs: &latency, - }) - return StreamResult{AccountID: item.ID, Provider: item.Provider}, classified, NewExecutionError(classified, err) - } - probed, probeClassified, probeErr := probeStreamBody(ctx, resp.Body) - if probeErr != nil { - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - if requestContextDone(ctx, probeErr) { - // The client went away before the first event. Report the - // cancellation and leave the account's cooldown untouched. - classified := ClassifyError(probeErr) - return StreamResult{AccountID: item.ID, Provider: item.Provider}, classified, NewExecutionError(classified, probeErr) - } - classified := probeClassified - if classified.Kind == "" { - classified = Classify(0, probeErr.Error(), "", accounts.KindUnavailable, "") - } - e.markClassified(item.ID, classified, req.Model) - status := accounts.AttemptStatusError - if classified.Failover { - status = accounts.AttemptStatusFailover - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: attemptIndex, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, ErrorKind: classified.Kind, ErrorMessage: truncateErr(probeErr.Error()), LatencyMs: &latency, - }) - return StreamResult{AccountID: item.ID, Provider: item.Provider}, classified, NewExecutionError(classified, probeErr) - } - resp.Body = probed - e.markOK(item.ID, req.Model) - ttfb := int(time.Since(started).Milliseconds()) - headerAt := time.Now().UTC() - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: attemptIndex, AccountID: item.ID, StartedAt: started, FinishedAt: &headerAt, - Status: accounts.AttemptStatusOK, HTTPStatus: ptrInt(http.StatusOK), LatencyMs: &ttfb, - }) - return StreamResult{Response: resp, AccountID: item.ID, PoolAccountID: item.ID, Provider: item.Provider, TTFBMs: ttfb, ReasoningLevel: resolved.ReasoningLevel, NativeResponses: nativeResponses}, Classified{}, nil -} - -func (e ChatExecutor) classifyInProcessError(err error) Classified { return ClassifyError(err) } - -func lastAccountID(excluded map[string]struct{}) string { - for id := range excluded { - return id - } - return "" -} - func firstNonEmpty(vals ...string) string { for _, v := range vals { if strings.TrimSpace(v) != "" { @@ -1723,267 +958,6 @@ func (e ChatExecutor) streamHTTPClient() *http.Client { return client } -func (e ChatExecutor) ChatStreamProxy(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (result StreamResult, returnErr error) { - return e.chatStreamProxy(ctx, req, nil, prefer, providerFilter, false) -} - -// ChatStreamProxyNativeResponses sends the original Responses request to a -// native-capable adapter. Once this path starts, retries remain native-only. -func (e ChatExecutor) ChatStreamProxyNativeResponses(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (result StreamResult, returnErr error) { - return e.chatStreamProxy(ctx, req, native, prefer, providerFilter, true) -} - -func (e ChatExecutor) NativeResponsesNonStream(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (result NativeResponseResult, returnErr error) { - upstream, err := e.ChatStreamProxyNativeResponses(ctx, req, native, prefer, providerFilter) - if err != nil { - return NativeResponseResult{AccountID: upstream.AccountID, Provider: upstream.Provider, AttemptCount: upstream.AttemptCount, Routing: upstream.Routing, ReasoningLevel: upstream.ReasoningLevel}, err - } - if upstream.Response == nil || upstream.Response.Body == nil { - return NativeResponseResult{AccountID: upstream.AccountID, Provider: upstream.Provider, AttemptCount: upstream.AttemptCount, Routing: upstream.Routing, ReasoningLevel: upstream.ReasoningLevel}, fmt.Errorf("native responses upstream returned no body") - } - defer upstream.Response.Body.Close() - collected, err := translate.CollectResponses(upstream.Response.Body) - result = NativeResponseResult{ - Response: collected.Response, AccountID: upstream.AccountID, Provider: upstream.Provider, - AttemptCount: upstream.AttemptCount, Routing: upstream.Routing, ReasoningLevel: upstream.ReasoningLevel, - FinishReason: collected.FinishReason, PromptTokens: collected.InputTokens, - OutputTokens: collected.OutputTokens, CachedTokens: collected.CachedTokens, - } - if err != nil { - e.ObserveStreamFailure(poolAccountID(upstream), err, req.Model) - return result, err - } - e.CommitSession(ctx, req, upstream.Routing, poolAccountID(upstream)) - return result, nil -} - -func poolAccountID(result StreamResult) string { - if strings.TrimSpace(result.PoolAccountID) != "" { - return result.PoolAccountID - } - return result.AccountID -} - -func (e ChatExecutor) HasNativeResponsesRoute(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) bool { - if e.Providers == nil { - return false - } - loop := e.newRouteLoop(ctx, prefer, providerFilter, req) - loop.eligible = func(item Item) bool { - adapter, ok := e.Providers.Get(itemProvider(item)) - return ok && adapter.NativeResponses != nil - } - if e.Pool == nil { - return false - } - query := e.routeQuery(loop.prefer, loop.providerFilter, loop.regionFilter, req.Model, loop.allowed, nil, loop.eligible, loop.plan) - return e.Pool.LenRoute(query) > 0 -} - -func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string, preferNativeResponses bool) (result StreamResult, returnErr error) { - loop := e.newRouteLoop(ctx, prefer, providerFilter, req) - if preferNativeResponses && native != nil && e.Providers == nil { - return StreamResult{}, providers.ErrUnsupported - } - if preferNativeResponses && native != nil { - loop.eligible = func(item Item) bool { - adapter, ok := e.Providers.Get(itemProvider(item)) - return ok && adapter.NativeResponses != nil - } - loop.attempts = e.attemptsFor(loop.providerFilter, loop.regionFilter, req.Model, loop.allowed, loop.eligible, loop.resolver) - } - defer func() { result.Routing = loop.routing.Source }() - startedAll := time.Now() - for loop.index < loop.attempts { - item, i, err := loop.pickNext(e, req.Model) - if err != nil { - attempts, accountID, provider, pickErr := loop.pickFailure(err) - if loop.lastErr != nil { - return StreamResult{AttemptCount: attempts, AccountID: accountID, Provider: provider}, pickErr - } - return StreamResult{}, pickErr - } - noteStreamRoute(ctx, item.ID, loop.resultProvider(item)) - poolID := item.ID - if !e.acquireInFlight(loop.requestID, poolID) { - loop.exclude(item) - continue - } - release := func() { e.releaseInFlight(loop.requestID, poolID) } - if isInProcessItem(item) || (e.qoderDirect(item) && !(preferNativeResponses && native != nil)) { - result, classified, err := e.chatInProcessStreamAttempt(ctx, item, loop.dispatchRequest(item, req), native, i, preferNativeResponses) - - if err == nil { - result.AttemptCount = i + 1 - e.observeRouting(&loop.routing, poolID) - // Bind at response headers, not after the stream body ends. A - // follow-up turn can start while the first stream is still - // running; waiting for [DONE] would let it select another - // account and lose the prompt cache. Bind the pool ID because - // the upstream-reported label is not a Pool routing key. - e.bindSession(loop.routing, poolID) - result.Response = e.attachInFlightRelease(result.Response, loop.requestID, poolID) - return result, nil - } - loop.lastErr = err - if requestContextDone(ctx, err) { - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - if loop.canFailover(classified) { - release() - loop.failover(e, item) - continue - } - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - payload, err := json.Marshal(buildWorkerChatPayload(sanitizeForItem(item, loop.dispatchRequest(item, req)), true)) - if err != nil { - release() - return StreamResult{}, err - } - headerAccount := loop.headerAccount(item, i) - httpReq, err := e.newWorkerRequest(ctx, item, payload, headerAccount) - if err != nil { - release() - return StreamResult{}, err - } - started := time.Now() - resp, err := e.streamHTTPClient().Do(httpReq) - if err != nil { - if requestContextDone(ctx, err) { - latency := int(time.Since(started).Milliseconds()) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: ptrTime(time.Now().UTC()), - Status: accounts.AttemptStatusError, ErrorKind: accounts.KindUnavailable, ErrorMessage: err.Error(), LatencyMs: &latency, - }) - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, err - } - classified := Classify(0, err.Error(), "", accounts.KindUnavailable, "") - loop.lastErr = NewExecutionError(classified, fmt.Errorf("worker %s stream request failed: %w", item.ID, err)) - e.markClassified(item.ID, classified, loop.attemptModel(item, req)) - latency := int(time.Since(started).Milliseconds()) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: ptrTime(time.Now().UTC()), - Status: accounts.AttemptStatusFailover, ErrorKind: classified.Kind, ErrorMessage: loop.lastErr.Error(), LatencyMs: &latency, - }) - release() - loop.failover(e, item) - continue - } - if account := resp.Header.Get("X-Qoder-Account"); account != "" { - item.ID = account - noteStreamRoute(ctx, item.ID, loop.resultProvider(item)) - } - poolItem := item - poolItem.ID = poolID - if resp.StatusCode >= 300 { - body, _ := io.ReadAll(io.LimitReader(resp.Body, maxWorkerResponseBytes)) - resp.Body.Close() - msg := strings.TrimSpace(string(body)) - classified := classifyWorkerErr(resp, msg) - loop.lastErr = NewExecutionError(classified, nil) - if classified.Kind == accounts.KindModelNotAvailable { - e.handleModelAvailabilityFailure(RequestIDFromContext(ctx), "worker_stream", poolID, loop.attemptModel(item, req), classified) - } - e.markClassified(poolID, classified, loop.attemptModel(item, req)) - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - status := accounts.AttemptStatusError - if loop.canFailover(classified) { - status = accounts.AttemptStatusFailover - loop.failover(e, poolItem) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(msg), LatencyMs: &latency, - }) - release() - continue - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(msg), LatencyMs: &latency, - }) - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, loop.lastErr - } - probed, probeClassified, probeErr := probeStreamBody(ctx, resp.Body) - if probeErr != nil { - if requestContextDone(ctx, probeErr) { - // The client went away before the first event. Record the - // cancellation without cooling the account or failing over. - classified := ClassifyError(probeErr) - latency := int(time.Since(started).Milliseconds()) - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: ptrTime(time.Now().UTC()), - Status: accounts.AttemptStatusError, ErrorKind: classified.Kind, ErrorMessage: probeErr.Error(), LatencyMs: &latency, - }) - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: item.Provider}, NewExecutionError(classified, probeErr) - } - classified := probeClassified - if classified.Kind == "" { - classified = Classify(0, probeErr.Error(), "", accounts.KindUnavailable, "") - } - loop.lastErr = NewExecutionError(classified, fmt.Errorf("worker %s stream failed before the first event: %w", item.ID, probeErr)) - e.markClassified(poolID, classified, loop.attemptModel(item, req)) - finished := time.Now().UTC() - latency := int(finished.Sub(started).Milliseconds()) - status := accounts.AttemptStatusError - if loop.canFailover(classified) { - status = accounts.AttemptStatusFailover - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(probeErr.Error()), LatencyMs: &latency, - }) - loop.failover(e, poolItem) - release() - continue - } - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, - Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, - ErrorMessage: truncateErr(probeErr.Error()), LatencyMs: &latency, - }) - release() - return StreamResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, loop.lastErr - } - resp.Body = probed - e.markOK(poolID, loop.attemptModel(item, req)) - ttfb := int(time.Since(startedAll).Milliseconds()) - headerAt := time.Now().UTC() - e.recordAttempt(ctx, accounts.RequestAttempt{ - AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &headerAt, - Status: accounts.AttemptStatusOK, HTTPStatus: ptrInt(resp.StatusCode), LatencyMs: &ttfb, - }) - e.observeRouting(&loop.routing, poolID) - e.bindSession(loop.routing, poolID) - resolved := RequestedReasoningLevel(req) - if resolved != "" { - logResolvedReasoning(ctx, "chat_stream", item, req.Model, resolved) - } - resp = e.attachInFlightRelease(resp, loop.requestID, poolID) - return StreamResult{ - Response: resp, - AccountID: item.ID, - PoolAccountID: poolID, - Provider: loop.resultProvider(item), - AttemptCount: i + 1, - TTFBMs: ttfb, - ReasoningLevel: resolved, - }, nil - } - if loop.lastErr == nil { - loop.lastErr = fmt.Errorf("no worker accounts available") - } - return StreamResult{AttemptCount: loop.attempts}, loop.lastErr -} - func ptrInt(value int) *int { return &value } func ptrTime(value time.Time) *time.Time { return &value } diff --git a/internal/executor/chat_test.go b/internal/executor/chat_test.go index a2ae876ff..5bc2e8727 100644 --- a/internal/executor/chat_test.go +++ b/internal/executor/chat_test.go @@ -277,11 +277,11 @@ func TestRouteFailoverKeepsAttemptBudgetAndCrossesRegion(t *testing.T) { p.Upsert(Item{ID: "c1", Provider: "workbuddy", Region: "cn", Models: []string{"shared"}}) e := ChatExecutor{Pool: p} - loop := e.newRouteLoop(context.Background(), "", "", translate.ChatRequest{Model: "shared"}) + loop := e.newRouteLoop(RouteInput{PublicModel: "shared"}, "shared", nil) if loop.attempts != 2 { t.Fatalf("attempts=%d, want 2", loop.attempts) } - first, _, err := loop.pickNext(e, "shared") + first, _, err := loop.pickNextReserved(e) if err != nil { t.Fatalf("first pick: %v", err) } @@ -289,13 +289,15 @@ func TestRouteFailoverKeepsAttemptBudgetAndCrossesRegion(t *testing.T) { t.Fatalf("attempt budget shrank after region pin: %d", loop.attempts) } - loop.failover(e, first) - second, _, err := loop.pickNext(e, "shared") + loop.failover(e, first, first.item.ID, Classified{Failover: true}, errors.New("first attempt failed")) + e.releaseInFlight("", first.item.ID) + second, _, err := loop.pickNextReserved(e) if err != nil { t.Fatalf("failover pick: %v", err) } - if second.Region == first.Region { - t.Fatalf("failover stayed in failed region %s: %+v", first.Region, second) + defer e.releaseInFlight("", second.item.ID) + if second.item.Region == first.item.Region { + t.Fatalf("failover stayed in failed region %s: %+v", first.item.Region, second) } } @@ -1022,11 +1024,10 @@ func TestChatStreamProxyWorkerAppliesAccountAlias(t *testing.T) { } } -// Priority aggregation must not spend the whole retry budget on sibling -// accounts of the first provider. Each priority tier gets its own budget, so -// two exhausted qoder accounts cannot prevent the workbuddy member from being -// tried. -func TestAggregatePriorityFallsThroughToNextProvider(t *testing.T) { +// The global budget is not multiplied by the number of priority tiers. +// The lower tier only gets traffic when both higher-tier accounts are +// unavailable and there is still budget, or a new request arrives. +func TestAggregatePriorityRespectsGlobalBudget(t *testing.T) { var q1Hits, q2Hits, w1Hits atomic.Int32 q1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { q1Hits.Add(1) @@ -1061,14 +1062,15 @@ func TestAggregatePriorityFallsThroughToNextProvider(t *testing.T) { }, }) executor := NewChatExecutor(pool, "") - result, err := executor.ChatNonStream(WithAggregatePlan(context.Background(), plan), translate.ChatRequest{ - Model: "logical", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, - }, "", "") - if err != nil { - t.Fatal(err) - } - if result.AccountID != "z-w1" || result.AttemptCount != 3 { - t.Fatalf("result = %+v, want z-w1 after 3 attempts", result) + req := translate.ChatRequest{Model: "logical", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}} + route := RouteInput{PublicModel: "logical", AggregatePlan: plan} + result, err := executor.ChatNonStreamPrepared(context.Background(), req, route) + if err == nil || result.AttemptCount != 2 || q1Hits.Load() != 1 || q2Hits.Load() != 1 || w1Hits.Load() != 0 { + t.Fatalf("budget=2: result=%+v err=%v; hits q1=%d q2=%d w1=%d", result, err, q1Hits.Load(), q2Hits.Load(), w1Hits.Load()) + } + result, err = executor.ChatNonStreamPrepared(context.Background(), req, route) + if err != nil || result.AccountID != "z-w1" || result.AttemptCount != 1 { + t.Fatalf("second request result = %+v, err=%v, want z-w1 on first dispatch", result, err) } if q1Hits.Load() != 1 || q2Hits.Load() != 1 || w1Hits.Load() != 1 { t.Fatalf("hits q1=%d q2=%d w1=%d", q1Hits.Load(), q2Hits.Load(), w1Hits.Load()) diff --git a/internal/executor/classify.go b/internal/executor/classify.go index 6104f1c08..ce78891ec 100644 --- a/internal/executor/classify.go +++ b/internal/executor/classify.go @@ -14,19 +14,62 @@ const maxRetryAfter = 10 * time.Minute const minRateLimitCooldown = 30 * time.Second type Classified struct { - Kind string - Status int - Failover bool - Cooldown time.Duration - Code string - Type string - Message string - RetryAfter time.Duration + Kind string + Status int + Failover bool + Cooldown time.Duration + Code string + Type string + Message string + // PublicMessage, when set, is the only text allowed in a client-facing + // error. Message stays the internal diagnostic for logs and operators. + PublicMessage string + RetryAfter time.Duration // Model scopes the cooldown to one public model. When set, only that // model is cooled; the account keeps serving everything else. Model string + + // Failure facts. They describe where a failure happened; the fields above + // are the policy derived from them. Keeping both makes it possible to + // change retry/cooldown rules without losing the upstream evidence. + // + // Source is one of: client, provider_http, provider_sse, adapter, worker, + // transport, gateway. + Source string + // Phase is one of: prepare, connect, request, response, stream_open, + // stream_body, collect. + Phase string + // RequestState distinguishes a request that provably never left this + // process from one that may have reached the upstream. Only "not_sent" + // permits a replay of a non-idempotent chat turn. + RequestState string + // RequestSent is retained for older readers; RequestState is authoritative. + RequestSent bool + // ProviderCode preserves the provider-native code (for example 10605 or + // invalid_request_error) after normalization into Code. + ProviderCode string + // RetryAfterSource records where RetryAfter came from: header, body, + // provider, default, or empty when no hint was available. + RetryAfterSource string + // Scope is the blast radius of the failure: request, model, account, or + // shared. It decides what a cooldown may touch; it is not the same thing + // as Failover. + Scope string + // InternalRetries counts adapter-internal upstream replays that happened + // before this failure. They are part of the request budget even though + // they are not executor route attempts. + InternalRetries int } +// Request state values. They answer "may this request have reached the +// upstream", not "did the upstream answer". +const ( + RequestStateNotSent = "not_sent" + RequestStateMaybeSent = "maybe_sent" + RequestStateSent = "sent" + RequestStateUnknown = "unknown" +) + // backoffFloor and backoffCeiling bound the exponential backoff applied to // repeated failures of the same kind. A first failure still uses the // classifier's own duration; backoff only extends it on repeats. @@ -62,14 +105,24 @@ func ParseRetryAfter(raw string, fallback time.Duration) time.Duration { } func ParseRetryAfterHint(body, header string, fallback time.Duration) time.Duration { + hint, _ := retryAfterHint(body, header) + if hint > 0 { + return hint + } + return clampRetryAfter(fallback) +} + +// retryAfterHint reports the upstream wait together with its provenance so a +// cooldown default cannot silently replace a real Retry-After. +func retryAfterHint(body, header string) (time.Duration, string) { now := time.Now() if parsed := parseRetryAfterValue(header, now); parsed > 0 { - return clampRetryAfter(parsed) + return clampRetryAfter(parsed), "header" } if parsed := retryAfterFromBody(body, now); parsed > 0 { - return clampRetryAfter(parsed) + return clampRetryAfter(parsed), "body" } - return clampRetryAfter(fallback) + return 0, "" } func parseRetryAfterValue(raw string, now time.Time) time.Duration { @@ -166,6 +219,7 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class msg, code, typ, nestedKind := extractError(body) kind := strings.TrimSpace(firstNonEmpty(kindHint, nestedKind)) lower := strings.ToLower(msg + " " + code + " " + typ) + hint, hintSource := retryAfterHint(body, retryAfter) catalogUnavailable := strings.Contains(lower, "model_catalog_unavailable") || strings.Contains(lower, "dynamic model catalog is unavailable") || strings.Contains(lower, "model catalog unavailable") @@ -185,6 +239,11 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class kind = KindRateLimit case status == 401 || status == 403: kind = KindAuth + case strings.EqualFold(typ, "invalid_request_error") || code == "invalid_request" || status == http.StatusBadRequest || status == http.StatusUnprocessableEntity: + // A 400/422 that is not quota, model, readiness, rate limiting or + // moderation is a request problem. Cooling the account for it made + // a malformed client call look like an unhealthy upstream. + kind = KindInvalidRequest default: kind = KindUnavailable } @@ -221,12 +280,15 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class // ClassifyError(*providers.Error) path for the buffered chat path. out.Failover = false out.Cooldown = 0 - out.RetryAfter = ParseRetryAfterHint(body, retryAfter, 0) + out.RetryAfter = hint break } out.Failover = true - out.Cooldown = ParseRetryAfterHint(body, retryAfter, 60*time.Second) - if out.Cooldown > 0 && out.Cooldown < minRateLimitCooldown { + out.Cooldown = hint + if out.Cooldown <= 0 { + out.Cooldown = 60 * time.Second + } + if out.Cooldown < minRateLimitCooldown { out.Cooldown = minRateLimitCooldown } case KindAuth: @@ -236,12 +298,18 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class out.Status = 403 } out.Failover = true - out.Cooldown = ParseRetryAfterHint(body, retryAfter, 30*time.Second) + out.Cooldown = hint + if out.Cooldown <= 0 { + out.Cooldown = 30 * time.Second + } out.Code = firstNonEmpty(code, "unauthorized") case KindNotReady: out.Status = 503 out.Failover = true - out.Cooldown = ParseRetryAfterHint(body, retryAfter, 10*time.Second) + out.Cooldown = hint + if out.Cooldown <= 0 { + out.Cooldown = 10 * time.Second + } out.Code = firstNonEmpty(code, "not_ready") case KindInvalidRequest: // Request content the upstream rejected; retrying on another account @@ -280,7 +348,10 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class out.Status = 502 } out.Failover = true - out.Cooldown = ParseRetryAfterHint(body, retryAfter, 15*time.Second) + out.Cooldown = hint + if out.Cooldown <= 0 { + out.Cooldown = 15 * time.Second + } out.Code = firstNonEmpty(code, "upstream_error") } if failoverHint == "0" { @@ -288,15 +359,48 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class } else if failoverHint == "1" { out.Failover = true } - if code != providers.CodeUpstreamQueued { + // A real upstream wait survives the local cooldown floor: the client hint + // answers "when may I retry", while Cooldown answers "when may this + // account serve again". They are related but not identical. + out.RetryAfterSource = hintSource + if hint > 0 { + out.RetryAfter = hint + } else if out.Cooldown > 0 { out.RetryAfter = out.Cooldown + out.RetryAfterSource = "default" + } else { + out.RetryAfter = 0 + out.RetryAfterSource = "" } + out.ProviderCode = firstNonEmpty(code, typ) + out.Scope = failureScope(out.Kind, out.Code) if out.Message == "" { out.Message = out.Code } return out } +// failureScope states what a failure may affect. It never implies failover: +// a model-scoped 429 can rotate to another model member without cooling the +// whole account, and a request-scoped 400 cools nothing at all. +func failureScope(kind, code string) string { + switch kind { + case KindQuota, KindAuth, KindNotReady, KindUnavailable: + return "account" + case KindRateLimit: + if code == providers.CodeUpstreamQueued { + return "shared" + } + return "model" + case KindModelNotAvailable: + return "model" + case KindInvalidRequest, KindCanceled: + return "request" + default: + return "account" + } +} + func extractError(body string) (msg, code, typ, kind string) { text := strings.TrimSpace(body) if text == "" { @@ -304,7 +408,13 @@ func extractError(body string) (msg, code, typ, kind string) { } var parsed map[string]any if json.Unmarshal([]byte(text), &parsed) == nil { - if errObj, ok := parsed["error"].(map[string]any); ok { + errObj, _ := parsed["error"].(map[string]any) + if errObj == nil { + if response, ok := parsed["response"].(map[string]any); ok { + errObj, _ = response["error"].(map[string]any) + } + } + if errObj != nil { msg, _ = errObj["message"].(string) if msg == "" { msg, _ = errObj["msg"].(string) diff --git a/internal/executor/classify_test.go b/internal/executor/classify_test.go index 477b52c63..b7d24904e 100644 --- a/internal/executor/classify_test.go +++ b/internal/executor/classify_test.go @@ -137,7 +137,7 @@ func TestClassifyErrorClampsProviderRateLimitCooldown(t *testing.T) { got := ClassifyError(&providers.Error{ Kind: KindRateLimit, Status: 429, Message: "slow down", RetryAfter: 5 * time.Second, }) - if got.Kind != KindRateLimit || got.Cooldown != 30*time.Second || got.RetryAfter != 30*time.Second { + if got.Kind != KindRateLimit || got.Cooldown != 30*time.Second || got.RetryAfter != 5*time.Second { t.Fatalf("got %+v", got) } } @@ -316,7 +316,7 @@ func TestStreamReadErrorPreservesExecutionErrorWrapper(test *testing.T) { } } -func TestStreamReadErrorPreservesCancellation(test *testing.T) { +func TestStreamReadErrorTreatsContextCauseAsUpstreamTimeout(t *testing.T) { for _, cause := range []error{context.Canceled, context.DeadlineExceeded} { for _, scenario := range []struct { name string @@ -326,18 +326,21 @@ func TestStreamReadErrorPreservesCancellation(test *testing.T) { {"wrapped", fmt.Errorf("stream read: %w", cause)}, {"joined", errors.Join(&providers.Error{Kind: KindUnavailable, Status: 502, Message: "stream closed"}, cause)}, } { - test.Run(cause.Error()+"/"+scenario.name, func(test *testing.T) { + t.Run(cause.Error()+"/"+scenario.name, func(test *testing.T) { got := StreamReadError(scenario.err) if !errors.Is(got, cause) || !errors.Is(got, scenario.err) { - test.Fatalf("cancellation cause was lost: %v", got) + test.Fatalf("original cause was lost: %v", got) } var executionErr *ExecutionError if !errors.As(got, &executionErr) { - test.Fatalf("cancellation was not classified: %T", got) + test.Fatalf("stream failure was not classified: %T", got) } classified := ClassifyError(got) - if classified.Kind != KindCanceled || classified.Status != 499 || classified.Failover || classified.Cooldown != 0 || classified.RetryAfter != 0 { - test.Fatalf("cancellation classification=%+v", classified) + if classified.Kind != KindUnavailable || classified.Failover || classified.Cooldown != 0 { + test.Fatalf("stream-body timeout classification=%+v", classified) + } + if classified.RequestState != RequestStateSent || !classified.RequestSent { + test.Fatalf("stream-body timeout must record a sent request: %+v", classified) } }) } @@ -347,7 +350,6 @@ func TestStreamReadErrorPreservesCancellation(test *testing.T) { func TestObserveStreamFailureIgnoresCancellation(test *testing.T) { for _, failure := range []error{ context.Canceled, - fmt.Errorf("stream read: %w", context.DeadlineExceeded), &providers.Error{Kind: KindCanceled, Status: 499, Message: "canceled"}, NewExecutionError(Classified{Kind: KindCanceled, Status: 499}, nil), } { @@ -364,6 +366,16 @@ func TestObserveStreamFailureIgnoresCancellation(test *testing.T) { } } +func TestObserveStreamFailureRecordsLiveReadTimeout(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "healthy"}) + NewChatExecutor(pool, "").ObserveStreamFailure("healthy", StreamReadError(context.DeadlineExceeded), "swe-2") + after, _ := pool.ByID("healthy") + if after.LastKind != accounts.KindUnavailable { + t.Fatalf("live read timeout was not recorded as an upstream failure: %+v", after) + } +} + func TestClassifyErrorUpstreamEmptyNoCooldown(t *testing.T) { // A heartbeat-only empty upstream stream says nothing about the account's // health: fail over, but never cool the account down. @@ -400,21 +412,19 @@ func TestClassifyErrorUpstreamEmptyNoCooldown(t *testing.T) { } } -// A streaming first-byte timeout is an upstream hang: the client request is -// still alive, the upstream just never sent a response head. It must classify -// as upstream_unavailable with failover so the next eligible account serves -// the turn, plus a short cooldown to shed a stuck worker for a few seconds. -func TestClassifyErrorFirstByteTimeoutFailsOver(t *testing.T) { +// A streaming first-byte timeout is an upstream hang after the request may +// already be on the wire. It must not replay the turn on another account. +func TestClassifyErrorFirstByteTimeoutDoesNotFailover(t *testing.T) { err := fmt.Errorf("%w: no response head within 1m0s", providers.ErrFirstByteTimeout) got := ClassifyError(err) - if got.Kind != accounts.KindUnavailable { - t.Fatalf("Kind=%s, want %s", got.Kind, accounts.KindUnavailable) + if got.Kind != accounts.KindUnavailable || got.Status != http.StatusGatewayTimeout { + t.Fatalf("Kind=%s status=%d", got.Kind, got.Status) } - if !got.Failover { - t.Fatalf("Failover=false, want true") + if got.Failover || got.Cooldown != 0 { + t.Fatalf("first-byte timeout must not fail over or cool: %+v", got) } - if got.Cooldown != 10*time.Second || got.RetryAfter != 10*time.Second { - t.Fatalf("Cooldown=%s RetryAfter=%s, want 10s", got.Cooldown, got.RetryAfter) + if got.RequestState != RequestStateMaybeSent || !got.RequestSent { + t.Fatalf("request state=%q sent=%t", got.RequestState, got.RequestSent) } if got.Code != "first_byte_timeout" { t.Fatalf("Code=%q, want first_byte_timeout", got.Code) diff --git a/internal/executor/dispatch.go b/internal/executor/dispatch.go new file mode 100644 index 000000000..9a9cda65e --- /dev/null +++ b/internal/executor/dispatch.go @@ -0,0 +1,599 @@ +package executor + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// dispatchAttempt owns the immutable route target and records one upstream +// request. The worker label is only used for presentation, not feedback. +type dispatchAttempt struct { + target dispatchTarget + index int + started time.Time + httpStatus int +} + +func (a dispatchAttempt) record(e ChatExecutor, ctx context.Context, status string, classified Classified, usage accounts.RequestAttempt) { + finished := time.Now().UTC() + latency := int(finished.Sub(a.started).Milliseconds()) + usage.AttemptIndex, usage.AccountID = a.index, a.target.item.ID + usage.StartedAt, usage.FinishedAt, usage.LatencyMs = a.started, &finished, &latency + usage.Status = status + if a.httpStatus != 0 { + usage.HTTPStatus = ptrInt(a.httpStatus) + } + usage.ErrorKind, usage.ErrorMessage = classified.Kind, truncateErr(classified.Message) + if classified.RequestState != "" { + usage.RequestState = classified.RequestState + usage.RequestSent = classified.RequestState == RequestStateSent || classified.RequestState == RequestStateMaybeSent + } else if status == accounts.AttemptStatusOK { + usage.RequestState, usage.RequestSent = RequestStateSent, true + } + if usage.ErrorCode == "" { + usage.ErrorCode = classified.Code + } + if usage.Model == "" { + usage.Model = classified.Model + } + if usage.Phase == "" { + usage.Phase = classified.Phase + } + if usage.CooldownScope == "" { + usage.CooldownScope = classified.Scope + } + if usage.InternalRetries == 0 { + usage.InternalRetries = classified.InternalRetries + } + e.recordAttempt(ctx, usage) +} + +// feedback never resolves the model again: a catalog or alias can change +// while the request is on the wire. +func (e ChatExecutor) feedback(ctx context.Context, target dispatchTarget, source string, classified Classified) { + if e.Pool == nil || target.item.ID == "" { + return + } + switch classified.Kind { + case "", accounts.KindCanceled, accounts.KindInvalidRequest: + return + case accounts.KindModelNotAvailable: + e.handleModelAvailabilityFailure(RequestIDFromContext(ctx), source, target.item.ID, target.cooldownKey, classified) + return + case accounts.KindRateLimit: + classified.Model = target.cooldownKey + } + e.Pool.MarkClassified(target.item.ID, classified) +} + +func (e ChatExecutor) dispatchError(ctx context.Context, l *routeLoop, a dispatchAttempt, label, source string, classified Classified, err error) (bool, error) { + status := accounts.AttemptStatusError + retry := false + if canceled := dispatchCancellation(ctx, err, classified); canceled != nil { + err = canceled + classified = ClassifyError(canceled) + l.lastTarget, l.lastLabel, l.lastErr = a.target, label, err + } else { + e.feedback(ctx, a.target, source, classified) + retry = l.failover(e, a.target, label, classified, err) && ctx.Err() == nil + if retry { + status = accounts.AttemptStatusFailover + } + } + a.record(e, ctx, status, classified, accounts.RequestAttempt{}) + return retry, err +} + +func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (ChatResult, error) { + return e.ChatNonStreamPrepared(ctx, req, routeInputFromContext(ctx, req, prefer, providerFilter)) +} + +func (e ChatExecutor) ChatNonStreamPrepared(ctx context.Context, req translate.ChatRequest, route RouteInput) (result ChatResult, returnErr error) { + ctx = dispatchContext(ctx, route) + l := e.newRouteLoop(route, req.Model, nil) + defer func() { result.Routing = l.routing.Source }() + for l.index < l.attempts { + if err := ctx.Err(); err != nil { + return l.chatError(err) + } + target, index, err := l.pickNextReserved(e) + if err != nil { + return l.chatError(err) + } + result, classified, a, err := e.nonStreamAttempt(ctx, target, index, l.headerAccount(target, index), req) + if err == nil { + if validationErr := validateChatToolResult(route.Tooling, result); validationErr != nil { + classified, err = upstreamToolValidationError(validationErr) + retry, retryErr := e.dispatchError(ctx, &l, a, result.AccountID, "chat_non_stream", classified, err) + e.releaseInFlight(l.requestID, target.item.ID) + if !retry { + return l.chatError(retryErr) + } + continue + } + e.Pool.markRouteOK(target.item, target.cooldownKey) + e.bindSession(l.routing, target.item.ID) + a.record(e, ctx, accounts.AttemptStatusOK, Classified{}, accounts.RequestAttempt{ + PromptTokens: ptrInt(result.PromptTokens), CompletionTokens: ptrInt(result.CompletionTokens), UsageSource: result.UsageSource, + InternalRetries: result.InternalRetries, + }) + e.releaseInFlight(l.requestID, target.item.ID) + return result, nil + } + retry, err := e.dispatchError(ctx, &l, a, result.AccountID, "chat_non_stream", classified, err) + e.releaseInFlight(l.requestID, target.item.ID) + if !retry { + return l.chatError(err) + } + } + return l.chatError(noAccountsError("no accounts available")) +} + +func (e ChatExecutor) nonStreamAttempt(ctx context.Context, target dispatchTarget, index int, header string, req translate.ChatRequest) (result ChatResult, classified Classified, attempt dispatchAttempt, returnErr error) { + item := target.item + label := item.ID + attempt = dispatchAttempt{target: target, index: index, started: time.Now().UTC()} + defer func() { + result.AccountID, result.PoolAccountID, result.Provider = label, item.ID, target.provider() + result.AttemptCount, result.CooldownModel = index+1, target.cooldownKey + result.AggregateFEFO = target.aggregateFEFO + }() + if isInProcessItem(item) || e.qoderDirect(item) { + adapter, ok := e.Providers.Get(target.provider()) + if !ok || adapter.Chat == nil { + err := fmt.Errorf("provider %s does not implement chat", item.Provider) + return ChatResult{}, ClassifyError(err), attempt, err + } + out, err := adapter.Chat.ChatNonStream(ctx, item.ID, target.request(req)) + if err != nil { + classified := ClassifyError(err) + return ChatResult{}, classified, attempt, NewExecutionError(classified, err) + } + logResolvedReasoning(ctx, "chat_non_stream", item, target.memberModel, out.ReasoningLevel) + return ChatResult{ + Model: out.Model, Content: out.Content, Reasoning: out.Reasoning, ToolCalls: out.ToolCalls, FinishReason: out.FinishReason, + PromptTokens: out.PromptTokens, CompletionTokens: out.CompletionTokens, CacheReadTokens: out.CacheReadTokens, CacheWriteTokens: out.CacheWriteTokens, + CachedTokens: out.CacheReadTokens, UsageSource: out.UsageSource, ConsumedCredits: out.Credits, ReasoningLevel: out.ReasoningLevel, + InternalRetries: out.InternalRetries, + }, Classified{}, attempt, nil + } + resp, classified, err := e.openWorker(ctx, target, header, req, false) + if resp != nil { + label = firstNonEmpty(resp.Header.Get("X-Qoder-Account"), label) + attempt.httpStatus = resp.StatusCode + } + if err != nil { + return ChatResult{}, classified, attempt, err + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, maxWorkerResponseBytes+1)) + if err == nil && len(body) > maxWorkerResponseBytes { + err = fmt.Errorf("worker response exceeds %d bytes", maxWorkerResponseBytes) + } + if err == nil { + result, err = decodeChatResult(req, body) + } + if err != nil { + classified = Classify(502, err.Error(), "", accounts.KindUnavailable, "") + return ChatResult{}, classified, attempt, NewExecutionError(classified, err) + } + result.ReasoningLevel = RequestedReasoningLevel(req) + logResolvedReasoning(ctx, "chat_non_stream", item, target.memberModel, result.ReasoningLevel) + return result, Classified{}, attempt, nil +} + +func (e ChatExecutor) openWorker(ctx context.Context, target dispatchTarget, header string, req translate.ChatRequest, stream bool) (*http.Response, Classified, error) { + payload, err := json.Marshal(buildWorkerChatPayload(target.request(req), stream)) + if err != nil { + return nil, Classified{}, err + } + httpReq, err := e.newWorkerRequest(ctx, target.item, payload, header) + if err != nil { + return nil, Classified{}, err + } + client := e.HTTPClient + if stream { + client = e.streamHTTPClient() + } else if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(httpReq) + if err != nil { + if requestContextDone(ctx, err) { + return nil, ClassifyError(ctx.Err()), err + } + classified := Classify(0, err.Error(), "", accounts.KindUnavailable, "") + return nil, classified, NewExecutionError(classified, fmt.Errorf("worker %s request failed: %w", target.item.ID, err)) + } + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxWorkerResponseBytes)) + resp.Body.Close() + classified := classifyWorkerErr(resp, strings.TrimSpace(string(body))) + return resp, classified, newUpstreamResponseError(classified) + } + return resp, Classified{}, nil +} + +func (e ChatExecutor) ChatStreamProxy(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) (StreamResult, error) { + return e.ChatStreamProxyPrepared(ctx, req, nil, routeInputFromContext(ctx, req, prefer, providerFilter)) +} + +// ChatStreamProxyNativeResponses retries only native-capable adapters. +func (e ChatExecutor) ChatStreamProxyNativeResponses(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (StreamResult, error) { + return e.ChatStreamProxyNativeResponsesPrepared(ctx, req, native, routeInputFromContext(ctx, req, prefer, providerFilter)) +} + +func (e ChatExecutor) ChatStreamProxyPrepared(ctx context.Context, req translate.ChatRequest, _ *translate.NativeResponsesRequest, route RouteInput) (StreamResult, error) { + return e.chatStreamProxy(ctx, req, nil, route) +} + +func (e ChatExecutor) ChatStreamProxyNativeResponsesPrepared(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, route RouteInput) (StreamResult, error) { + if native == nil || e.Providers == nil { + return StreamResult{}, providers.ErrUnsupported + } + return e.chatStreamProxy(ctx, req, native, route) +} + +// nativeResponsesCompatFallback keeps the named aggregate candidate set intact +// when the original Responses body can be represented by the shared Chat form. +// Non-aggregate requests retain the existing native-only route contract. +func nativeResponsesCompatFallback(plan *AggregatePlan, native *translate.NativeResponsesRequest) bool { + if plan == nil || native == nil { + return false + } + _, err := native.Compat() + return err == nil +} + +func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, route RouteInput) (result StreamResult, returnErr error) { + ctx = dispatchContext(ctx, route) + optionalNative := nativeResponsesCompatFallback(route.AggregatePlan, native) + var eligible func(Item) bool + if native != nil { + eligible = e.nativeResponsesEligible + if optionalNative { + eligible = nil + } + } + l := e.newRouteLoop(route, req.Model, eligible) + defer func() { result.Routing = l.routing.Source }() + started := time.Now() + upstream, a, err := e.openRoutedStream(ctx, &l, req, native, optionalNative) + if err != nil { + return upstream, err + } + upstream.TTFBMs = int(time.Since(started).Milliseconds()) + // Provisional affinity permits a follow-up while a stream is open. + // A late upstream failure only invalidates a binding to this account. + completion := &streamCompletion{attempt: a, sessionKey: l.routing.SessionKey, requestID: l.requestID, internalRetries: upstream.InternalRetries} + if ctx.Err() == nil { + completion.bindingVersion = e.bindSession(l.routing, a.target.item.ID) + } + upstream.completion = completion + upstream.Response.Body = &releaseCloser{ReadCloser: upstream.Response.Body, release: func() { + // Legacy callers that close without relaying did not confirm success. + e.completeStream(ctx, completion, context.Canceled) + e.releaseInFlight(l.requestID, a.target.item.ID) + }} + return upstream, nil +} + +// openRoutedStream retries only failures before an accepted first event. +// It leaves the accepted attempt reserved for the relay or collector. +func (e ChatExecutor) openRoutedStream(ctx context.Context, l *routeLoop, req translate.ChatRequest, native *translate.NativeResponsesRequest, optionalNative bool) (StreamResult, dispatchAttempt, error) { + for l.index < l.attempts { + if err := ctx.Err(); err != nil { + r, err := l.streamError(err) + return r, dispatchAttempt{}, err + } + target, index, err := l.pickNextReserved(e) + if err != nil { + r, err := l.streamError(err) + return r, dispatchAttempt{}, err + } + noteStreamRoute(ctx, target.item.ID, target.provider()) + result, classified, a, err := e.streamAttempt(ctx, target, index, l.headerAccount(target, index), req, native, optionalNative) + if err == nil { + return result, a, nil + } + retry, err := e.dispatchError(ctx, l, a, result.AccountID, "chat_stream_open", classified, err) + e.releaseInFlight(l.requestID, target.item.ID) + if !retry { + return result, a, err + } + } + r, err := l.streamError(noAccountsError("no accounts available")) + return r, dispatchAttempt{}, err +} + +func (e ChatExecutor) streamAttempt(ctx context.Context, target dispatchTarget, index int, header string, req translate.ChatRequest, native *translate.NativeResponsesRequest, optionalNative bool) (StreamResult, Classified, dispatchAttempt, error) { + item := target.item + a := dispatchAttempt{target: target, index: index, started: time.Now().UTC()} + result := StreamResult{AccountID: item.ID, PoolAccountID: item.ID, Provider: target.provider(), AttemptCount: index + 1, CooldownModel: target.cooldownKey, AggregateFEFO: target.aggregateFEFO, RequestState: RequestStateSent} + var resp *http.Response + var err error + var classified Classified + workerAttempt := false + inProcess := isInProcessItem(item) || e.qoderDirect(item) + var resolved providers.ResolvedChat + adapter, _ := e.Providers.Get(target.provider()) + switch { + case native != nil && adapter.NativeResponses != nil: + resp, resolved, err = adapter.NativeResponses.ResponsesStream(ctx, item.ID, native, providers.RequestOptions{ + Model: target.upstreamModel, DropSystemPrompt: item.DropSystemPrompt && target.provider() != "qoder", + }) + result.NativeResponses = err == nil + case native != nil && optionalNative && inProcess && adapter.Chat != nil: + resp, resolved, err = adapter.Chat.ChatStream(ctx, item.ID, target.request(req)) + case native != nil && optionalNative && !inProcess: + workerAttempt = true + resp, classified, err = e.openWorker(ctx, target, header, req, true) + case native == nil && inProcess && adapter.Chat != nil: + resp, resolved, err = adapter.Chat.ChatStream(ctx, item.ID, target.request(req)) + case native == nil && !inProcess: + workerAttempt = true + resp, classified, err = e.openWorker(ctx, target, header, req, true) + default: + err = providers.ErrUnsupported + } + result.ReasoningLevel = resolved.ReasoningLevel + result.InternalRetries = resolved.InternalRetries + if workerAttempt { + if resp != nil { + a.httpStatus = resp.StatusCode + result.AccountID = firstNonEmpty(resp.Header.Get("X-Qoder-Account"), result.AccountID) + noteStreamRoute(ctx, result.AccountID, target.provider()) + } + if err != nil { + return result, classified, a, err + } + result.ReasoningLevel = RequestedReasoningLevel(req) + } else if err != nil { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } + if errors.Is(err, providers.ErrUnsupported) { + return result, Classified{Kind: accounts.KindInvalidRequest, Message: err.Error()}, a, err + } + classified := ClassifyError(err) + return result, classified, a, NewExecutionError(classified, err) + } + if resp == nil || resp.Body == nil { + err := StreamIncompleteError() + return result, ClassifyError(err), a, err + } + a.httpStatus = resp.StatusCode + body, classified, err := probeStreamBody(resp.Body) + if err != nil { + if classified.Kind == "" { + classified = ClassifyError(err) + } + return result, classified, a, NewExecutionError(classified, err) + } + resp.Body = body + result.Response = resp + result.TTFBMs = int(time.Since(a.started).Milliseconds()) + logResolvedReasoning(ctx, "chat_stream", item, target.memberModel, result.ReasoningLevel) + return result, Classified{}, a, nil +} + +type streamCompletion struct { + once sync.Once + attempt dispatchAttempt + requestID string + sessionKey string + bindingVersion uint64 + internalRetries int +} + +// FinishStream reports the terminal result of an accepted relay. Call before +// closing the body; client cancellation must not cool the upstream account. +func (e ChatExecutor) FinishStream(ctx context.Context, result StreamResult, err error) { + if result.completion != nil { + e.completeStream(ctx, result.completion, err) + } else if err != nil && dispatchCancellation(ctx, err, ClassifyError(err)) == nil { + e.ObserveStreamFailure(result.PoolAccountID, err, result.CooldownModel) + } +} + +func (e ChatExecutor) completeStream(ctx context.Context, completion *streamCompletion, err error) { + if ctx == nil { + ctx = context.Background() + } + ctx = context.WithValue(ctx, requestIDKey{}, completion.requestID) + completion.once.Do(func() { + a := completion.attempt + if err == nil { + e.Pool.markRouteOK(a.target.item, a.target.cooldownKey) + e.SessionAffinity.touchVersion(completion.sessionKey, completion.bindingVersion) + a.record(e, ctx, accounts.AttemptStatusOK, Classified{}, accounts.RequestAttempt{ + InternalRetries: completion.internalRetries, + }) + return + } + classified := ClassifyError(err) + if canceled := dispatchCancellation(ctx, err, classified); canceled != nil { + classified = ClassifyError(canceled) + } + if classified.Kind == accounts.KindQuota && classified.Cooldown <= 0 { + classified.Cooldown = NextLocalMidnightCooldown() + } + e.feedback(ctx, a.target, "stream_body", classified) + if classified.Failover { + e.SessionAffinity.forgetVersion(completion.sessionKey, completion.bindingVersion) + } + a.record(e, ctx, accounts.AttemptStatusError, classified, accounts.RequestAttempt{}) + }) +} + +// releaseCloser transfers the reservation to the caller, who must close the +// body after consuming or abandoning it. +type releaseCloser struct { + io.ReadCloser + once sync.Once + release func() + err error +} + +func (c *releaseCloser) Close() error { + c.once.Do(func() { + c.err = c.ReadCloser.Close() + c.release() + }) + return c.err +} + +func (e ChatExecutor) NativeResponsesNonStream(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, prefer, providerFilter string) (NativeResponseResult, error) { + return e.NativeResponsesNonStreamPrepared(ctx, req, native, routeInputFromContext(ctx, req, prefer, providerFilter)) +} + +// NativeResponsesNonStreamPrepared collects upstream SSE before exposing +// anything to the client. Collection failures may retry within this same loop. +func (e ChatExecutor) NativeResponsesNonStreamPrepared(ctx context.Context, req translate.ChatRequest, native *translate.NativeResponsesRequest, route RouteInput) (result NativeResponseResult, returnErr error) { + if native == nil || e.Providers == nil { + return result, providers.ErrUnsupported + } + ctx = dispatchContext(ctx, route) + optionalNative := nativeResponsesCompatFallback(route.AggregatePlan, native) + var eligible func(Item) bool = e.nativeResponsesEligible + if optionalNative { + eligible = nil + } + l := e.newRouteLoop(route, req.Model, eligible) + defer func() { result.Routing = l.routing.Source }() + for l.index < l.attempts { + var upstream StreamResult + var a dispatchAttempt + if optionalNative { + if err := ctx.Err(); err != nil { + r, streamErr := l.streamError(err) + result = nativeResponsesResultFromStream(r) + return result, streamErr + } + target, index, err := l.pickNextReserved(e) + if err != nil { + r, streamErr := l.streamError(err) + result = nativeResponsesResultFromStream(r) + return result, streamErr + } + noteStreamRoute(ctx, target.item.ID, target.provider()) + if !e.nativeResponsesEligible(target.item) { + chatResult, classified, attempt, attemptErr := e.nonStreamAttempt(ctx, target, index, l.headerAccount(target, index), req) + result = nativeResponsesResultFromChat(chatResult) + if attemptErr == nil { + if validationErr := validateChatToolResult(route.Tooling, chatResult); validationErr != nil { + classified, attemptErr = upstreamToolValidationError(validationErr) + retry, retryErr := e.dispatchError(ctx, &l, attempt, chatResult.AccountID, "chat_non_stream", classified, attemptErr) + e.releaseInFlight(l.requestID, target.item.ID) + if !retry { + return result, retryErr + } + continue + } + e.Pool.markRouteOK(target.item, target.cooldownKey) + e.bindSession(l.routing, target.item.ID) + attempt.record(e, ctx, accounts.AttemptStatusOK, Classified{}, accounts.RequestAttempt{ + PromptTokens: ptrInt(chatResult.PromptTokens), CompletionTokens: ptrInt(chatResult.CompletionTokens), UsageSource: chatResult.UsageSource, + }) + e.releaseInFlight(l.requestID, target.item.ID) + return result, nil + } + retry, attemptErr := e.dispatchError(ctx, &l, attempt, chatResult.AccountID, "chat_non_stream", classified, attemptErr) + e.releaseInFlight(l.requestID, target.item.ID) + if !retry { + return result, attemptErr + } + continue + } + var classified Classified + upstream, classified, a, err = e.streamAttempt(ctx, target, index, l.headerAccount(target, index), req, native, true) + if err != nil { + retry, err := e.dispatchError(ctx, &l, a, upstream.AccountID, "chat_stream_open", classified, err) + e.releaseInFlight(l.requestID, target.item.ID) + result = nativeResponsesResultFromStream(upstream) + if !retry { + return result, err + } + continue + } + } else { + var err error + upstream, a, err = e.openRoutedStream(ctx, &l, req, native, false) + result = nativeResponsesResultFromStream(upstream) + if err != nil { + return result, err + } + } + result = nativeResponsesResultFromStream(upstream) + collected, err := translate.CollectResponses(upstream.Response.Body) + upstream.Response.Body.Close() + if err == nil { + result.Response, result.FinishReason = collected.Response, collected.FinishReason + result.PromptTokens, result.OutputTokens, result.CachedTokens = collected.InputTokens, collected.OutputTokens, collected.CachedTokens + if validationErr := validateNativeToolResult(route.Tooling, result); validationErr != nil { + classified, attemptErr := upstreamToolValidationError(validationErr) + retry, retryErr := e.dispatchError(ctx, &l, a, upstream.AccountID, "native_responses_body", classified, attemptErr) + e.releaseInFlight(l.requestID, a.target.item.ID) + if !retry { + return result, retryErr + } + continue + } + e.Pool.markRouteOK(a.target.item, a.target.cooldownKey) + e.bindSession(l.routing, a.target.item.ID) + a.record(e, ctx, accounts.AttemptStatusOK, Classified{}, accounts.RequestAttempt{PromptTokens: result.PromptTokens, CompletionTokens: result.OutputTokens}) + e.releaseInFlight(l.requestID, a.target.item.ID) + return result, nil + } + err = classifyResponsesCollectionError(err) + retry, err := e.dispatchError(ctx, &l, a, upstream.AccountID, "native_responses_body", ClassifyError(err), err) + e.releaseInFlight(l.requestID, a.target.item.ID) + if !retry { + return result, err + } + } + return result, l.lastErr +} + +func nativeResponsesResultFromStream(upstream StreamResult) NativeResponseResult { + return NativeResponseResult{ + AccountID: upstream.AccountID, PoolAccountID: upstream.PoolAccountID, Provider: upstream.Provider, + AttemptCount: upstream.AttemptCount, ReasoningLevel: upstream.ReasoningLevel, CooldownModel: upstream.CooldownModel, + AggregateFEFO: upstream.AggregateFEFO, + } +} + +func nativeResponsesResultFromChat(chat ChatResult) NativeResponseResult { + cached := chat.CacheReadTokens + if cached == nil { + cached = chat.CachedTokens + } + return NativeResponseResult{ + CompatResult: &chat, AccountID: chat.AccountID, PoolAccountID: chat.PoolAccountID, Provider: chat.Provider, + AttemptCount: chat.AttemptCount, ReasoningLevel: chat.ReasoningLevel, FinishReason: chat.FinishReason, + PromptTokens: ptrInt(chat.PromptTokens), OutputTokens: ptrInt(chat.CompletionTokens), CachedTokens: cached, + CooldownModel: chat.CooldownModel, AggregateFEFO: chat.AggregateFEFO, + } +} + +func classifyResponsesCollectionError(err error) error { + var upstream *translate.ResponsesStreamFailure + if errors.As(err, &upstream) { + return ClassifyUpstreamBody(0, upstream.Body) + } + if errors.Is(err, translate.ErrResponsesIncomplete) { + return StreamIncompleteError() + } + return StreamReadError(err) +} diff --git a/internal/executor/error.go b/internal/executor/error.go index d9d3247cc..96b4c6748 100644 --- a/internal/executor/error.go +++ b/internal/executor/error.go @@ -2,9 +2,12 @@ package executor import ( "context" + "encoding/json" "errors" + "net" "net/http" "net/url" + "strconv" "strings" "time" @@ -46,9 +49,167 @@ func NewExecutionError(classified Classified, err error) *ExecutionError { return &ExecutionError{Classified: classified, Err: err} } -// ClassifyUpstreamBody classifies an upstream HTTP/SSE error body once. +// ClassifyUpstreamBody classifies a known upstream failure envelope. func ClassifyUpstreamBody(status int, body string) error { - return NewExecutionError(Classify(status, body, "", "", ""), nil) + classified := inspectUpstreamFailure(body).classify(status) + classified.Source, classified.Phase = "provider_http", "response" + classified.RequestState, classified.RequestSent = RequestStateSent, true + return newUpstreamResponseError(classified) +} + +// ClassifyStreamEvent returns nil for ordinary SSE events. Use this for both +// pre-dispatch probing and the relay so nested worker and Responses errors +// have the same meaning before and after the stream is exposed. +func ClassifyStreamEvent(eventName, data string) error { + failure := inspectUpstreamFailure(data) + event := strings.ToLower(strings.TrimSpace(eventName)) + if event != "error" && event != "response.failed" && !failure.recognized { + return nil + } + classified := failure.classify(0) + classified.Source, classified.Phase = "provider_sse", "stream_body" + classified.RequestState, classified.RequestSent = RequestStateSent, true + return newUpstreamResponseError(classified) +} + +// An explicit upstream reply is distinct from a failed read. Keep that +// distinction through wrappers when the client disconnects at the same time. +type upstreamResponseError struct{ *ExecutionError } + +func (e upstreamResponseError) Unwrap() error { return e.ExecutionError } + +func newUpstreamResponseError(classified Classified) error { + return upstreamResponseError{NewExecutionError(classified, nil)} +} + +// dispatchCancellation treats an ambiguous read/open failure as cancellation +// only when the request context is actually done. An observed upstream reply +// (or a specific classification such as quota or rate limit) is still evidence +// about the selected account. A successful terminal result has no error. +func dispatchCancellation(ctx context.Context, err error, classified Classified) error { + if ctx == nil || err == nil { + return nil + } + cause := ctx.Err() + if cause == nil { + return nil + } + if requestContextDone(ctx, err) { + return cause + } + var upstream upstreamResponseError + if errors.As(err, &upstream) { + return nil + } + switch classified.Kind { + case "", accounts.KindCanceled, accounts.KindUnavailable: + return cause + default: + return nil + } +} + +type upstreamFailure struct { + raw, body string + status int + noFailover bool + recognized bool +} + +func inspectUpstreamFailure(raw string) upstreamFailure { + raw = strings.TrimSpace(raw) + f := upstreamFailure{raw: raw, body: raw} + // Wrapper metadata remains authoritative even when the diagnostic lives + // in a JSON string or an inner body. Bound traversal of wrappers. + for depth := 0; depth < 8; depth++ { + var value any + if json.Unmarshal([]byte(f.body), &value) != nil { + break + } + switch value := value.(type) { + case string: + f.body = strings.TrimSpace(value) + case map[string]any: + response, _ := value["response"].(map[string]any) + typ, _ := value["type"].(string) + if typ == "error" || typ == "response.failed" || value["error"] != nil || response["error"] != nil { + f.recognized = true + } + for _, obj := range []map[string]any{value, nestedFailureObject(value, "error"), response, nestedFailureObject(response, "error")} { + f.readMetadata(obj) + f.readMetadata(nestedFailureObject(obj, "data")) + } + if _, isChatChunk := value["choices"]; !isChatChunk && !strings.HasPrefix(typ, "response.") { + message, _ := value["message"].(string) + f.recognized = f.recognized || value["code"] != nil || value["msgCode"] != nil || value["kind"] != nil || strings.TrimSpace(message) != "" + } + if value["body"] == nil || value["error"] != nil || response["error"] != nil { + return f + } + inner, err := json.Marshal(value["body"]) + if err != nil { + return f + } + f.body = string(inner) + default: + return f + } + } + return f +} + +func nestedFailureObject(obj map[string]any, field string) map[string]any { + nested, _ := obj[field].(map[string]any) + return nested +} + +func (f *upstreamFailure) readMetadata(obj map[string]any) { + if v, ok := obj["failover"].(bool); ok && !v { + f.noFailover = true + } + if f.status != 0 { + return + } + for _, key := range []string{"status", "status_code", "statusCode", "statusCodeValue"} { + if status, err := strconv.Atoi(stringifyJSONCode(obj[key])); err == nil && status >= 400 && status <= 599 { + f.status, f.recognized = status, true + return + } + } +} + +func (f upstreamFailure) classify(status int) Classified { + if status == 0 { + status = f.status + } + var retryAfter string + if f.body != f.raw { + if retry := retryAfterFromBody(f.raw, time.Now()); retry > 0 { + retryAfter = retry.String() + } + } + var failover string + if f.noFailover { + // An upstream can forbid switching; it cannot make a request-level + // failure retryable against the executor's classification. + failover = "0" + } + return Classify(status, f.body, retryAfter, "", failover) +} + +// ErrStreamFirstFrameTimeout is returned after response headers arrived but no +// valid SSE frame followed within the independent first-frame window. The +// request is already on the wire, so this is never a failover signal. +var ErrStreamFirstFrameTimeout = errors.New("upstream sent response headers but no valid SSE frame") + +// ErrClientDisconnected marks a downstream write failure: the client left +// before the terminal frame arrived. It is never evidence about the upstream +// account, even when the HTTP request context has not been canceled yet. +var ErrClientDisconnected = errors.New("client disconnected before terminal frame") + +func ClientDisconnectError(cause error) error { + classified := ClassifyContextDone(ErrClientDisconnected) + return NewExecutionError(classified, cause) } // StreamIncompleteError is a mid-body stream that ended without [DONE]. @@ -56,7 +217,10 @@ func StreamIncompleteError() error { return newUnavailableStreamError("upstream_stream_incomplete", "stream ended before [DONE]", 502, nil) } -// StreamReadError wraps a mid-body stream read failure. +// StreamReadError wraps a mid-body stream read failure. A deadline on the body +// is treated as an upstream timeout here; the executor's cancellation helper +// overrides it with context.Canceled only when the parent request is actually +// done. That keeps a live parent from being reported as a client cancellation. func StreamReadError(err error) error { if err == nil { return StreamIncompleteError() @@ -65,11 +229,26 @@ func StreamReadError(err error) error { if errors.As(err, &execErr) && execErr != nil { return err } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + classified := upstreamTimeoutClassification(err, "stream_body") + // The read happened after response headers, so the upstream request is + // definitively sent even though the error text is a bare deadline. + classified.RequestState, classified.RequestSent = RequestStateSent, true + return NewExecutionError(classified, err) + } var providerErr *providers.Error - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &providerErr) && providerErr != nil) { + if errors.As(err, &providerErr) && providerErr != nil { return NewExecutionError(ClassifyError(err), err) } - return newUnavailableStreamError("upstream_stream_interrupted", "stream read error: "+err.Error(), 502, err) + wrapped := newUnavailableStreamError("upstream_stream_interrupted", "stream read error: "+err.Error(), 502, err) + var wrappedExec *ExecutionError + if errors.As(wrapped, &wrappedExec) && wrappedExec != nil { + // The bytes stopped arriving from the transport, not from a provider + // error frame; the response headers had already arrived. + wrappedExec.Classified.Source, wrappedExec.Classified.Phase = "transport", "stream_body" + wrappedExec.Classified.RequestState, wrappedExec.Classified.RequestSent = RequestStateSent, true + } + return wrapped } func newUnavailableStreamError(code, message string, status int, cause error) error { @@ -78,11 +257,22 @@ func newUnavailableStreamError(code, message string, status int, cause error) er classified.Message = message classified.Status = status classified.Type = "api_error" + classified.Source, classified.Phase = "provider_sse", "stream_body" + classified.RequestState, classified.RequestSent = RequestStateSent, true + classified.Scope = "account" return NewExecutionError(classified, cause) } // ClassifyError is the single adapter-error policy used by execution and HTTP reporting. func ClassifyError(err error) Classified { + classified := classifyError(err) + if classified.InternalRetries == 0 { + classified.InternalRetries = providers.InternalRetriesOf(err) + } + return classified +} + +func classifyError(err error) Classified { if err == nil { return Classify(0, "", "", accounts.KindUnavailable, "") } @@ -90,35 +280,53 @@ func ClassifyError(err error) Classified { if errors.As(err, &execErr) && execErr != nil { return execErr.Classified } - // A streaming first-byte timeout is an upstream hang, not a client cancel: - // the parent request is still alive, the upstream just never answered. Cool - // the account briefly and fail over so the next eligible account serves the - // turn instead of hanging until the client gives up. + // A streaming first-byte timeout means the request was written but no + // response head arrived. The upstream may already be processing it, so a + // replay could duplicate a non-idempotent turn. Report the timeout and let + // the caller decide; do not rotate the account. + if errors.Is(err, ErrStreamFirstFrameTimeout) { + classified := upstreamTimeoutClassification(err, "stream_open") + classified.Code = "stream_first_frame_timeout" + classified.Message = err.Error() + classified.Failover, classified.Cooldown = false, 0 + classified.RequestState, classified.RequestSent = RequestStateSent, true + classified.Scope = "account" + return classified + } if errors.Is(err, providers.ErrFirstByteTimeout) { return Classified{ - Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, - Failover: true, Cooldown: 10 * time.Second, RetryAfter: 10 * time.Second, + Kind: accounts.KindUnavailable, Status: http.StatusGatewayTimeout, + Failover: false, Cooldown: 0, Code: "first_byte_timeout", Message: err.Error(), + Source: "provider_http", Phase: "stream_open", + RequestState: RequestStateMaybeSent, RequestSent: true, + RetryAfterSource: "default", Scope: "account", } } - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return Classified{ - Kind: accounts.KindCanceled, Status: 499, Failover: false, - Code: "request_canceled", Message: err.Error(), - } + if errors.Is(err, context.Canceled) { + return ClassifyContextDone(err) + } + if errors.Is(err, context.DeadlineExceeded) { + return upstreamTimeoutClassification(err, "response") + } + if isTimeoutError(err) { + return upstreamTimeoutClassification(err, transportPhase(err)) } if isTransportFailure(err) { - // The request never reached the upstream: a dial, TLS handshake, or - // reset failure says nothing about this account's credential, quota, - // or rate limit. Cooling it with the generic unavailable default (15s) - // just parks a healthy account, and in a single-account route one - // handshake timeout turns into "all accounts are cooling down" for - // every request that follows. Surface the transport failure and let - // the client retry; the account stays routable. + // A dial or TLS handshake never reached the upstream; a reset or read + // timeout may have. Both stay out of cooldown because the account's + // credential, quota and rate-limit state are unknown, but the state + // bit tells an operator (and a future replay policy) which one happened. + state := transportSendState(err) return Classified{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, - Failover: false, Code: "upstream_unreachable", Type: "api_error", - Message: err.Error(), + Failover: state == RequestStateNotSent, Cooldown: 0, + Code: "upstream_unreachable", Type: "api_error", + Message: transportErrorMessage(err), + Source: "transport", + Phase: transportPhase(err), + RequestState: state, RequestSent: state != RequestStateNotSent && state != RequestStateUnknown, + Scope: "account", } } if providers.IsTLSVerifyError(err) { @@ -132,15 +340,22 @@ func ClassifyError(err error) Classified { } var providerErr *providers.Error if !errors.As(err, &providerErr) || providerErr == nil { - return Classify(0, err.Error(), "", "", "") + classified := Classify(0, err.Error(), "", "", "") + classified.Source, classified.Phase = "adapter", "stream_body" + classified.RequestState, classified.RequestSent = RequestStateSent, true + return classified } message := strings.TrimSpace(providerErr.Message) if message == "" { message = providerErr.Error() } - classified := Classify(providerErr.Status, message, "", providerErr.Kind, "") + classified := Classify(providerErr.Status, message, "", providerKindHint(providerErr), "") + classified.Source, classified.Phase = "adapter", providerPhase(providerErr) + classified.RequestState, classified.RequestSent = RequestStateSent, true + classified.InternalRetries = providerErr.InternalRetries if providerErr.Code != "" { classified.Code = providerErr.Code + classified.ProviderCode = providerErr.Code } if providerErr.Type != "" { classified.Type = providerErr.Type @@ -158,6 +373,10 @@ func ClassifyError(err error) Classified { classified.Failover = false classified.Cooldown = 0 classified.RetryAfter = providerErr.RetryAfter + if classified.RetryAfter > 0 { + classified.RetryAfterSource = "provider" + } + classified.Scope = "shared" return classified case providers.CodeClientVersionTooLow: classified.Failover = false @@ -198,10 +417,155 @@ func ClassifyError(err error) Classified { classified.Cooldown = providerErr.RetryAfter } } - classified.RetryAfter = classified.Cooldown + // The provider hint answers "when may the client retry" and must survive + // the cooldown floor applied to this account. + if providerErr.RetryAfter > 0 { + classified.RetryAfter = providerErr.RetryAfter + classified.RetryAfterSource = "provider" + } else if classified.Cooldown > 0 { + classified.RetryAfter = classified.Cooldown + classified.RetryAfterSource = "default" + } else { + classified.RetryAfter = 0 + classified.RetryAfterSource = "" + } + if classified.Scope == "" { + classified.Scope = failureScope(classified.Kind, classified.Code) + } return classified } +// ClassifyContextDone classifies a failure whose cause is the caller's request +// context. It must be used instead of ClassifyError(ctx.Err()) so a gateway +// deadline is never mistaken for an upstream timeout. +func ClassifyContextDone(err error) Classified { + code := "request_canceled" + if errors.Is(err, context.DeadlineExceeded) { + code = "request_deadline_exceeded" + } + return Classified{ + Kind: accounts.KindCanceled, Status: 499, Failover: false, + Code: code, Message: err.Error(), + Source: "client", Phase: "request", Scope: "request", + RequestState: RequestStateUnknown, + } +} + +// upstreamTimeoutClassification is a timeout inside an adapter or transport +// whose parent request is still alive. The request may already be on the wire, +// so it is never replayed on another account. +func upstreamTimeoutClassification(err error, phase string) Classified { + state := transportSendState(err) + if state == "" || state == RequestStateNotSent { + // A pure context deadline carries no net.OpError; the adapter had + // already started the call, so treat it as possibly sent. + state = RequestStateMaybeSent + } + return Classified{ + Kind: accounts.KindUnavailable, Status: http.StatusGatewayTimeout, + Failover: false, Cooldown: 0, Code: "upstream_timeout", + Message: transportErrorMessage(err), + Source: "transport", Phase: phase, + RequestState: state, RequestSent: state == RequestStateSent, + Scope: "account", RetryAfterSource: "default", + } +} + +// providerKindHint maps an explicit provider error type to the shared kind +// vocabulary. An empty result leaves Classify's own text/status inference +// untouched, so a typed hint never masks a quota or model message. +func providerKindHint(pe *providers.Error) string { + if pe == nil { + return "" + } + if pe.Kind != "" { + return pe.Kind + } + switch strings.ToLower(strings.TrimSpace(pe.Type)) { + case "invalid_request_error", "invalid_request", "bad_request": + return accounts.KindInvalidRequest + case "rate_limit_error", "rate_limit_exceeded", "too_many_requests": + return accounts.KindRateLimit + case "authentication_error", "permission_error", "unauthorized": + return accounts.KindAuth + case "insufficient_quota", "quota_exceeded": + return accounts.KindQuota + } + return "" +} + +func providerPhase(pe *providers.Error) string { + if pe != nil && pe.Status == 0 { + return "stream_body" + } + return "response" +} + +// transportSendState distinguishes a connection that never carried the request +// from one that may have. A *url.Error wrapping *net.OpError is common: +// http.Client reports the outer operation as "Post", while the inner OpError +// still says "dial" when the connection was never established. +func transportSendState(err error) string { + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + return RequestStateNotSent + } + var opErr *net.OpError + if errors.As(err, &opErr) { + switch strings.ToLower(strings.TrimSpace(opErr.Op)) { + case "dial", "proxyconnect": + return RequestStateNotSent + case "write": + return RequestStateMaybeSent + case "read": + return RequestStateSent + } + } + message := strings.ToLower(err.Error()) + if strings.Contains(message, "tls handshake") || strings.Contains(message, "x509") { + return RequestStateNotSent + } + var urlErr *url.Error + if errors.As(err, &urlErr) { + switch strings.ToLower(strings.TrimSpace(urlErr.Op)) { + case "dial", "proxyconnect": + return RequestStateNotSent + } + if strings.Contains(strings.ToLower(urlErr.Error()), "connection refused") { + return RequestStateNotSent + } + // The outer operation is Post/Get, but the inner error did not prove + // whether bytes were written. + return RequestStateMaybeSent + } + return RequestStateUnknown +} + +func transportMayHaveSent(err error) bool { + return transportSendState(err) == RequestStateSent +} + +func transportPhase(err error) string { + switch transportSendState(err) { + case RequestStateNotSent: + return "connect" + case RequestStateMaybeSent: + return "request" + default: + return "response" + } +} + +func transportErrorMessage(err error) string { + var urlErr *url.Error + if errors.As(err, &urlErr) && urlErr.Err != nil { + // url.Error repeats the method and URL; exposing the URL can leak a + // proxy host or account path into a client-facing message. + return urlErr.Err.Error() + } + return err.Error() +} + // isTransportFailure reports whether err is a connection-level failure (dial, // TLS handshake, reset) rather than an answer from the upstream. http.Client // reports every such failure as *url.Error; a response that arrived comes back @@ -211,3 +575,14 @@ func isTransportFailure(err error) bool { var urlErr *url.Error return errors.As(err, &urlErr) } + +// isTimeoutError reports a transport timeout (dial, TLS handshake, response +// header, body read) rather than a caller cancellation. +func isTimeoutError(err error) bool { + var urlErr *url.Error + if errors.As(err, &urlErr) && urlErr.Timeout() { + return true + } + var netErr net.Error + return errors.As(err, &netErr) && netErr.Timeout() +} diff --git a/internal/executor/fefo.go b/internal/executor/fefo.go index b1297008e..5fbcb563e 100644 --- a/internal/executor/fefo.go +++ b/internal/executor/fefo.go @@ -196,29 +196,76 @@ func fefoCandidates(available []Item, publicModel string, now time.Time, resolve } // HasFEFOQuota reports whether a completed request could have consumed a -// trustworthy package balance. Runtime uses this gate to refresh only opt-in, -// supported routes; the historical strategies add no upstream traffic. +// trustworthy package balance under the global FEFO strategy. The legacy +// caller supplies a public model, so account aliases still apply. func (p *Pool) HasFEFOQuota(accountID, publicModel string) bool { + return p.hasFEFOQuotaForUse(accountID, publicModel, false, false) +} + +// HasRouteFEFOQuota checks the actual model key captured at dispatch. An +// aggregate FEFO path is eligible independently of the global pool strategy. +func (p *Pool) HasRouteFEFOQuota(accountID, concreteModel string, aggregateFEFO bool) bool { + return p.hasFEFOQuotaForUse(accountID, concreteModel, aggregateFEFO, true) +} + +func (p *Pool) hasFEFOQuotaForUse(accountID, model string, aggregateFEFO, concrete bool) bool { if p == nil || accountID == "" { return false } p.mu.Lock() defer p.mu.Unlock() - if p.routingStrategy != RoutingStrategyFEFO { + if !aggregateFEFO && p.routingStrategy != RoutingStrategyFEFO { + return false + } + item, ok := p.fefoQuotaAccountLocked(accountID) + if !ok { return false } + if !concrete { + model = effectiveCreditModel(item, model) + return model != "" && !itemServesFreeModel(item, model) + } + // The dispatched key is authoritative, even if it is also an alias in + // the current pool snapshot. Compare it directly to canonical free IDs. + if model == "" || model == "auto" || model != CanonicalModelID(model) { + return false + } + for _, free := range item.FreeModels { + if CanonicalModelID(free) == model { + return false + } + } + return true +} + +// FEFOQuotaAccount returns the latest item for a queued after-use refresh +// only while it still has trustworthy packages. Request-specific strategy +// and model checks belong to admission, not the account-wide fetch. +func (p *Pool) FEFOQuotaAccount(accountID string) (Item, bool) { + if p == nil || accountID == "" { + return Item{}, false + } + p.mu.Lock() + defer p.mu.Unlock() + item, ok := p.fefoQuotaAccountLocked(accountID) + if !ok { + return Item{}, false + } + return item.clone(), true +} + +func (p *Pool) fefoQuotaAccountLocked(accountID string) (Item, bool) { for _, item := range p.items { if item.ID != accountID { continue } - model := effectiveCreditModel(item, publicModel) - if model == "" || itemServesFreeModel(item, model) { - return false - } _, _, tracked := fefoQuotaState(item, time.Now()) - return tracked + if tracked { + return item, true + } + break } - return false + return Item{}, false } // FEFOQuotaDepleted reports whether an account routed by FEFO has a diff --git a/internal/executor/fefo_test.go b/internal/executor/fefo_test.go index 0c14b9853..0beb7cf92 100644 --- a/internal/executor/fefo_test.go +++ b/internal/executor/fefo_test.go @@ -317,3 +317,40 @@ func TestFEFOQuotaTrackingAndDepletion(t *testing.T) { t.Fatal("unknown dates must not be treated as depleted") } } + +func TestRouteFEFOQuotaChecksDispatchedKeyAndStrategy(t *testing.T) { + account := fefoItem("account", fefoPack(10, 0)) + account.FreeModels = []string{"FREE", "Vendor:Preview"} + account.ModelAliases = map[string]string{"public": "paid", "paid": "free", "free": "paid"} + untrusted := fefoItem("untrusted", fefoPack(10, 0)) + untrusted.Quota.Packages[0].Scope = "" + p := fefoPool(account, untrusted) + if !p.HasFEFOQuota(account.ID, "public") || p.HasFEFOQuota(account.ID, "paid") { + t.Fatal("legacy public names should still use one account alias lookup") + } + if !p.HasRouteFEFOQuota(account.ID, "paid", false) || p.HasRouteFEFOQuota(account.ID, "free", false) { + t.Fatal("dispatched keys must not resolve aliases even under global FEFO") + } + + p.SetRoutingStrategy(RoutingStrategyFillFirst) + if p.HasRouteFEFOQuota(account.ID, "paid", false) || !p.HasRouteFEFOQuota(account.ID, "paid", true) { + t.Fatal("only the selected aggregate FEFO path should bypass the global strategy") + } + for _, model := range []string{"", "auto", " Paid ", "free", "vendor:preview"} { + if p.HasRouteFEFOQuota(account.ID, model, true) { + t.Errorf("non-concrete or free model %q admitted to after-use refresh", model) + } + } + for _, id := range []string{"", "missing", untrusted.ID} { + if p.HasRouteFEFOQuota(id, "paid", true) { + t.Errorf("untracked account %q admitted to after-use refresh", id) + } + } + if item, ok := p.FEFOQuotaAccount(account.ID); !ok || item.ID != account.ID { + t.Fatalf("after-use worker could not find tracked account outside global FEFO: %q, %v", item.ID, ok) + } + p.MergeQuota(account.ID, untrusted.Quota) + if _, ok := p.FEFOQuotaAccount(account.ID); ok { + t.Fatal("after-use worker must not refresh an account once its packages lose their trusted scope") + } +} diff --git a/internal/executor/native_responses_test.go b/internal/executor/native_responses_test.go index 6da83d7bd..491d5260f 100644 --- a/internal/executor/native_responses_test.go +++ b/internal/executor/native_responses_test.go @@ -3,10 +3,14 @@ package executor import ( "context" "io" + "maps" "net/http" + "slices" "strings" "testing" + "time" + "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/providers" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -56,3 +60,145 @@ func TestNativeResponsesDispatchDoesNotRequireChatCompatibility(t *testing.T) { t.Fatalf("native request changed: model=%q input=%s", streamer.model, streamer.input) } } + +// A native-only adapter can fail either before the first frame is exposed or +// after response.created while the non-stream handler is buffering. Both +// failures must use the real member and the original request budget. +func TestNativeAggregateFailureUsesSameBudgetAndTarget(t *testing.T) { + for _, tc := range []struct { + name string + firstEvent string + stream bool + fallback bool + }{ + {name: "first-frame", stream: true, fallback: true}, + {name: "collect", firstEvent: "data: {\"type\":\"response.created\"}\n\n", fallback: true}, + {name: "single-attempt", firstEvent: "data: {\"type\":\"response.created\"}\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + var models []string + adapter := nativeDispatchFunc(func(accountID, upstreamModel string) string { + if accountID != "native-1" { + t.Errorf("account ID = %q", accountID) + } + models = append(models, upstreamModel) + if upstreamModel == "native-A" { + return tc.firstEvent + "event: response.failed\n" + + `data: {"type":"response.failed",` + "\n" + + `data: "response":{"status":"failed","error":{"status_code":429,"code":"tight_budget","message":"busy","retry_after":120}}}` + "\n\n" + } + return `data: {"type":"response.completed","response":{"status":"completed","output":[]}}` + "\n\n" + }) + p := NewPool(nil, nil) + p.Upsert(Item{ + ID: "native-1", Provider: "codex", Runtime: "in_process", MaxInFlight: 1, + Models: []string{"real-a", "real-b"}, ModelAliases: map[string]string{"alias-a": "real-a"}, + NativeModels: map[string]string{"real-a": "native-A", "real-b": "native-B"}, + }) + e := NewChatExecutor(p, "") + e.Providers = providers.NewRegistry() + e.Providers.Register(providers.Adapter{ID: "codex", NativeResponses: adapter}) + e.MaxAttempts = 1 // a prepared aggregate uses its own upper bound + var attempts []accounts.RequestAttempt + e.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, + AllowFallbacks: tc.fallback, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "codex", Model: "alias-a", Priority: 0}, + {Provider: "codex", Model: "real-b", Priority: 1}, + }, + }) + req := translate.ChatRequest{Model: "logical", Stream: tc.stream} + route := RouteInput{RequestID: "native-test", RouteModel: req.Model, AggregatePlan: plan} + native, err := translate.ParseNativeResponses([]byte(`{"model":"logical","input":"hi"}`)) + if err != nil { + t.Fatal(err) + } + if tc.stream { + result, err := e.ChatStreamProxyNativeResponsesPrepared(t.Context(), req, native, route) + if err != nil || result.CooldownModel != "real-b" || result.AttemptCount != 2 { + t.Fatalf("stream = %+v, err=%v", result, err) + } + defer result.Response.Body.Close() + _, err = translate.CollectResponses(result.Response.Body) + if err != nil { + t.Fatal(err) + } + e.FinishStream(t.Context(), result, nil) + result.Response.Body.Close() + } else { + result, err := e.NativeResponsesNonStreamPrepared(t.Context(), req, native, route) + if tc.fallback { + if err != nil || result.CooldownModel != "real-b" || result.AttemptCount != 2 { + t.Fatalf("buffered = %+v, err=%v", result, err) + } + } else if classified := ClassifyError(err); err == nil || result.AttemptCount != 1 || classified.Code != "tight_budget" || classified.Status != 429 || classified.RetryAfter != 120*time.Second { + t.Fatalf("terminal = %+v, class=%+v, err=%v", result, classified, err) + } + } + want := []string{"native-A"} + if tc.fallback { + want = append(want, "native-B") + } + if !slices.Equal(models, want) || len(attempts) != len(want) { + t.Fatalf("models=%v attempts=%+v, want %v", models, attempts, want) + } + for i, a := range attempts { + if a.AttemptIndex != i || a.AccountID != "native-1" || a.RequestID != route.RequestID { + t.Fatalf("attempt #%d = %+v", i, a) + } + } + item, _ := p.ByID("native-1") + if item.InFlight != 0 || len(item.ModelDownUntil) != 1 || item.ModelDownUntil["real-a"].IsZero() || !item.DownUntil.IsZero() { + t.Fatalf("feedback = %+v", item) + } + }) + } +} + +type nativeDispatchFunc func(accountID, upstreamModel string) string + +func (f nativeDispatchFunc) ResponsesStream(_ context.Context, id string, _ *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(f(id, options.Model)))}, providers.ResolvedChat{}, nil +} + +func TestNativeCapabilityProbeLeavesPoolAndAffinityUntouched(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a", Provider: "workbuddy", Region: "cn", Models: []string{"model"}, MaxInFlight: 1}) + p.Upsert(Item{ID: "b", Provider: "workbuddy", Region: "cn", Models: []string{"model"}, MaxInFlight: 1}) + if !p.Acquire("a") { + t.Fatal("cannot occupy the first account") + } + p.MarkClassified("b", Classified{Kind: accounts.KindRateLimit, Model: "model", Cooldown: time.Hour}) + e := NewChatExecutor(p, "") + e.Providers = providers.NewRegistry() + e.Providers.Register(providers.Adapter{ID: "workbuddy", NativeResponses: &nativeOnlyStreamer{}}) + e.SessionAffinity.Bind("missing", "deleted") + before := e.SessionAffinity.Stats() + cursor, region := maps.Clone(p.lastPicked), maps.Clone(p.lastRegion) + req := translate.ChatRequest{Model: "model"} + route := RouteInput{RouteModel: req.Model, SessionKey: "missing", AllowedProviders: []string{"workbuddy:cn"}} + if !e.HasNativeResponsesRoutePrepared(t.Context(), req, route) { + t.Fatal("cooldown and contention hid an in-scope native route") + } + plan := NewAggregatePlan(accounts.Aggregation{ID: "logical", Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{{Provider: "workbuddy", Model: "model"}}}) + route.AggregatePlan, route.RouteModel = plan, plan.ID + if !e.HasNativeResponsesRoutePrepared(t.Context(), req, route) { + t.Fatal("cooldown and contention hid an in-scope aggregate native route") + } + route.RegionFilter = "global" + if e.HasNativeResponsesRoutePrepared(t.Context(), req, route) { + t.Fatal("probe bypassed the region/grant intersection") + } + a, _ := p.ByID("a") + b, _ := p.ByID("b") + if a.InFlight != 1 || b.InFlight != 0 || b.ModelDownUntil["model"].IsZero() || !maps.Equal(cursor, p.lastPicked) || !maps.Equal(region, p.lastRegion) { + t.Fatalf("probe changed the pool: a=%+v b=%+v", a, b) + } + if got := e.SessionAffinity.Stats(); got != before { + t.Fatalf("probe changed affinity statistics: before=%+v after=%+v", before, got) + } + if bound, ok := e.SessionAffinity.Peek("missing"); !ok || bound != "deleted" { + t.Fatalf("probe changed the prior binding: %q, %t", bound, ok) + } + p.Release("a") +} diff --git a/internal/executor/pool.go b/internal/executor/pool.go index 71991fe47..04a474dd0 100644 --- a/internal/executor/pool.go +++ b/internal/executor/pool.go @@ -2,7 +2,10 @@ package executor import ( "log" + "maps" + "slices" "sort" + "strconv" "strings" "sync" "time" @@ -50,6 +53,10 @@ type Item struct { // spelling so Trae config_name case is preserved. Models []string ModelsAt time.Time + // NoToolsModels lists catalog IDs whose provider entry explicitly declares + // that the model cannot call tools. Matching is canonical; nil means the + // account has no negative catalog fact, so routing fails open. + NoToolsModels []string // NativeModels maps a canonical public model ID onto the provider-native // key its own catalog uses for that model. Qoder's catalog carries a // distinct mapped_key ("qfmodel") behind a friendly public ID, and its @@ -82,6 +89,11 @@ type Item struct { // model-A look like a repeat. The account-wide LastKind covers // non-model-scoped failures. ModelLastKind map[string]string + // modelFeedback is short-lived, process-local model availability state. It + // keeps explicit model rejections scoped to one canonical model and records + // a per-model revision so a request selected before rejection cannot report + // stale success after a catalog refresh. It is deliberately not persisted. + modelFeedback map[string]modelFeedbackState // BackoffLevel climbs on repeated failures of the same kind and resets // on success, so a persistently failing account backs off instead of // being retried at a fixed interval. @@ -106,7 +118,7 @@ type Item struct { } // RouteQuery selects candidates for one public model request. Empty fields are -// not filtered; excluded account IDs are honored before anything else. +// not filtered; exclusions may target an entire account or one of its models. type RouteQuery struct { PublicModel string PreferAccount string @@ -114,9 +126,14 @@ type RouteQuery struct { RegionFilter string AllowedProviders []string Excluded map[string]struct{} + ExcludedModels map[routeModelKey]struct{} + // preferAffinity is a soft session hint. An unsupported model on this + // account must not block other candidates in the same route scope. + preferAffinity bool // Eligible, when set, admits only items that can serve the request's // protocol (for example native Responses input the chat form cannot - // carry). Nil admits every item. + // carry). Nil admits every item. Like ModelResolver, it must be a pure + // function and may not call back into the pool. Eligible func(Item) bool // ModelResolver, when set, maps an item to the concrete model it should // serve for this request (used by aggregated/virtual model IDs). It MUST be @@ -134,12 +151,41 @@ type RouteQuery struct { // fefoNow is set only by a FEFO pool. Other strategies keep the historical // quota gate, even when a cached package has since expired. fefoNow time.Time - // creditFloorDefault is the global floor, filled in by PickRoute from the - // pool. An account's Item.CreditFloor override wins when non-nil. + // creditFloorDefault is the global floor, filled in by the pool from the + // current configuration. An account's CreditFloor override wins when non-nil. creditFloorDefault float64 percentFloorDefault float64 } +type routeModelKey struct{ AccountID, Model string } + +type modelFeedbackState struct { + version uint64 + rejectedUntil time.Time + updatedAt time.Time +} + +const ( + modelRejectionTTL = 5 * time.Minute + maxModelFeedbackPerItem = 512 +) + +func accountRouteModelKey(item Item, model string) routeModelKey { + key := cooldownModel(item, model) + if key == "" { + key = "auto" + } + return routeModelKey{AccountID: item.ID, Model: key} +} + +func routeModelExcluded(item Item, model string, q RouteQuery) bool { + if len(q.ExcludedModels) == 0 { + return false + } + _, excluded := q.ExcludedModels[accountRouteModelKey(item, model)] + return excluded +} + // effectiveModel returns the concrete model to match/cooldown for an item. // Without a resolver this is exactly PublicModel, so all existing routes are // byte-for-byte equivalent. @@ -188,6 +234,61 @@ func itemHasProvenModel(item Item, want string) bool { return false } +func modelRejected(item Item, model string, now time.Time) bool { + key := routeModel(model) + if key == "" { + return false + } + state, ok := item.modelFeedback[key] + return ok && now.Before(state.rejectedUntil) +} + +func modelFeedbackVersion(item Item, model string) uint64 { + return item.modelFeedback[routeModel(model)].version +} + +func recordModelRejection(item *Item, model string, version uint64, now time.Time) { + if item == nil { + return + } + if item.modelFeedback == nil { + item.modelFeedback = make(map[string]modelFeedbackState) + } + if _, exists := item.modelFeedback[model]; !exists && len(item.modelFeedback) >= maxModelFeedbackPerItem { + // Keep the map bounded. Prefer evicting a recovered/expired entry; if + // every entry is still actively rejected, evict the oldest rejection. + // The cap is per account and far above a normal provider catalog. + oldestKey := "" + oldestActive := false + var oldest time.Time + for key, state := range item.modelFeedback { + active := now.Before(state.rejectedUntil) + if oldestKey == "" || (oldestActive && !active) || (oldestActive == active && state.updatedAt.Before(oldest)) || + (oldestActive == active && state.updatedAt.Equal(oldest) && key < oldestKey) { + oldestKey, oldestActive, oldest = key, active, state.updatedAt + } + } + delete(item.modelFeedback, oldestKey) + } + item.modelFeedback[model] = modelFeedbackState{ + version: version, rejectedUntil: now.Add(modelRejectionTTL), updatedAt: now, + } +} + +func clearModelRejection(item *Item, model string, now time.Time) { + key := routeModel(model) + if item == nil || key == "" { + return + } + state, ok := item.modelFeedback[key] + if !ok || state.rejectedUntil.IsZero() { + return + } + state.rejectedUntil = time.Time{} + state.updatedAt = now + item.modelFeedback[key] = state +} + func rememberProvenModel(item *Item, model string) { if item == nil { return @@ -235,6 +336,9 @@ func itemCouldServeModel(item Item, publicModel string) bool { if target := item.ModelAliases[want]; target != "" { want = routeModel(target) } + if modelRejected(item, want, time.Now()) { + return false + } if itemHasCatalogModel(item, want) || itemHasProvenModel(item, want) { return true } @@ -296,6 +400,9 @@ func itemHasModel(item Item, publicModel string) bool { if target := item.ModelAliases[want]; target != "" { want = routeModel(target) } + if modelRejected(item, want, time.Now()) { + return false + } if itemHasCatalogModel(item, want) || itemHasProvenModel(item, want) { return true } @@ -415,14 +522,7 @@ func routeReadyAndScoped(item Item, q RouteQuery) bool { // that its quota is exceeded. Free-model accounts are never quota-blocked: // they spend no credits, so an exhausted account can still serve them. func routeBlockedByQuota(item Item, q RouteQuery) bool { - if !routeQuotaExceeded(item, q) { - return false - } - resolved, ok := routeResolvedModel(item, q) - if !ok { - return false - } - return routeReadyAndScoped(item, q) && itemCouldServeModel(item, resolved) + return routeQuotaExceeded(item, q) && routeHasModelCandidate(item, q) } // routeResolvedModel returns the concrete model this item serves for the @@ -446,20 +546,36 @@ func routeMatches(item Item, q RouteQuery) bool { return false } resolved, ok := routeResolvedModel(item, q) - return ok && itemHasModel(item, resolved) + return ok && !routeModelExcluded(item, resolved, q) && itemHasModel(item, resolved) } func routeHintMatches(item Item, q RouteQuery) bool { - if !routeBaseMatches(item, q) { + return !routeQuotaExceeded(item, q) && routeHasModelCandidate(item, q) +} + +func routeHasModelCandidate(item Item, q RouteQuery) bool { + if !routeReadyAndScoped(item, q) { return false } resolved, ok := routeResolvedModel(item, q) - return ok && itemCouldServeModel(item, resolved) + return ok && !routeModelExcluded(item, resolved, q) && itemCouldServeModel(item, resolved) +} + +func routeDispatchable(item Item, q RouteQuery, now time.Time) bool { + return !itemSaturated(item) && routeMatchesNow(item, q, now) +} + +func routeMatchesNow(item Item, q RouteQuery, now time.Time) bool { + return !itemDown(item, now) && routeMatches(item, q) && !itemModelDown(item, q, now) } type Pool struct { mu sync.Mutex items []Item + // Removed accounts can be reinserted by a runtime restart before old + // requests release their slots. Keep those reservations by logical ID + // until their last release or until Upsert makes the account live again. + detachedSlots map[string]inFlightSlots // lastPicked tracks the rotation cursor per route, keyed by // provider|region|model, as the *ID* of the previous pick. // @@ -483,14 +599,19 @@ type Pool struct { // have no per-account override. Zero disables the floor. Guarded by mu. defaultCreditFloor float64 defaultPercentFloor float64 - // stateCounter is the monotonic source for Item.StateVersion. Bumped - // under p.mu on every persistable mutation, so the version stamped onto - // a snapshot reflects its true production order even though the observer - // runs after the lock is released. + // stateCounter allocates monotonic versions for Item.StateVersion and + // per-model feedback. Persistable mutations stamp Item.StateVersion under + // p.mu so observer snapshots keep production order; a model rejection can + // consume a version without invalidating unrelated models account-wide. stateCounter uint64 observer PoolObserver } +type inFlightSlots struct { + count int + since time.Time +} + // PoolObserver receives a cloned Item after a persistable mutation // (MarkClassified / MarkOK). The callback is data-only: Pool never // accepts *Store, and the Manager persist goroutine is the writer. @@ -529,6 +650,18 @@ func (p *Pool) effectiveRoutingStrategy(q RouteQuery) string { return strategy } +// configureRouteLocked takes the routing configuration for a decision made +// under p.mu. Quota and strategy must be evaluated from the same snapshot. +func (p *Pool) configureRouteLocked(q RouteQuery, now time.Time) (RouteQuery, string) { + strategy := p.effectiveRoutingStrategy(q) + if strategy == RoutingStrategyFEFO { + q.fefoNow = now + } + q.creditFloorDefault = p.defaultCreditFloor + q.percentFloorDefault = p.defaultPercentFloor + return q, strategy +} + func NewPool(urls []string, ids []string) *Pool { items := make([]Item, 0, len(urls)) for i, url := range urls { @@ -576,7 +709,7 @@ func (p *Pool) SetCreditFloor(id string, floor *float64) { defer p.mu.Unlock() for i := range p.items { if p.items[i].ID == id { - p.items[i].CreditFloor = floor + p.items[i].CreditFloor = clonePoolValue(floor) return } } @@ -591,7 +724,7 @@ func (p *Pool) SetPercentFloor(id string, floor *float64) { defer p.mu.Unlock() for i := range p.items { if p.items[i].ID == id { - p.items[i].PercentFloor = floor + p.items[i].PercentFloor = clonePoolValue(floor) return } } @@ -636,8 +769,6 @@ func (p *Pool) Len() int { return p.LenRoute(RouteQuery{}) } -// LenRoute counts the candidate set for one route query, so retry attempts -// match the current pool instead of every registered account. // ReadyItems returns ready accounts for a route without moving a cursor. func (p *Pool) ReadyItems(q RouteQuery) []Item { if p == nil { @@ -646,15 +777,11 @@ func (p *Pool) ReadyItems(q RouteQuery) []Item { p.mu.Lock() defer p.mu.Unlock() now := time.Now() - if p.effectiveRoutingStrategy(q) == RoutingStrategyFEFO { - q.fefoNow = now - } - q.creditFloorDefault = p.defaultCreditFloor - q.percentFloorDefault = p.defaultPercentFloor + q, _ = p.configureRouteLocked(q, now) out := make([]Item, 0) for _, item := range p.items { - if routeMatches(item, q) && !itemDown(item, now) && !itemModelDown(item, q, now) && !itemSaturated(item) { - out = append(out, item) + if routeDispatchable(item, q, now) { + out = append(out, item.clone()) } } return out @@ -669,21 +796,12 @@ func (p *Pool) RotateIDs(key string, ids []string, advance bool) []string { } p.mu.Lock() defer p.mu.Unlock() - p.ensureRotationKey(key) start := 0 if last, ok := p.lastPicked[key]; ok { - for i, id := range ids { - if id == last { - if advance { - start = (i + 1) % len(ids) - } else { - start = i - } - break - } - } + start = rotationStart(ids, last, advance) } if advance { + p.ensureRotationKey(key) p.lastPicked[key] = ids[start] } out := make([]string, 0, len(ids)) @@ -692,17 +810,30 @@ func (p *Pool) RotateIDs(key string, ids []string, advance bool) []string { return out } +// rotationStart reads an already ordered list without moving its cursor. A +// composite route can scan from here and commit the winning seat only after +// reserving a slot while still holding p.mu. +func rotationStart(ids []string, last string, after bool) int { + for i, id := range ids { + if id == last { + if after { + return (i + 1) % len(ids) + } + return i + } + } + return 0 +} + +// LenRoute counts the candidate set for one route query, so retry attempts +// match the current pool instead of every registered account. func (p *Pool) LenRoute(q RouteQuery) int { if p == nil { return 0 } p.mu.Lock() defer p.mu.Unlock() - if p.effectiveRoutingStrategy(q) == RoutingStrategyFEFO { - q.fefoNow = time.Now() - } - q.creditFloorDefault = p.defaultCreditFloor - q.percentFloorDefault = p.defaultPercentFloor + q, _ = p.configureRouteLocked(q, time.Now()) count := 0 for _, item := range p.items { if routeMatches(item, q) { @@ -723,13 +854,26 @@ func (p *Pool) HasCapacity(q RouteQuery) bool { p.mu.Lock() defer p.mu.Unlock() now := time.Now() - if p.effectiveRoutingStrategy(q) == RoutingStrategyFEFO { - q.fefoNow = now + q, _ = p.configureRouteLocked(q, now) + for _, item := range p.items { + if routeDispatchable(item, q, now) { + return true + } } - q.creditFloorDefault = p.defaultCreditFloor - q.percentFloorDefault = p.defaultPercentFloor + return false +} + +// HasRoute reports whether a ready, in-scope account belongs to the route, +// regardless of quota, cooldown, or slot capacity. Protocol probes use it +// without changing the scheduler or mistaking temporary load for no route. +func (p *Pool) HasRoute(q RouteQuery) bool { + if p == nil { + return false + } + p.mu.Lock() + defer p.mu.Unlock() for _, item := range p.items { - if routeMatches(item, q) && !itemDown(item, now) && !itemModelDown(item, q, now) && !itemSaturated(item) { + if routeHasModelCandidate(item, q) { return true } } @@ -746,26 +890,25 @@ func (p *Pool) QuotaBlockedForModel(q RouteQuery) (Item, bool) { } p.mu.Lock() defer p.mu.Unlock() - if p.effectiveRoutingStrategy(q) == RoutingStrategyFEFO { - q.fefoNow = time.Now() - } - q.creditFloorDefault = p.defaultCreditFloor - q.percentFloorDefault = p.defaultPercentFloor + q, _ = p.configureRouteLocked(q, time.Now()) for _, item := range p.items { if routeBlockedByQuota(item, q) { - return item, true + return item.clone(), true } } return Item{}, false } func (p *Pool) First() (Item, bool) { - if p == nil || len(p.items) == 0 { + if p == nil { return Item{}, false } p.mu.Lock() defer p.mu.Unlock() - return p.items[0], true + if len(p.items) == 0 { + return Item{}, false + } + return p.items[0].clone(), true } func (p *Pool) ByID(id string) (Item, bool) { @@ -776,7 +919,7 @@ func (p *Pool) ByID(id string) (Item, bool) { defer p.mu.Unlock() for _, item := range p.items { if item.ID == id { - return item, true + return item.clone(), true } } return Item{}, false @@ -790,44 +933,86 @@ func (p *Pool) Pick(prefer string, excluded map[string]struct{}) (Item, bool) { // round-robin are applied in that order. The fallback path returns the item // with the earliest cooldown so callers can surface a classified error. func (p *Pool) PickRoute(q RouteQuery) (Item, bool) { - if p == nil || len(p.items) == 0 { - return Item{}, false + pick := p.selectRoute(q, false, nil) + return pick.item, pick.found +} + +// ReserveRoute selects and reserves a dispatchable account under the same lock. +// Only reserved=true owns a slot and requires Release(item.ID). When found is +// true but reserved is false, item is a cooldown hint, never a dispatch target. +func (p *Pool) ReserveRoute(q RouteQuery) (item Item, found, reserved bool) { + item, found, reserved, _ = p.reserveRoute(q) + return item, found, reserved +} + +// reserveRoute also reports whether an otherwise dispatchable account was +// at capacity when there was neither a reservation nor a cooldown hint. +func (p *Pool) reserveRoute(q RouteQuery) (item Item, found, reserved, saturated bool) { + pick := p.selectRoute(q, true, nil) + return pick.item, pick.found, pick.reserved, pick.saturated +} + +type routeSelection struct { + item Item + found bool + reserved bool + saturated bool + staleAffinityModel bool + widened bool +} + +func (p *Pool) selectRoute(q RouteQuery, reserve bool, hardScope *RouteQuery) routeSelection { + if p == nil { + return routeSelection{} } p.mu.Lock() defer p.mu.Unlock() now := time.Now() - strategy := p.effectiveRoutingStrategy(q) - if strategy == RoutingStrategyFEFO { - q.fefoNow = now - } - q.creditFloorDefault = p.defaultCreditFloor - q.percentFloorDefault = p.defaultPercentFloor - eligible := make([]int, 0, len(p.items)) - for i, item := range p.items { - if routeMatches(item, q) { - eligible = append(eligible, i) + pick := p.selectRouteLocked(q, reserve, now) + // Only a proven model miss on the soft preference permits this wider + // search. Neither a miss nor a cooldown hint has reserved or rotated. + if reserve && hardScope != nil && !pick.reserved && pick.staleAffinityModel { + if wide := p.selectRouteLocked(*hardScope, true, now); wide.reserved { + wide.staleAffinityModel, wide.widened = true, true + return wide } } + return pick +} + +func (p *Pool) selectRouteLocked(q RouteQuery, reserve bool, now time.Time) routeSelection { + q, strategy := p.configureRouteLocked(q, now) + var staleAffinityModel bool if q.PreferAccount != "" { - var pinned *Item for i := range p.items { - if p.items[i].ID != q.PreferAccount { + pinned := &p.items[i] + if pinned.ID != q.PreferAccount { continue } - copy := p.items[i] - pinned = © - break - } - if pinned != nil { - if _, skip := q.Excluded[pinned.ID]; !skip { - if routeModel(q.PublicModel) != "" && !itemCouldServeModel(*pinned, effectiveModel(*pinned, q)) { - return Item{}, false + if _, skip := q.Excluded[pinned.ID]; skip { + break + } + model := effectiveModel(*pinned, q) + if routeModelExcluded(*pinned, model, q) { + break + } + if q.preferAffinity { + // Repeat the model and alias/protocol eligibility checks from + // routeScope against the current item under the pool lock. + if !stickyAccountCanServeModel(*pinned, model) || (q.Eligible != nil && !q.Eligible(*pinned)) { + staleAffinityModel = true + break } - if routeMatches(*pinned, q) && !itemDown(*pinned, now) && - !itemModelDown(*pinned, q, now) && !itemSaturated(*pinned) { - return *pinned, true + } else if routeModel(q.PublicModel) != "" && !itemCouldServeModel(*pinned, model) { + return routeSelection{} + } + if routeDispatchable(*pinned, q, now) { + if reserve { + acquireItemLocked(pinned, now) } + return routeSelection{item: pinned.clone(), found: true, reserved: reserve} } + break } // Historical Qoder clients may pin an unknown account label; fall back // to normal scheduling like the pre-provider pool did. A cooling pin @@ -835,12 +1020,17 @@ func (p *Pool) PickRoute(q RouteQuery) (Item, bool) { } // Candidates that are ready right now. Sorted by ID so the rotation // cursor can resume from the previous pick even as the set changes. - available := make([]Item, 0, len(eligible)) - for _, i := range eligible { - item := p.items[i] - if !itemDown(item, now) && !itemModelDown(item, q, now) && !itemSaturated(item) { - available = append(available, item) + available := make([]Item, 0, len(p.items)) + saturated := false + for _, item := range p.items { + if !routeMatchesNow(item, q, now) { + continue + } + if itemSaturated(item) { + saturated = true + continue } + available = append(available, item) } if len(available) == 0 { // Nothing is ready right now. Distinguish the two failure modes so @@ -851,28 +1041,30 @@ func (p *Pool) PickRoute(q RouteQuery) (Item, bool) { // If any account is cooling, surface the one that frees up soonest so // the caller can report a classified retry-after error. var best Item - found := false - for i := range p.items { - item := p.items[i] - if !routeHintMatches(item, q) { + var bestAt time.Time + for _, item := range p.items { + until := resumeAt(item, q) + if !now.Before(until) || !routeHintMatches(item, q) { continue } - if !itemDown(item, now) && !itemModelDown(item, q, now) { - // Saturated only — skip; not a candidate for the retry hint. - continue - } - if !found || resumeAt(item, q).Before(resumeAt(best, q)) { - best = item - found = true + if bestAt.IsZero() || until.Before(bestAt) { + best, bestAt = item, until } } - return best, found + found := !bestAt.IsZero() + return routeSelection{item: best.clone(), found: found, saturated: !found && saturated, staleAffinityModel: staleAffinityModel} } - // Priority strategy: order candidates by the aggregation member's - // configured priority (lower first), then ID for a stable tie-break. The - // existing failover loop excludes the picked account on error, which - // naturally falls through to the next priority. - if strategy == AggregationStrategyPriority && q.PriorityResolver != nil { + key := rotationKey(q) + priorityReserve := reserve && strategy == AggregationStrategyPriority + if priorityReserve { + // Each usable priority tier has its own ID cursor. An interlude in + // a fallback tier cannot perturb ordering in the preferred tier. + var tier int + available, tier = lowestPriorityItems(available, q.PriorityResolver) + key += "|priority|" + strconv.Itoa(tier) + } + if strategy == AggregationStrategyPriority && q.PriorityResolver != nil && !priorityReserve { + // Compatibility: non-reserving priority picks used a fixed ID tie-break. sort.SliceStable(available, func(i, j int) bool { pi, pj := q.PriorityResolver(available[i]), q.PriorityResolver(available[j]) if pi != pj { @@ -883,8 +1075,14 @@ func (p *Pool) PickRoute(q RouteQuery) (Item, bool) { } else { sort.Slice(available, func(i, j int) bool { return available[i].ID < available[j].ID }) } - key := rotationKey(q) - p.ensureRotationKey(key) + lastID, seen := p.lastPicked[key] + lastRegion := p.lastRegion[key] + weightCounters := p.weightCounter[key] + if !seen && len(p.lastPicked) >= rotationLimit { + // A successful pick here will reset the cursor maps. Rank as if the + // reset has happened, without mutating them before the reservation. + lastRegion, weightCounters = "", nil + } // When the caller has not pinned a region, keep serving the region this // route used last (if it still has a candidate). Request handlers pin the // region from the first account picked, so an unpinned pick decides the @@ -899,70 +1097,73 @@ func (p *Pool) PickRoute(q RouteQuery) (Item, bool) { // or an aggregated model whose members carry their own provider/region) // must rank every member; latching one region would silently pin the whole // route to that region's provider and strand the other members. - if q.RegionFilter == "" && q.ModelResolver == nil && !crossProviderCandidates(available) && !isQuotaRoutingStrategy(strategy) { - if previous, ok := p.lastRegion[key]; ok { - // The latch is a hint, not a commitment: the pool can change - // underneath it. Keep the remembered region only while it still - // carries a fair share of the route; a latch left far behind by - // a bulk pool change is dropped so the route re-seats below. - if subset := inRegion(available, previous); len(subset) > 0 && !regionLatchStale(len(subset), available) { - available = subset - } else { - delete(p.lastRegion, key) - } + if !priorityReserve && q.RegionFilter == "" && q.ModelResolver == nil && !crossProviderCandidates(available) && !isQuotaRoutingStrategy(strategy) { + if subset := inRegion(available, lastRegion); len(subset) > 0 && !regionLatchStale(len(subset), available) { + available = subset + } else if preferred := largestRegion(available); preferred != "" { + available = inRegion(available, preferred) } - if _, ok := p.lastRegion[key]; !ok { - if preferred := largestRegion(available); preferred != "" { - p.lastRegion[key] = preferred - if subset := inRegion(available, preferred); len(subset) > 0 { - available = subset - } - } - } - } else { - p.lastRegion[key] = itemRegion(available[0]) } if strategy == RoutingStrategyFEFO { available = fefoCandidates(available, q.PublicModel, now, q.ModelResolver) } - // Priority order always uses the highest-priority available member; on - // failure the route loop excludes it and the next retry takes the next one. - if strategy == AggregationStrategyPriority { - picked := available[0] - p.lastPicked[key] = picked.ID - p.lastRegion[key] = itemRegion(picked) - return picked, true - } - if strategy == RoutingStrategyLeastQuotaFirst || strategy == RoutingStrategyMostQuotaFirst { - picked := pickQuotaStrategy(available, strategy == RoutingStrategyMostQuotaFirst, p.lastPicked[key]) - p.lastPicked[key] = picked.ID - p.lastRegion[key] = itemRegion(picked) - return picked, true - } - if strategy == RoutingStrategyFillFirst { - picked := pickFillFirstWithWeight(available, q) - p.lastPicked[key] = picked.ID - p.lastRegion[key] = itemRegion(picked) - return picked, true - } - if strategy == RoutingStrategyWeightedRoundRobin { - weighted, ok := p.pickWeighted(available, key, q) - if !ok { - picked := available[successorIndex(available, p.lastPicked[key])] - p.lastPicked[key] = picked.ID - p.lastRegion[key] = itemRegion(picked) - return picked, true - } - // Differentiated weights: smooth weighted round-robin keeps the load - // proportional without bursting one high-weight account first. - p.lastPicked[key] = weighted.ID - p.lastRegion[key] = itemRegion(weighted) - return weighted, true - } - picked := available[successorIndex(available, p.lastPicked[key])] + var picked Item + var totalWeight int64 + switch strategy { + case AggregationStrategyPriority: + if priorityReserve { + picked = available[successorIndex(available, lastID)] + } else { + picked = available[0] + } + case RoutingStrategyLeastQuotaFirst, RoutingStrategyMostQuotaFirst: + picked = pickQuotaStrategy(available, strategy == RoutingStrategyMostQuotaFirst, lastID) + case RoutingStrategyFillFirst: + picked = pickFillFirstWithWeight(available, q) + case RoutingStrategyWeightedRoundRobin: + picked, totalWeight = pickWeighted(available, weightCounters, q) + if totalWeight == 0 { + picked = available[successorIndex(available, lastID)] + } + default: + picked = available[successorIndex(available, lastID)] + } + if reserve { + // The candidate set and p.items cannot change between selection and + // this write. If a legacy pool was supplied duplicate IDs, keep the + // first-ID ownership rule used by Acquire and Release. + i := p.itemIndexLocked(picked.ID) + if i < 0 || !routeDispatchable(p.items[i], q, now) { + return routeSelection{saturated: saturated || (i >= 0 && itemSaturated(p.items[i])), staleAffinityModel: staleAffinityModel} + } + acquireItemLocked(&p.items[i], now) + picked = p.items[i] + } + p.ensureRotationKey(key) + if totalWeight != 0 { + p.commitWeighted(available, key, q, picked.ID, totalWeight) + } p.lastPicked[key] = picked.ID p.lastRegion[key] = itemRegion(picked) - return picked, true + return routeSelection{item: picked.clone(), found: true, reserved: reserve, staleAffinityModel: staleAffinityModel} +} + +func lowestPriorityItems(items []Item, priority func(Item) int) ([]Item, int) { + if priority == nil { + return items, 0 + } + tier := priority(items[0]) + best := items[:1] + for _, item := range items[1:] { + rank := priority(item) + if rank < tier { + tier, best = rank, best[:0] + } + if rank == tier { + best = append(best, item) + } + } + return best, tier } func pickFillFirst(available []Item) Item { @@ -1053,49 +1254,47 @@ func pickQuotaStrategy(available []Item, most bool, lastID string) Item { return best[successorIndex(best, lastID)] } -// pickWeighted runs smooth weighted round-robin when candidates have differing -// weights. It reports false when every candidate shares one weight, which -// leaves plain round-robin in charge: with a uniform pool the two are -// equivalent, and the ID cursor is what keeps rotation stable across a -// changing candidate set. -func (p *Pool) pickWeighted(available []Item, key string, q RouteQuery) (Item, bool) { +// pickWeighted ranks a smooth WRR turn without changing its counters. A zero +// total means weights are uniform (or invalid), so the caller uses the plain +// ID cursor, which is stable even as candidates enter or leave the set. +func pickWeighted(available []Item, counters map[string]int64, q RouteQuery) (Item, int64) { total := int64(0) uniform := true first := routeItemWeight(available[0], q) - for _, item := range available { + best := available[0] + var bestCurrent int64 + for i, item := range available { weight := int64(routeItemWeight(item, q)) total += weight if weight != int64(first) { uniform = false } + if current := counters[item.ID] + weight; i == 0 || current > bestCurrent { + best, bestCurrent = item, current + } } if uniform || total <= 0 { - return Item{}, false + return Item{}, 0 } + return best, total +} + +// commitWeighted applies the winning WRR turn under p.mu. Give each current +// candidate its weight, then debit the total from the winner; this spreads +// picks in proportion to their weights without a burst at the start. +func (p *Pool) commitWeighted(available []Item, key string, q RouteQuery, winner string, total int64) { if p.weightCounter == nil { p.weightCounter = map[string]map[string]int64{} } - if p.weightCounter[key] == nil { - p.weightCounter[key] = map[string]int64{} - } - // Smooth WRR: add each candidate's weight to its running counter and take - // the largest, then subtract the total from the winner. This spreads picks - // evenly across a window instead of front-loading the heaviest candidate. - best := -1 - var bestCurrent int64 - for i := range available { - current := p.weightCounter[key][available[i].ID] + int64(routeItemWeight(available[i], q)) - p.weightCounter[key][available[i].ID] = current - if best < 0 || current > bestCurrent { - best = i - bestCurrent = current - } + counters := p.weightCounter[key] + if counters == nil { + counters = map[string]int64{} + p.weightCounter[key] = counters } - if best < 0 { - return Item{}, false + for _, item := range available { + counters[item.ID] += int64(routeItemWeight(item, q)) } - p.weightCounter[key][available[best].ID] -= total - return available[best], true + counters[winner] -= total } // successorIndex returns the position of the first candidate ordered after @@ -1200,8 +1399,8 @@ func inRegion(items []Item, region string) []Item { } // itemSaturated reports whether the account already serves its configured -// concurrency limit. InFlight is owned by Acquire/Release on the request -// path; PickRoute uses this to skip accounts already at capacity. +// concurrency limit. Only request-path reservations and releases change the +// live count; selection skips accounts already at capacity. func itemSaturated(item Item) bool { if item.MaxInFlight <= 0 { return false @@ -1428,6 +1627,20 @@ func (p *Pool) ClearAccountQuotaCooldown(id string) { // model is empty the account is treated as fully healthy: account-wide // cooldown, backoff, and all model-scoped state are cleared. func (p *Pool) MarkOK(id, model string) { + p.markOK(id, model, nil) +} + +// markRouteOK records a completed dispatch against its concrete cooldown +// key. Unlike the administrative reset, auto is not evidence that all the +// account's models recovered. A late success must not overwrite state that +// changed after the account was selected. +func (p *Pool) markRouteOK(item Item, model string) { + if routeModel(model) != "" { + p.markOK(item.ID, model, &item) + } +} + +func (p *Pool) markOK(id, model string, selected *Item) { if p == nil || id == "" { return } @@ -1438,6 +1651,12 @@ func (p *Pool) MarkOK(id, model string) { continue } scoped := routeModel(model) + if selected != nil && (p.items[i].StateVersion != selected.StateVersion || + !p.items[i].DownUntil.Equal(selected.DownUntil) || + !p.items[i].ModelDownUntil[scoped].Equal(selected.ModelDownUntil[scoped]) || + modelFeedbackVersion(p.items[i], scoped) != modelFeedbackVersion(*selected, scoped)) { + break + } if scoped != "" { wasCooling := false if until, ok := p.items[i].ModelDownUntil[scoped]; ok && time.Now().Before(until) { @@ -1473,6 +1692,7 @@ func (p *Pool) MarkOK(id, model string) { p.items[i].LastKind = "" p.items[i].BackoffLevel = 0 } + clearModelRejection(&p.items[i], scoped, time.Now()) rememberProvenModel(&p.items[i], model) } else { // Account-wide success: the account proved it can serve traffic. @@ -1497,9 +1717,7 @@ func (p *Pool) MarkOK(id, model string) { } } -// SetDropSystemPrompt updates only the request-sanitization flag on a live -// item. Routing and runtime state stay untouched so the change applies to the -// next request without disturbing cooldowns or health. +// SetModelRouting replaces the aliases and allowed-model settings for an account. func (p *Pool) SetModelRouting(id string, aliases map[string]string, enabled []string, restricted bool) { if p == nil || id == "" { return @@ -1513,7 +1731,7 @@ func (p *Pool) SetModelRouting(id string, aliases map[string]string, enabled []s if len(aliases) == 0 { p.items[i].ModelAliases = nil } else { - p.items[i].ModelAliases = aliases + p.items[i].ModelAliases = maps.Clone(aliases) } if len(enabled) == 0 { p.items[i].EnabledModels = nil @@ -1525,6 +1743,8 @@ func (p *Pool) SetModelRouting(id string, aliases map[string]string, enabled []s } } +// SetDropSystemPrompt updates the request-sanitization flag without changing +// the account's routing or health state. func (p *Pool) SetDropSystemPrompt(id string, drop bool) { if p == nil || id == "" { return @@ -1593,42 +1813,58 @@ func (p *Pool) Acquire(id string) bool { } p.mu.Lock() defer p.mu.Unlock() + i := p.itemIndexLocked(id) + if i < 0 || itemSaturated(p.items[i]) { + return false + } + acquireItemLocked(&p.items[i], time.Now()) + return true +} + +// acquireItemLocked is shared by all selectors. The caller holds p.mu and +// has already established that the item has room. +func acquireItemLocked(item *Item, now time.Time) { + if item.InFlight == 0 { + item.InFlightSince = now + } + item.InFlight++ +} + +func (p *Pool) itemIndexLocked(id string) int { for i := range p.items { - if p.items[i].ID != id { - continue - } - if p.items[i].MaxInFlight > 0 && p.items[i].InFlight >= p.items[i].MaxInFlight { - return false - } - if p.items[i].InFlight == 0 { - p.items[i].InFlightSince = time.Now() + if p.items[i].ID == id { + return i } - p.items[i].InFlight++ - return true } - return false + return -1 } -// Release frees one in-flight slot. Unknown ids are a no-op; the counter -// never goes below zero. +// Release frees one in-flight slot. A removed account may still own slots; +// unknown IDs and already-idle accounts are a no-op. func (p *Pool) Release(id string) { if p == nil || id == "" { return } p.mu.Lock() defer p.mu.Unlock() - for i := range p.items { - if p.items[i].ID != id { - continue - } - if p.items[i].InFlight > 0 { - p.items[i].InFlight-- - if p.items[i].InFlight == 0 { - p.items[i].InFlightSince = time.Time{} + if i := p.itemIndexLocked(id); i >= 0 { + item := &p.items[i] + if item.InFlight > 0 { + item.InFlight-- + if item.InFlight == 0 { + item.InFlightSince = time.Time{} } } return } + if slots, ok := p.detachedSlots[id]; ok { + if slots.count == 1 { + delete(p.detachedSlots, id) + } else { + slots.count-- + p.detachedSlots[id] = slots + } + } } func (p *Pool) SetRuntimeState(id, state string, nextRestartAt time.Time, backoffLevel int, lastError string) { @@ -1702,6 +1938,41 @@ func (p *Pool) MergeNativeModels(id string, nativeModels map[string]string) { // of those models the provider prices at zero. A nil free list means the // provider reported no pricing, which is treated as "nothing known is free" // rather than "everything is free". +// MergeModelToolSupport replaces the account's negative tool-capability list +// from a successful catalog refresh. Only models whose catalog entry explicitly +// says tools are unsupported belong here; a nil list means "no negative fact" +// and routing stays fail-open. +func (p *Pool) MergeModelToolSupport(id string, noToolsModels []string) { + if p == nil || id == "" { + return + } + copied := make([]string, 0, len(noToolsModels)) + seen := map[string]struct{}{} + for _, model := range noToolsModels { + native := strings.TrimSpace(model) + canonical := CanonicalModelID(native) + if canonical == "" || canonical == "auto" || native == "" { + continue + } + if _, ok := seen[canonical]; ok { + continue + } + seen[canonical] = struct{}{} + copied = append(copied, native) + } + if len(copied) == 0 { + copied = nil + } + p.mu.Lock() + defer p.mu.Unlock() + for i := range p.items { + if p.items[i].ID == id { + p.items[i].NoToolsModels = copied + return + } + } +} + func (p *Pool) MergeModelsWithPricing(id string, models, freeModels []string) { if p == nil || id == "" { return @@ -1734,20 +2005,25 @@ func (p *Pool) MergeModelsWithPricing(id string, models, freeModels []string) { freeSeen[canonical] = struct{}{} free = append(free, native) } + now := time.Now() p.mu.Lock() defer p.mu.Unlock() for i := range p.items { if p.items[i].ID == id { p.items[i].Models = copied p.items[i].FreeModels = free - p.items[i].ModelsAt = time.Now() + p.items[i].ModelsAt = now + for model := range seen { + clearModelRejection(&p.items[i], model, now) + } return } } } -// RemoveModel drops one public ID from a cached catalog so a stale snapshot -// cannot keep sending traffic to an account that no longer serves the model. +// RemoveModel drops one public ID from a cached catalog and temporarily marks +// that canonical account/model route unavailable. Unknown catalogs would +// otherwise fail open and immediately reselect the explicitly rejected model. func (p *Pool) RemoveModel(id, model string) { want := routeModel(model) if p == nil || id == "" || want == "" { @@ -1784,6 +2060,8 @@ func (p *Pool) RemoveModel(id, model string) { // Force the manager to refresh this account's catalog on the next // request instead of trusting the now-mutated snapshot for the TTL. p.items[i].ModelsAt = time.Time{} + p.stateCounter++ + recordModelRejection(&p.items[i], want, p.stateCounter, time.Now()) return } } @@ -1796,7 +2074,7 @@ func (p *Pool) MergeQuota(id string, quota *QuotaSnapshot) { defer p.mu.Unlock() for i := range p.items { if p.items[i].ID == id { - p.items[i].Quota = quota + p.items[i].Quota = clonePoolQuota(quota) return } } @@ -1852,40 +2130,45 @@ func itemDown(item Item, now time.Time) bool { return !item.DownUntil.IsZero() && now.Before(item.DownUntil) } -// clone returns a copy of item whose mutable reference fields no longer -// alias the live pool entry. The persistence observer hands the snapshot -// to an async drainer that reads ModelDownUntil/ModelBackoff/Models/Quota -// off the pool lock; without a deep copy those maps and slices race -// against MarkClassified/MergeModels mutations. +// clone makes a detached snapshot for readers and the persistence observer. +// In particular, cooldown maps and model slices can be changed in place +// under p.mu after the snapshot is returned. Nil catalogs mean unknown; a +// known empty catalog must stay non-nil while copying it. func (item Item) clone() Item { out := item - if item.ModelDownUntil != nil { - out.ModelDownUntil = make(map[string]time.Time, len(item.ModelDownUntil)) - for k, v := range item.ModelDownUntil { - out.ModelDownUntil[k] = v - } - } - if item.ModelBackoff != nil { - out.ModelBackoff = make(map[string]int, len(item.ModelBackoff)) - for k, v := range item.ModelBackoff { - out.ModelBackoff[k] = v - } - } - if item.ModelLastKind != nil { - out.ModelLastKind = make(map[string]string, len(item.ModelLastKind)) - for k, v := range item.ModelLastKind { - out.ModelLastKind[k] = v - } - } - if item.Models != nil { - out.Models = append([]string(nil), item.Models...) - } - if item.ProvenModels != nil { - out.ProvenModels = append([]string(nil), item.ProvenModels...) + out.Ready = clonePoolValue(item.Ready) + out.Hot = clonePoolValue(item.Hot) + out.CreditFloor = clonePoolValue(item.CreditFloor) + out.PercentFloor = clonePoolValue(item.PercentFloor) + out.Quota = clonePoolQuota(item.Quota) + out.Models = slices.Clone(item.Models) + out.NativeModels = maps.Clone(item.NativeModels) + out.FreeModels = slices.Clone(item.FreeModels) + out.ProvenModels = slices.Clone(item.ProvenModels) + out.ModelDownUntil = maps.Clone(item.ModelDownUntil) + out.ModelBackoff = maps.Clone(item.ModelBackoff) + out.ModelLastKind = maps.Clone(item.ModelLastKind) + out.modelFeedback = maps.Clone(item.modelFeedback) + out.ModelAliases = maps.Clone(item.ModelAliases) + out.EnabledModels = slices.Clone(item.EnabledModels) + return out +} + +func clonePoolValue[T any](value *T) *T { + if value == nil { + return nil } - if item.Quota != nil { - q := *item.Quota - out.Quota = &q + out := *value + return &out +} + +func clonePoolQuota(quota *QuotaSnapshot) *QuotaSnapshot { + out := clonePoolValue(quota) + if out != nil { + out.Windows = slices.Clone(quota.Windows) + out.Packages = slices.Clone(quota.Packages) + out.AddOnAvailable = clonePoolValue(quota.AddOnAvailable) + out.ResourcePackageAvailable = clonePoolValue(quota.ResourcePackageAvailable) } return out } @@ -1926,6 +2209,7 @@ func (p *Pool) Upsert(item Item) { } item.Provider = NormalizeProviderFamily(item.Provider) item.Region = NormalizeRegion(item.Region) + item = item.clone() p.mu.Lock() defer p.mu.Unlock() for i := range p.items { @@ -1955,6 +2239,9 @@ func (p *Pool) Upsert(item Item) { if len(item.ModelLastKind) == 0 && len(p.items[i].ModelLastKind) > 0 { item.ModelLastKind = p.items[i].ModelLastKind } + if len(item.modelFeedback) == 0 && len(p.items[i].modelFeedback) > 0 { + item.modelFeedback = maps.Clone(p.items[i].modelFeedback) + } if item.StateVersion == 0 { item.StateVersion = p.items[i].StateVersion } @@ -1979,10 +2266,10 @@ func (p *Pool) Upsert(item Item) { if item.Hot == nil { item.Hot = p.items[i].Hot } - // InFlight is owned by Acquire/Release on the request path. - // Runtime Upserts never carry a live counter, so always keep the - // existing value instead of wiping concurrent requests to zero. + // In-flight state belongs to the request path, not the runtime + // snapshot being upserted. item.InFlight = p.items[i].InFlight + item.InFlightSince = p.items[i].InFlightSince if item.Quota == nil { item.Quota = p.items[i].Quota } @@ -2019,6 +2306,10 @@ func (p *Pool) Upsert(item Item) { return } } + if slots, ok := p.detachedSlots[item.ID]; ok { + item.InFlight, item.InFlightSince = slots.count, slots.since + delete(p.detachedSlots, item.ID) + } p.items = append(p.items, item) } @@ -2032,10 +2323,16 @@ func (p *Pool) Remove(id string) { if p.items[i].ID != id { continue } + if item := p.items[i]; item.InFlight > 0 { + if p.detachedSlots == nil { + p.detachedSlots = make(map[string]inFlightSlots) + } + p.detachedSlots[id] = inFlightSlots{count: item.InFlight, since: item.InFlightSince} + } // The rotation cursor stores the previous pick's ID, so a removed // account is skipped naturally; only a cursor pointing at it needs // clearing. - p.items = append(p.items[:i], p.items[i+1:]...) + p.items = slices.Delete(p.items, i, i+1) p.dropRotationCursor(id) return } diff --git a/internal/executor/pool_model_feedback_test.go b/internal/executor/pool_model_feedback_test.go new file mode 100644 index 000000000..d50b827c2 --- /dev/null +++ b/internal/executor/pool_model_feedback_test.go @@ -0,0 +1,129 @@ +package executor + +import ( + "testing" + "time" +) + +func TestRemoveModelRejectsUnknownCatalogOnlyForThatAccountAndModel(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "rejected"}) + p.Upsert(Item{ID: "other"}) + + p.RemoveModel("rejected", "Model-A") + + modelA := RouteQuery{PublicModel: "model-a"} + if got, found, reserved := p.ReserveRoute(modelA); !found || !reserved || got.ID != "other" { + t.Fatalf("rejected account re-entered unknown-catalog route: got=%+v found=%v", got, found) + } else { + p.Release(got.ID) + } + + modelB := RouteQuery{PublicModel: "model-b", PreferAccount: "rejected"} + if got, found, reserved := p.ReserveRoute(modelB); !found || !reserved || got.ID != "rejected" { + t.Fatalf("rejection for model-a blocked unrelated model-b: got=%+v found=%v", got, found) + } else { + p.Release(got.ID) + } + for _, item := range p.Items() { + if item.ID == "rejected" && (ItemHasModel(item, "model-a") || ItemCouldServeModel(item, "model-a")) { + t.Fatal("rejected account still reports model-a as routable or potentially routable") + } + } +} + +func TestRemoveModelPreventsLateSuccessFromRestoringProof(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a", Models: []string{"model-a"}}) + selected := reservePoolItem(t, p, RouteQuery{PublicModel: "model-a"}, "a") + p.RemoveModel("a", "model-a") + p.markRouteOK(selected, "model-a") + p.Release(selected.ID) + + got, _ := p.ByID("a") + if itemHasProvenModel(got, "model-a") || ItemHasModel(got, "model-a") { + t.Fatalf("late success restored explicitly rejected model: %+v", got) + } +} + +func TestRemoveModelDoesNotInvalidateOtherModelSuccess(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a", ModelDownUntil: map[string]time.Time{"model-c": time.Now().Add(time.Hour)}}) + selected := reservePoolItem(t, p, RouteQuery{PublicModel: "model-b"}, "a") + p.RemoveModel("a", "model-a") + p.markRouteOK(selected, "model-b") + p.Release(selected.ID) + + got, _ := p.ByID("a") + if !itemHasProvenModel(got, "model-b") { + t.Fatalf("rejecting model-a discarded an in-flight model-b success: %+v", got) + } + if got.ModelDownUntil["model-c"].IsZero() { + t.Fatalf("rejecting model-a cleared model-c cooldown: %+v", got.ModelDownUntil) + } +} + +func TestSuccessfulCatalogRefreshRecoversRejectedModel(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a"}) + oldRequest := reservePoolItem(t, p, RouteQuery{PublicModel: "model-a"}, "a") + p.RemoveModel("a", "model-a") + firstVersion, _ := p.ByID("a") + firstRevision := modelFeedbackVersion(firstVersion, "model-a") + p.Upsert(Item{ID: "a"}) + p.RemoveModel("a", "MODEL-A") + secondVersion, _ := p.ByID("a") + secondRevision := modelFeedbackVersion(secondVersion, "model-a") + if secondRevision <= firstRevision { + t.Fatalf("repeated removal did not advance the model revision: first=%d second=%d", firstRevision, secondRevision) + } + p.Upsert(Item{ID: "a"}) + if _, found, reserved := p.ReserveRoute(RouteQuery{PublicModel: "model-a"}); found || reserved { + t.Fatal("explicitly rejected unknown-catalog model remained routable before refresh") + } + + p.MergeModels("a", []string{"model-a"}) + got, _ := p.ByID("a") + if !ItemCouldServeModel(got, "model-a") { + t.Fatal("successful catalog refresh did not restore model capability") + } + p.markRouteOK(oldRequest, "model-a") + got, _ = p.ByID("a") + if itemHasProvenModel(got, "model-a") { + t.Fatal("late success from before rejection restored proof after catalog recovery") + } + current := reservePoolItem(t, p, RouteQuery{PublicModel: "model-a"}, "a") + p.markRouteOK(current, "model-a") + p.Release(current.ID) + got, _ = p.ByID("a") + if !itemHasProvenModel(got, "model-a") { + t.Fatalf("new success after catalog recovery was not accepted: %+v", got) + } +} + +func TestRejectedModelStateExpiresAndStaysBounded(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a"}) + p.RemoveModel("a", "model-a") + p.mu.Lock() + state := p.items[0].modelFeedback["model-a"] + state.rejectedUntil = time.Now().Add(-time.Second) + p.items[0].modelFeedback["model-a"] = state + p.mu.Unlock() + if got, found, reserved := p.ReserveRoute(RouteQuery{PublicModel: "model-a"}); !found || !reserved || got.ID != "a" { + t.Fatalf("expired rejection did not become routable: got=%+v found=%v reserved=%v", got, found, reserved) + } + p.Release("a") + + for i := 0; i < maxModelFeedbackPerItem+10; i++ { + p.RemoveModel("a", "model-"+itoa(i)) + } + items := p.Items() + if len(items) != 1 || len(items[0].modelFeedback) > maxModelFeedbackPerItem { + t.Fatalf("model feedback state exceeded per-account cap: items=%d states=%d cap=%d", len(items), len(items[0].modelFeedback), maxModelFeedbackPerItem) + } + latest := "model-" + itoa(maxModelFeedbackPerItem+9) + if !modelRejected(items[0], latest, time.Now()) || ItemCouldServeModel(items[0], latest) { + t.Fatal("capacity eviction lost the most recent explicit rejection") + } +} diff --git a/internal/executor/pool_reservation_test.go b/internal/executor/pool_reservation_test.go new file mode 100644 index 000000000..6149240c2 --- /dev/null +++ b/internal/executor/pool_reservation_test.go @@ -0,0 +1,319 @@ +package executor + +import ( + "maps" + "sync" + "testing" + "time" +) + +func TestPoolReserveRouteOnlyOneConcurrentSlot(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "account", Models: []string{"model"}, MaxInFlight: 1}) + q := RouteQuery{PublicModel: "model"} + const contenders = 64 + start := make(chan struct{}) + type decision struct { + item Item + found, reserved, saturated bool + } + results := make(chan decision, contenders) + for i := 0; i < contenders; i++ { + go func() { + <-start + item, found, reserved, saturated := p.reserveRoute(q) + results <- decision{item, found, reserved, saturated} + }() + } + close(start) + winners := 0 + for i := 0; i < contenders; i++ { + result := <-results + if result.reserved { + winners++ + if !result.found || result.saturated || result.item.ID != "account" || result.item.InFlight != 1 || result.item.InFlightSince.IsZero() { + t.Errorf("bad reservation: %+v", result) + } + } else if result.found || !result.saturated || result.item.ID != "" { + t.Errorf("a losing request should see only saturation, got %+v", result) + } + } + if winners != 1 { + t.Fatalf("got %d reservations for one slot", winners) + } + p.Release("account") + idle, _ := p.ByID("account") + if idle.InFlight != 0 || !idle.InFlightSince.IsZero() { + t.Fatalf("release left a busy slot: %+v", idle) + } + reservePoolItem(t, p, q, "account") + p.Release("account") +} + +func TestPoolReserveRouteMissesDoNotCommitRotation(t *testing.T) { + p := NewPool(nil, nil) + p.SetRoutingStrategy(RoutingStrategyWeightedRoundRobin) + p.Upsert(Item{ID: "a", Weight: 80, MaxInFlight: 1}) + p.Upsert(Item{ID: "b", Weight: 40, MaxInFlight: 1}) + q := RouteQuery{PublicModel: "model"} + reservePoolItem(t, p, q, "a") + if !p.Acquire("b") { + t.Fatal("could not fill the second account") + } + key := rotationKey(q) + beforePicked, beforeRegion, beforeWeights := maps.Clone(p.lastPicked), maps.Clone(p.lastRegion), maps.Clone(p.weightCounter[key]) + if item, found, reserved := p.ReserveRoute(q); found || reserved || item.ID != "" { + t.Fatalf("saturated route = %q, found=%v reserved=%v", item.ID, found, reserved) + } + p.MarkClassified("a", Classified{Kind: KindRateLimit, Model: "model", Cooldown: 2 * time.Hour}) + p.MarkDown("b", time.Hour, "unavailable") + p.Release("a") + p.Release("b") + item, found, reserved := p.ReserveRoute(q) + if !found || reserved || item.ID != "b" || item.InFlight != 0 || p.RetryAfter(item, q.PublicModel) <= 0 { + t.Fatalf("cooling route = %+v, found=%v reserved=%v", item, found, reserved) + } + if !maps.Equal(beforePicked, p.lastPicked) || !maps.Equal(beforeRegion, p.lastRegion) || !maps.Equal(beforeWeights, p.weightCounter[key]) { + t.Fatalf("route misses changed the cursor, region latch, or weighted counters: %v %v %v", p.lastPicked, p.lastRegion, p.weightCounter[key]) + } + p.MarkOK("a", "model") + p.MarkOK("b", "") + reservePoolItem(t, p, q, "b") + p.Release("b") +} + +func TestPoolReserveRouteRotatesOnlyWithinLowestUsablePriority(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "c", Region: "global"}) + p.Upsert(Item{ID: "b", Region: "global"}) + p.Upsert(Item{ID: "a", Region: "cn"}) + q := RouteQuery{ + PublicModel: "logical", StrategyOverride: AggregationStrategyPriority, + ModelResolver: func(Item) string { return "real" }, + PriorityResolver: func(item Item) int { + if item.ID == "b" { + return 10 + } + return 2 + }, + } + reservePoolItem(t, p, q, "a") + p.Release("a") + for _, id := range []string{"a", "c"} { + p.MarkClassified(id, Classified{Kind: KindRateLimit, Model: "real", Cooldown: time.Hour}) + } + reservePoolItem(t, p, q, "b") + p.Release("b") + for _, id := range []string{"a", "c"} { + p.MarkOK(id, "real") + } + for _, id := range []string{"c", "a", "c"} { + reservePoolItem(t, p, q, id) + p.Release(id) + } + for i := 0; i < 2; i++ { + if item, found := p.PickRoute(q); !found || item.ID != "a" || item.InFlight != 0 { + t.Fatalf("legacy priority pick = %+v found=%v", item, found) + } + } +} + +func TestPoolReserveRouteModelExclusionAndRouteProbe(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ + ID: "a", Provider: "workbuddy", Region: "cn", MaxInFlight: 1, + Models: []string{"Actual-Model", "another"}, ModelAliases: map[string]string{"alias": "Actual-Model"}, + }) + q := RouteQuery{PublicModel: "alias", AllowedProviders: []string{"workbuddy:cn"}} + item := reservePoolItem(t, p, q, "a") + if !p.HasRoute(q) || p.HasCapacity(q) { + t.Fatal("saturation must not erase the route from protocol probes") + } + p.Release(item.ID) + p.MarkClassified("a", Classified{Kind: KindRateLimit, Model: "actual-model", Cooldown: time.Hour}) + if hint, found, reserved := p.ReserveRoute(q); !p.HasRoute(q) || !found || reserved || hint.ID != "a" { + t.Fatalf("alias missing its real model's cooling hint: %q, found=%v reserved=%v", hint.ID, found, reserved) + } + q.ExcludedModels = map[routeModelKey]struct{}{accountRouteModelKey(item, "alias"): {}} + if hint, found, reserved := p.ReserveRoute(q); p.HasRoute(q) || found || reserved { + t.Fatalf("excluded model still affects route selection: %q, found=%v reserved=%v", hint.ID, found, reserved) + } + display := q + display.PublicModel = "WorkBuddy: Actual Model" + if hint, found, reserved := p.ReserveRoute(display); p.HasRoute(display) || found || reserved { + t.Fatalf("display spelling bypassed the concrete exclusion: %q, found=%v reserved=%v", hint.ID, found, reserved) + } + p.MergeQuota("a", &QuotaSnapshot{Exceeded: true}) + if _, blocked := p.QuotaBlockedForModel(q); blocked { + t.Fatal("excluded model produced a quota diagnostic") + } + q.PublicModel = "another" + if !p.HasRoute(q) || p.HasCapacity(q) { + t.Fatal("quota should not hide an otherwise matching route") + } + otherKey := q + otherKey.AllowedProviders = []string{"workbuddy:global"} + if p.HasRoute(otherKey) { + t.Fatal("route probe escaped the key's allowed region") + } + p.MergeQuota("a", nil) + reservePoolItem(t, p, q, "a") + p.Release("a") +} + +func TestPoolReserveRouteHotUpsertAndReinsertPreserveSlots(t *testing.T) { + p := NewPool(nil, nil) + a := Item{ID: "a", MaxInFlight: 1, URL: "old"} + p.Upsert(a) + q := RouteQuery{PublicModel: "model"} + first := reservePoolItem(t, p, q, "a") + a.URL = "new" + p.Upsert(a) + current, _ := p.ByID("a") + if current.InFlight != 1 || !current.InFlightSince.Equal(first.InFlightSince) || current.URL != "new" { + t.Fatalf("hot upsert lost either the slot or the new endpoint: %+v", current) + } + p.Remove("a") + if _, found := p.First(); found { + t.Fatal("removed account is still visible") + } + p.Upsert(a) + if _, found, reserved := p.ReserveRoute(q); found || reserved { + t.Fatal("reinserted account ignored an outstanding reservation") + } + p.Release(first.ID) + next := reservePoolItem(t, p, q, "a") + if next.URL != "new" || next.InFlight != 1 { + t.Fatalf("wrong reservation after old release: %+v", next) + } + p.Remove("a") + p.Release(next.ID) + p.Upsert(a) + reservePoolItem(t, p, q, "a") + p.Release("a") +} + +func TestPoolHotUpdatesAndDetachedReadSnapshots(t *testing.T) { + p := NewPool(nil, nil) + initial := Item{ + ID: "a", MaxInFlight: 1, Models: make([]string, 0), ProvenModels: []string{"model"}, + NativeModels: map[string]string{"model": "native"}, ModelDownUntil: map[string]time.Time{"model": {}}, + } + p.Upsert(initial) + before, _ := p.ByID("a") + if before.Models == nil { + t.Fatal("known empty catalog turned into an unknown catalog after cloning") + } + p.RemoveModel("a", "model") + p.MarkClassified("a", Classified{Kind: KindRateLimit, Model: "model", Cooldown: time.Hour}) + if len(before.ProvenModels) != 1 || before.ProvenModels[0] != "model" || before.NativeModels["model"] != "native" || !before.ModelDownUntil["model"].IsZero() { + t.Fatalf("snapshot changed after mutating live routing state: %+v", before) + } + if got := initial.NativeModels["model"]; got != "native" { + t.Fatalf("pool mutated the caller's input: native model = %q", got) + } + q := RouteQuery{PublicModel: "model"} + const rounds = 200 + var wg sync.WaitGroup + start := make(chan struct{}) + wg.Go(func() { + <-start + for i := 0; i < rounds; i++ { + p.Remove("a") + p.Upsert(initial) + p.RemoveModel("a", "model") + p.MarkClassified("a", Classified{Kind: KindRateLimit, Model: "model", Cooldown: time.Hour}) + p.MarkOK("a", "model") + } + }) + wg.Go(func() { + <-start + for i := 0; i < rounds; i++ { + item, _ := p.First() + _ = item.ModelDownUntil["model"] + item, _ = p.PickRoute(q) + _ = NativeModelID(item, "model") + for _, item := range p.Items() { + _ = ItemHasModel(item, "model") + } + item, _, reserved := p.ReserveRoute(q) + if reserved { + if item.ID != "a" || item.InFlight != 1 { + t.Errorf("bad reservation during hot update: %+v", item) + } + p.Release(item.ID) + } + } + }) + close(start) + wg.Wait() + reservePoolItem(t, p, q, "a") + p.Release("a") +} + +func TestPoolRouteSuccessDoesNotEraseNewerFailure(t *testing.T) { + for _, tc := range []struct { + name string + failure Classified + }{ + {"model", Classified{Kind: KindRateLimit, Model: "model", Cooldown: time.Hour, Message: "new rate limit"}}, + {"account", Classified{Kind: KindAuth, Cooldown: time.Hour, Message: "new auth cooldown"}}, + {"account without cooldown", Classified{Kind: KindAuth, Message: "new auth failure"}}, + } { + t.Run(tc.name, func(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a", MaxInFlight: 2}) + q := RouteQuery{PublicModel: "model"} + first := reservePoolItem(t, p, q, "a") + second := reservePoolItem(t, p, q, "a") + failed := make(chan struct{}) + done := make(chan struct{}) + go func() { + <-failed + p.markRouteOK(first, "model") + p.Release(first.ID) + close(done) + }() + p.MarkClassified(second.ID, tc.failure) + p.Release(second.ID) + want, _ := p.ByID("a") + close(failed) + <-done + got, _ := p.ByID("a") + if got.StateVersion != want.StateVersion || got.LastError != tc.failure.Message || got.LastKind != want.LastKind || + got.ModelLastKind["model"] != want.ModelLastKind["model"] || !got.DownUntil.Equal(want.DownUntil) || + !got.ModelDownUntil["model"].Equal(want.ModelDownUntil["model"]) { + t.Fatalf("late success overwrote the newer failure: got %+v, want %+v", got, want) + } + }) + } +} + +func TestPoolRouteSuccessRequiresConcreteModel(t *testing.T) { + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a"}) + p.MarkClassified("a", Classified{Kind: KindRateLimit, Model: "other", Cooldown: time.Hour}) + item := reservePoolItem(t, p, RouteQuery{PublicModel: "auto"}, "a") + for _, model := range []string{"", "auto", " AUTO "} { + p.markRouteOK(item, model) + } + got, _ := p.ByID("a") + if got.StateVersion != item.StateVersion || got.ModelDownUntil["other"].IsZero() || len(got.ProvenModels) != 0 { + t.Fatalf("auto success modified account or model state: %+v", got) + } + p.markRouteOK(item, "model") + got, _ = p.ByID("a") + if !itemHasProvenModel(got, "model") || got.ModelDownUntil["other"].IsZero() { + t.Fatalf("concrete success not recorded independently: %+v", got) + } + p.Release("a") +} + +func reservePoolItem(t *testing.T, p *Pool, q RouteQuery, id string) Item { + t.Helper() + item, found, reserved := p.ReserveRoute(q) + if !found || !reserved || item.ID != id { + t.Fatalf("reservation = %q, found=%v reserved=%v; want %q", item.ID, found, reserved, id) + } + return item +} diff --git a/internal/executor/pool_route_test.go b/internal/executor/pool_route_test.go index f17a215d6..c14eab5f4 100644 --- a/internal/executor/pool_route_test.go +++ b/internal/executor/pool_route_test.go @@ -222,7 +222,6 @@ func TestAggregateMemberHonorsAccountAliasAfterPick(t *testing.T) { accounts.AggregationMember{Provider: "qoder", Model: "model-b", Priority: 0}, accounts.AggregationMember{Provider: "workbuddy", Model: "model-b", Priority: 1}, ) - loop := routeLoop{resolver: plan.resolver()} q1 := Item{ ID: "q1", Provider: "qoder", Models: []string{"model-a"}, ModelAliases: map[string]string{"model-b": "model-a"}, @@ -246,7 +245,8 @@ func TestAggregateMemberHonorsAccountAliasAfterPick(t *testing.T) { {w1, "model-b"}, } { req := translate.ChatRequest{Model: "logical-model-b"} - got := sanitizeForItem(tc.item, loop.dispatchRequest(tc.item, req)) + member, _ := plan.matchMember(tc.item) + got := targetFor(tc.item, member.Model).request(req) if got.Model != tc.want { t.Fatalf("%s aggregate model = %q want %q", tc.item.ID, got.Model, tc.want) } diff --git a/internal/executor/prepare.go b/internal/executor/prepare.go index 4c2603b48..b09065da0 100644 --- a/internal/executor/prepare.go +++ b/internal/executor/prepare.go @@ -5,7 +5,9 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "log" + "net/http" "os" "strconv" "strings" @@ -14,6 +16,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/auth" "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -40,13 +43,21 @@ type CatalogPreparer interface { // AggregationResolver resolves a logical model ID to a read-only snapshot of // its provider/model members. Implemented by control.Aggregations and injected -// by the gateway. The executor never imports control directly. +// by the gateway. ErrAggregationNotFound means no enabled logical model by +// that ID exists. A known model with no permitted members still resolves, so +// the caller cannot accidentally route to an ordinary model of the same name. type AggregationResolver interface { Resolve(ctx context.Context, id string, allowedProviders map[string]bool) (accounts.Aggregation, error) } -// AggregationCatalog is implemented by the control facade. Prepare uses it to -// compile nested aggregations from the same snapshot Resolve just read. +// aggregationWithCatalog keeps the root and any referenced groups on one +// configuration version, including while the control plane applies an edit. +type aggregationWithCatalog interface { + ResolveWithCatalog(context.Context, string, map[string]bool) (accounts.Aggregation, map[string]accounts.Aggregation, error) +} + +// AggregationCatalog is the compatibility interface for resolvers that do not +// expose a single snapshot. Production preparation uses aggregationWithCatalog. type AggregationCatalog interface { Catalog(ctx context.Context) (map[string]accounts.Aggregation, error) } @@ -85,6 +96,58 @@ type PrepareInput struct { Catalogs CatalogPreparer Aggregations AggregationResolver Logs RequestStarter + // BeforeSideEffects admits the request after pure validation and before + // aggregation resolution (which can dispatch a classifier), catalog reads + // or request logging. A non-nil error stops preparation unchanged. + BeforeSideEffects func() error +} + +// RouteInput is the complete routing snapshot for a prepared request. Empty +// fields are authoritative too: they do not fall back to context values. +type RouteInput struct { + RequestID string + PublicModel string // Original client-facing name. + RouteModel string // Model without its gateway provider/region prefix. + ProviderFilter string + RegionFilter string + Prefer string + SessionKey string + AllowedProviders []string + AggregatePlan *AggregatePlan + // Tooling is the canonical tool declaration for this attempt. A zero + // request means the client declared no executable tools. + Tooling toolcall.Request + // RequireModelAlias prevents an alias-only key from taking another + // account’s identically named catalog model. + RequireModelAlias bool +} + +// routeInputFromContext adapts legacy executor entry points exactly once, +// including their content-derived session key when no key was supplied. +func routeInputFromContext(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) RouteInput { + publicModel := req.Model + sessionKey := resolveSessionKey(ctx, req) + regionFilter := regionFilterFromContext(ctx) + // Keep the old entry point's precedence: an explicit model prefix + // replaces the corresponding filter; omitted options stay in force. + if provider, region := ResolveProviderFilter(&req, true); provider != "" { + providerFilter = provider + if region != "" { + regionFilter = region + } + } + return RouteInput{ + RequestID: RequestIDFromContext(ctx), + PublicModel: publicModel, + RouteModel: req.Model, + ProviderFilter: strings.ToLower(strings.TrimSpace(providerFilter)), + RegionFilter: regionFilter, + Prefer: strings.TrimSpace(prefer), + SessionKey: sessionKey, + AllowedProviders: append([]string(nil), allowedProvidersFrom(ctx)...), + AggregatePlan: aggregatePlanFrom(ctx), + Tooling: toolingFromRequest(req), + } } type PreparedRequest struct { @@ -96,6 +159,7 @@ type PreparedRequest struct { PublicModel string ProviderFilter string Prefer string + Route RouteInput } func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { @@ -109,32 +173,10 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { request.Model = publicModel request.Stream = in.NativeRequest.Stream() } - // Resolve a logical aggregation model into an immutable per-request plan. - // This happens once, before any Pool lock, and the plan is carried in the - // context so routing uses a stable snapshot (no DB/facade access under lock, - // no cross-request mutable state). An aggregation key accepts both its - // provider-neutral account aliases and the logical models configured in the - // model pool, so the plan must exist before the key contract is checked. - var aggregatePlan *AggregatePlan - if in.Aggregations != nil && (in.CrossProviderPool || in.ModelAggregation) && ProviderPrefix(publicModel) == "" { - if plan, ok := e.resolveAggregation(in.Context, in.Aggregations, publicModel, in.Identity.AllowedProviders, request); ok { - aggregatePlan = plan - } + if in.ModelAggregation && ProviderPrefix(publicModel) != "" { + return PreparedRequest{}, aggregationModelRequired() } - if in.ModelAggregation { - // An aggregation key's contract is stricter than the shared pool: it may - // only call the provider-neutral names it exposes — an account alias or a - // configured logical model. A real catalog id or a provider-prefixed id - // would leak the split view back. - if strings.Contains(strings.TrimSpace(publicModel), "/") || - (aggregatePlan == nil && !e.servesAggregationAlias(publicModel, in.Identity)) { - return PreparedRequest{}, &PrepareError{ - Status: 400, - Code: "model_not_aggregated", - Message: "this API key only accepts its aggregated model names; call /v1/models for the list", - } - } - } else if RejectsBareModel(publicModel, in.CrossProviderPool) { + if !in.ModelAggregation && RejectsBareModel(publicModel, in.CrossProviderPool) { return PreparedRequest{}, &PrepareError{ Status: 400, Code: "provider_prefix_required", @@ -143,14 +185,37 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { } providerFilter, modelRegion := ResolveProviderFilter(&request, in.CrossProviderPool || in.ModelAggregation) + if !in.Identity.AllowsProvider(providerFilter) { + return PreparedRequest{}, providerNotAllowed(providerFilter) + } + if in.BeforeSideEffects != nil { + if err := in.BeforeSideEffects(); err != nil { + return PreparedRequest{}, err + } + } + + // Resolve a logical model exactly once, before selection. An aggregation + // key accepts only account aliases or logical model names. Verifying these + // names needs the admitted request to read the catalog and possibly run + // a classifier, so it comes after the pure model and grant checks above. + var aggregatePlan *AggregatePlan + if in.Aggregations != nil && (in.CrossProviderPool || in.ModelAggregation) && providerFilter == "" { + var err error + aggregatePlan, err = e.resolveAggregation(in.Context, in.Aggregations, publicModel, in.Identity.AllowedProviders, request) + if err != nil { + return PreparedRequest{}, err + } + } + requireModelAlias := in.ModelAggregation && aggregatePlan == nil + if requireModelAlias && (strings.Contains(publicModel, "/") || !e.servesAggregationAlias(publicModel, in.Identity)) { + return PreparedRequest{}, aggregationModelRequired() + } prefer := strings.TrimSpace(in.PreferAccount) - providerFilter = ApplyPinnedProviderFilter(e.Pool, providerFilter, publicModel, prefer) - if providerFilter != "" && !in.Identity.AllowsProvider(providerFilter) { - return PreparedRequest{}, &PrepareError{ - Status: 403, - Code: "provider_not_allowed", - Message: "This API key cannot use provider " + providerFilter, + if pinnedProvider := ApplyPinnedProviderFilter(e.Pool, providerFilter, publicModel, prefer); pinnedProvider != providerFilter { + if !in.Identity.AllowsProvider(pinnedProvider) { + return PreparedRequest{}, providerNotAllowed(pinnedProvider) } + providerFilter = pinnedProvider } if in.NativeRequest == nil { if err := ApplyModelContextDefaults(in.Context, in.ModelContexts, &request, providerFilter); err != nil { @@ -210,11 +275,19 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { // layer; membership is already constrained by the resolved plan. effectiveAllow = nil } - ctx := WithAllowedProviders(WithRequestID(in.Context, requestID), effectiveAllow) sessionKey := sessionKeyFor(in.SessionHeader, in.ConversationID, in.Identity, request) if sessionKey == "" && in.NativeRequest != nil { sessionKey = NativeSessionKeyFor(in.NativeRequest, in.Identity) } + tooling, toolingErr := canonicalTooling(request, in.NativeRequest) + if toolingErr != nil { + return PreparedRequest{}, toolingErr + } + if tooling.HasTools() && prefer != "" && e.Pool != nil { + if pinned, found := e.Pool.ByID(prefer); found && !e.itemSupportsTooling(pinned, request.Model, tooling) { + return PreparedRequest{}, toolCapabilityError(itemProvider(pinned), request.Model, tooling) + } + } // Sharding is a fallback for requests that have no conversation id and // no content seed (a one-shot with no user anchor). It must not replace // ContentSessionSeed: that fingerprint already pins one chat to one @@ -225,19 +298,9 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { sessionKey = shard } } - if sessionKey != "" { - ctx = WithSessionKey(ctx, sessionKey) - ctx = WithConversation(ctx, sessionKey) - } - if modelRegion != "" { - ctx = WithRegionFilter(ctx, modelRegion) - } if requestedReasoning != "" { log.Printf("request reasoning request_id=%q model=%q level=%q", requestID, request.Model, requestedReasoning) } - if aggregatePlan != nil { - ctx = WithAggregatePlan(ctx, aggregatePlan) - } if sessionKey != "" && sessionAffinityDebugOn() { source := "content-seed" if strings.TrimSpace(in.SessionHeader) != "" { @@ -250,6 +313,22 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { log.Printf("session affinity request_id=%q source=%q key=%q model=%q tools=%t msgs=%d", requestID, source, shortSessionKey(sessionKey), request.Model, len(request.Tools) > 0, len(request.Messages)) } + route := RouteInput{ + RequestID: requestID, + PublicModel: publicModel, + RouteModel: request.Model, + ProviderFilter: providerFilter, + RegionFilter: modelRegion, + Prefer: prefer, + SessionKey: sessionKey, + AllowedProviders: append([]string(nil), effectiveAllow...), + AggregatePlan: aggregatePlan, + RequireModelAlias: requireModelAlias, + Tooling: tooling, + } + // Request ID and the provider-facing conversation are transport metadata, + // not a second source of routing constraints. + ctx := dispatchContext(in.Context, route) return PreparedRequest{ Context: ctx, RequestID: requestID, @@ -259,21 +338,37 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { PublicModel: publicModel, ProviderFilter: providerFilter, Prefer: prefer, + Route: route, }, nil } +func aggregationModelRequired() *PrepareError { + return &PrepareError{ + Status: 400, + Code: "model_not_aggregated", + Message: "this API key only accepts its aggregated model names; call /v1/models for the list", + } +} + +func providerNotAllowed(provider string) *PrepareError { + return &PrepareError{ + Status: 403, + Code: "provider_not_allowed", + Message: "This API key cannot use provider " + provider, + } +} + // resolveAggregation attempts to resolve a bare public model ID as a logical -// aggregation model. It returns false for ordinary models so the normal route -// path is unchanged. Provider grants are reduced to a family set used to -// filter members; an empty allowlist means "all providers allowed" (nil map). -func (e ChatExecutor) resolveAggregation(ctx context.Context, resolver AggregationResolver, model string, grants []string, request translate.ChatRequest) (*AggregatePlan, bool) { +// aggregation model. Only a definite absence permits the ordinary route path. +// Provider grants are reduced to a family set used to filter members; an +// empty allowlist means "all providers allowed" (nil map). +func (e ChatExecutor) resolveAggregation(ctx context.Context, resolver AggregationResolver, model string, grants []string, request translate.ChatRequest) (*AggregatePlan, error) { allowed := map[string]bool(nil) + aggregationOnly := accounts.IsAggregationOnly(grants) // An aggregation-only key must not filter members by its own sentinel // grant (that would drop every real provider). nil means "no member // filtering"; the pool-level allowlist is cleared for these requests too. - if accounts.IsAggregationOnly(grants) { - allowed = nil - } else if len(grants) > 0 { + if !aggregationOnly && len(grants) > 0 { allowed = make(map[string]bool, len(grants)) for _, entry := range grants { // ParseProviderGrant already lowercases and trims; do not pre-fold @@ -285,83 +380,133 @@ func (e ChatExecutor) resolveAggregation(ctx context.Context, resolver Aggregati allowed[grant.Provider] = true } } - agg, err := resolver.Resolve(ctx, model, allowed) - if err != nil || (strings.TrimSpace(agg.Document) == "" && len(agg.Members) == 0) { - return nil, false + var ( + agg accounts.Aggregation + catalog map[string]accounts.Aggregation + err error + ) + snapshot, hasSnapshot := resolver.(aggregationWithCatalog) + if hasSnapshot { + agg, catalog, err = snapshot.ResolveWithCatalog(ctx, model, allowed) + } else { + agg, err = resolver.Resolve(ctx, model, allowed) } - if strings.TrimSpace(agg.Document) != "" { - var catalog map[string]accounts.Aggregation - if source, ok := resolver.(AggregationCatalog); ok { - catalog, _ = source.Catalog(ctx) - } - text := latestUserText(request) - labels := map[string]string{} - if len(text) > 0 { - targets, err := accounts.ClassifierTargets(agg.ID, agg.Document, catalog) - if err == nil { - classifyCtx := ctx - // Classifiers run before the request-level allowed-provider - // context is installed. Give them the same non-aggregation - // grants so a provider-scoped key cannot send the user's text - // to an out-of-scope provider named in the pipeline. - if !accounts.IsAggregationOnly(grants) && len(grants) > 0 { - classifyCtx = WithAllowedProviders(ctx, grants) - } - labels = e.ClassifyIntent(classifyCtx, targets, text) + if errors.Is(err, accounts.ErrAggregationNotFound) { + return nil, nil + } + if err != nil { + return nil, aggregationUnavailable() + } + if strings.TrimSpace(agg.Document) == "" { + if len(agg.Members) == 0 { + return nil, &PrepareError{ + Status: http.StatusBadRequest, + Code: "model_not_available", + Message: "The requested model has no available aggregation members", } } - compiled, seats, _, err := accounts.CompilePipeline(agg, catalog, text, labels, allowed) - if err != nil || len(compiled.Members) == 0 { - return nil, false + return NewAggregatePlan(agg), nil + } + + if !hasSnapshot { + if source, ok := resolver.(AggregationCatalog); ok { + catalog, err = source.Catalog(ctx) + if err != nil { + return nil, aggregationUnavailable() + } } - plan := NewAggregatePlan(compiled) - plan.Seats = seats - return plan, true } - return NewAggregatePlan(agg), true + text := latestUserText(request) + // A classifier routes to its own concrete target, never the virtual + // model's plan or session. Carry the full region-scoped grants, and let + // the compiler request a label only when it reaches that branch. + classifierRoute := RouteInput{} + if !aggregationOnly { + classifierRoute.AllowedProviders = grants + } + classifier := e.intentClassifier(ctx, text, classifierRoute) + compiled, seats, _, err := accounts.CompilePipelineWithClassifier(agg, catalog, text, allowed, classifier) + if err != nil || len(compiled.Members) == 0 { + return nil, aggregationUnavailable() + } + plan := NewAggregatePlan(compiled) + plan.Seats = seats + return plan, nil +} + +func aggregationUnavailable() *PrepareError { + return &PrepareError{ + Status: http.StatusServiceUnavailable, + Code: "aggregation_unavailable", + Message: "The requested model could not be resolved through the aggregation catalog", + } } type intentCallKey struct{} func (e ChatExecutor) ClassifyIntent(ctx context.Context, targets []accounts.ClassifierTarget, text string) map[string]string { - if e.Pool == nil || len(targets) == 0 || strings.TrimSpace(text) == "" || ctx.Value(intentCallKey{}) != nil { + // Keep the direct entry point's explicit legacy constraints, not any + // aggregate plan or affinity key of the caller. + classify := e.intentClassifier(ctx, text, RouteInput{ + RequestID: RequestIDFromContext(ctx), + RegionFilter: regionFilterFromContext(ctx), + AllowedProviders: append([]string(nil), allowedProvidersFrom(ctx)...), + }) + if len(targets) == 0 || classify == nil { return nil } labels := make(map[string]string, len(targets)) for _, target := range targets { - label, err := e.oneIntent(ctx, target, text) - if err != nil || strings.TrimSpace(label) == "" { - continue + if label := classify(target); label != "" { + labels[target.Key()] = label } - labels[target.Key()] = label } return labels } -func (e ChatExecutor) oneIntent(ctx context.Context, target accounts.ClassifierTarget, text string) (string, error) { - ctx, cancel := context.WithTimeout(context.WithValue(ctx, intentCallKey{}, true), 8*time.Second) - defer cancel() +func (e ChatExecutor) intentClassifier(ctx context.Context, text string, route RouteInput) func(accounts.ClassifierTarget) string { + if ctx == nil { + ctx = context.Background() + } + if e.Pool == nil || strings.TrimSpace(text) == "" || ctx.Value(intentCallKey{}) != nil { + return nil + } + return func(target accounts.ClassifierTarget) string { + label, err := e.oneIntent(ctx, target, text, route) + if err != nil { + return "" + } + return strings.TrimSpace(label) + } +} + +func (e ChatExecutor) oneIntent(ctx context.Context, target accounts.ClassifierTarget, text string, route RouteInput) (string, error) { rawProvider := strings.ToLower(strings.TrimSpace(target.Provider)) provider := "" if rawProvider != "" { provider = accounts.NormalizeProviderFamily(rawProvider) } - // ChatNonStream expects a bare model plus an explicit provider filter. - // A prefixed classifier model makes every account look unable to serve it. - // A blank region means any region of that provider. Only an explicit - // region pins the pool; NormalizeRegion would turn a blank into global. + // Dispatch the bare model with the classifier target's provider and any + // explicit target region. A blank target region adds no hard pin. model := accounts.BareAggregationModel(rawProvider, target.Region, target.Model) + route.PublicModel, route.RouteModel = target.Model, model + route.ProviderFilter = provider if region, pin := classifierRegionPin(target.Region); pin { - ctx = WithRegionFilter(ctx, region) + if inherited := strings.TrimSpace(route.RegionFilter); inherited != "" && accounts.NormalizeRegion(inherited) != region { + return "", nil // Neither hard region can override the other. + } + route.RegionFilter = region } - result, err := e.ChatNonStream(ctx, translate.ChatRequest{ + ctx, cancel := context.WithTimeout(WithAttemptKind(context.WithValue(ctx, intentCallKey{}, true), AttemptKindClassifier), 8*time.Second) + defer cancel() + result, err := e.ChatNonStreamPrepared(ctx, translate.ChatRequest{ Model: model, Messages: []translate.ChatMessage{ {Role: "system", Content: "Reply with only the path label."}, {Role: "user", Content: text}, }, MaxTokens: json.RawMessage("32"), - }, "", provider) + }, route) if err != nil { return "", err } @@ -395,46 +540,9 @@ func latestUserText(req translate.ChatRequest) string { return "" } -// providerPrefixes are the provider segments a client may pin with a leading -// "/" model id. Command Code's own model ids are org-namespaced -// ("deepseek/…", "moonshotai/…"), so its provider prefix sits in front of an -// already-namespaced id ("command/deepseek/…"). -var providerPrefixes = []string{"qoder/", "workbuddy/", "trae/", "devin/", "command/", "codex/", "zhipu/", "qwenwork/", "kimi/", "codearts/", "kiro/", "meta/", "muse/", "doubaowork/", "minimaxcode/", "opencode/"} - -// regionDashSuffixes are the region qualifiers that may be appended to a -// provider prefix with a dash: "workbuddy-cn/", "workbuddy-gl/", -// "workbuddy-auto/". "-auto/" is the opt-out: it pins the provider family -// while letting the pool pick the region (the lastRegion latch in pool.go). -var regionDashSuffixes = []string{"-cn/", "-gl/", "-auto/"} - -// regionAliases maps shorthand region tags to canonical region IDs. -// "auto" maps to "" (no region pin), which triggers the pool's automatic -// region selection instead of a fixed region. -var regionAliases = map[string]string{ - "cn": "cn", - "gl": "global", - "auto": "", -} - -// regionTag extracts the bare region tag from a dash suffix like "-cn/". -func regionTag(suffix string) string { - return strings.TrimSuffix(strings.TrimPrefix(suffix, "-"), "/") -} - func ProviderPrefix(model string) string { - model = strings.TrimSpace(model) - for _, prefix := range providerPrefixes { - if strings.HasPrefix(model, prefix) { - return strings.TrimSuffix(prefix, "/") - } - base := strings.TrimSuffix(prefix, "/") - for _, rs := range regionDashSuffixes { - if strings.HasPrefix(model, base+rs) { - return base - } - } - } - return "" + provider, _, _ := accounts.SplitProviderModelPrefix(model) + return provider } func RejectsBareModel(model string, crossProviderPool bool) bool { @@ -456,7 +564,7 @@ func (e ChatExecutor) servesAggregationAlias(model string, identity auth.Identit if !identity.AllowsProvider(item.Provider) || !identity.AllowsProviderRegion(item.Provider, item.Region) { continue } - if strings.TrimSpace(item.ModelAliases[want]) == "" { + if !definesModelAlias(item, want) { continue } if itemHasModel(item, want) { @@ -466,6 +574,10 @@ func (e ChatExecutor) servesAggregationAlias(model string, identity auth.Identit return false } +func definesModelAlias(item Item, model string) bool { + return strings.TrimSpace(item.ModelAliases[routeModel(model)]) != "" +} + // ResolveProviderFilter parses the provider prefix (and an optional region // qualifier) from the model id, strips both from req.Model, and returns the // provider family and the canonical region ("" when no region was specified). @@ -479,26 +591,12 @@ func (e ChatExecutor) servesAggregationAlias(model string, identity auth.Identit // The region coexists with API-key grants: routeBaseMatches enforces both // independently, so a prefix that conflicts with a grant yields no candidates. func ResolveProviderFilter(req *translate.ChatRequest, crossProviderPool bool) (provider, region string) { - model := strings.TrimSpace(req.Model) - if model == "" { - return "", "" - } - for _, prefix := range providerPrefixes { - base := strings.TrimSuffix(prefix, "/") - // Region-qualified dash form: "workbuddy-cn/model" - for _, rs := range regionDashSuffixes { - if strings.HasPrefix(model, base+rs) { - req.Model = strings.TrimPrefix(model, base+rs) - return accounts.NormalizeProviderFamily(base), regionAliases[regionTag(rs)] - } - } - // Standard form: "workbuddy/model" - if strings.HasPrefix(model, prefix) { - req.Model = strings.TrimPrefix(model, prefix) - return accounts.NormalizeProviderFamily(base), "" - } + provider, region, bare := accounts.SplitProviderModelPrefix(req.Model) + if provider != "" { + req.Model = bare + return provider, region } - if crossProviderPool { + if crossProviderPool || bare == "" { return "", "" } return "qoder", "" diff --git a/internal/executor/prepare_test.go b/internal/executor/prepare_test.go index f50d379d8..470593240 100644 --- a/internal/executor/prepare_test.go +++ b/internal/executor/prepare_test.go @@ -3,6 +3,9 @@ package executor import ( "context" "encoding/json" + "errors" + "net/http" + "reflect" "testing" "time" @@ -69,6 +72,9 @@ func TestPrepareStripsPrefixAndChecksGrants(t *testing.T) { if got.ProviderFilter != "workbuddy" || got.Prefer != "account-a" || got.Request.Model != "glm-5.2" || got.PublicModel != "workbuddy/glm-5.2" { t.Fatalf("%+v", got) } + if got.Route.RouteModel != "glm-5.2" || got.Route.PublicModel != "workbuddy/glm-5.2" { + t.Fatalf("prepare split the names incorrectly: %+v", got.Route) + } if got.RequestID != "req_fixed" { t.Fatalf("request id=%s", got.RequestID) } @@ -139,7 +145,7 @@ func TestPrepareAggregationKeyAcceptsLogicalModel(t *testing.T) { if err != nil { t.Fatalf("logical model on aggregation key: %v", err) } - plan := aggregatePlanFrom(got.Context) + plan := got.Route.AggregatePlan if plan == nil || plan.ID != "glm-5.2" || len(plan.Members) != 1 { t.Fatalf("plan=%+v", plan) } @@ -158,12 +164,18 @@ func TestPrepareAggregationKeyAcceptsLogicalModel(t *testing.T) { } type stubAggregationResolver struct { - agg accounts.Aggregation + agg accounts.Aggregation + onResolve func() + catalog map[string]accounts.Aggregation + catalogErr error } func (s stubAggregationResolver) Resolve(_ context.Context, id string, allowed map[string]bool) (accounts.Aggregation, error) { + if s.onResolve != nil { + s.onResolve() + } if id != s.agg.ID { - return accounts.Aggregation{}, context.Canceled + return accounts.Aggregation{}, accounts.ErrAggregationNotFound } out := s.agg out.Members = nil @@ -175,6 +187,10 @@ func (s stubAggregationResolver) Resolve(_ context.Context, id string, allowed m return out, nil } +func (s stubAggregationResolver) Catalog(context.Context) (map[string]accounts.Aggregation, error) { + return s.catalog, s.catalogErr +} + func TestPrepareDeniesUngrantedProvider(t *testing.T) { ex := NewChatExecutor(NewPool(nil, nil), "") _, err := ex.Prepare(PrepareInput{ @@ -189,6 +205,261 @@ func TestPrepareDeniesUngrantedProvider(t *testing.T) { } } +func TestPrepareChecksPureErrorsBeforeAdmission(t *testing.T) { + for _, tc := range []struct { + name string + input PrepareInput + code string + }{ + { + name: "missing provider prefix", + input: PrepareInput{Request: translate.ChatRequest{Model: "glm-5.2"}}, + code: "provider_prefix_required", + }, + { + name: "explicit provider out of grant", + input: PrepareInput{ + Request: translate.ChatRequest{Model: "qoder-cn/glm-5.2"}, + Identity: auth.Identity{AllowedProviders: []string{"workbuddy"}}, + }, + code: "provider_not_allowed", + }, + { + name: "aggregation key with a reserved provider prefix", + input: PrepareInput{ + Request: translate.ChatRequest{Model: "qoder-cn/model"}, + ModelAggregation: true, + }, + code: "model_not_aggregated", + }, + } { + t.Run(tc.name, func(t *testing.T) { + tc.input.BeforeSideEffects = func() error { + t.Fatal("pure rejection must not acquire a key slot") + return nil + } + tc.input.Aggregations = stubAggregationResolver{onResolve: func() { + t.Fatal("pure rejection must not access the aggregation resolver") + }} + _, err := (ChatExecutor{}).Prepare(tc.input) + var prepared *PrepareError + if !asPrepareError(err, &prepared) || prepared.Code != tc.code { + t.Fatalf("err=%v, want %s", err, tc.code) + } + }) + } +} + +func TestPrepareStopsBeforeSideEffectsWhenAdmissionFails(t *testing.T) { + rejected := &PrepareError{Status: 429, Code: "at_capacity"} + catalogs := &stubCatalogs{} + contexts := &stubContexts{} + logs := &stubLogs{} + calls := 0 + _, err := (ChatExecutor{}).Prepare(PrepareInput{ + Request: translate.ChatRequest{Model: "logical"}, + CrossProviderPool: true, + Aggregations: stubAggregationResolver{onResolve: func() { + t.Fatal("denied request reached the resolver") + }}, + Catalogs: catalogs, + ModelContexts: contexts, + Logs: logs, + NewRequestID: func() string { + t.Fatal("denied request generated a log ID") + return "" + }, + BeforeSideEffects: func() error { calls++; return rejected }, + }) + if err != rejected || calls != 1 { + t.Fatalf("err=%v calls=%d, want unchanged admission error and one call", err, calls) + } + if contexts.got != "" || catalogs.calls != 0 || len(logs.entries) != 0 { + t.Fatalf("denied request ran side effects: model=%q catalog=%d logs=%d", contexts.got, catalogs.calls, len(logs.entries)) + } +} + +func TestPrepareClassifierUsesOwnRouteAfterAdmission(t *testing.T) { + for _, tc := range []struct { + name string + region string + wantCalls int + wantMember string + }{ + {name: "classify with granted account", wantCalls: 1, wantMember: "planner"}, + {name: "different explicitly requested region is forbidden", region: "global", wantMember: "fallback"}, + } { + t.Run(tc.name, func(t *testing.T) { + pool := NewPool(nil, nil) + for _, region := range []string{"global", "cn"} { + pool.Upsert(Item{ID: region, Provider: "qoder", Region: region, Runtime: "in_process", Models: []string{"glm-5.2", "wrong"}}) + } + ex := NewChatExecutor(pool, "") + fake := &recordingIntentChat{} + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "qoder", Chat: fake}) + ex.SessionAffinity.Bind("stale-session", "global") + ctx := WithSessionKey(context.Background(), "stale-session") + ctx = WithConversation(ctx, "stale-conversation") + ctx = WithRequestID(ctx, "stale-request") + ctx = WithRegionFilter(ctx, "global") + ctx = WithAllowedProviders(ctx, []string{"workbuddy"}) + ctx = WithAggregatePlan(ctx, NewAggregatePlan(accounts.Aggregation{ + ID: "stale-plan", Members: []accounts.AggregationMember{{Provider: "qoder", Model: "wrong"}}, + })) + admitted := 0 + agg := accounts.Aggregation{ID: "logical", Document: `{"version":1,"steps":[ + {"id":"branch","kind":"branch","classifier":{"provider":"qoder","region":"` + tc.region + `","model":"glm-5.2"},"paths":[ + {"id":"plan","label":"Plan","intent":"ok","steps":[{"id":"p","kind":"member","provider":"qoder","model":"planner"}]}, + {"id":"default","label":"Default","fallback":true,"steps":[{"id":"f","kind":"member","provider":"qoder","model":"fallback"}]} + ]}]}`, + } + got, err := ex.Prepare(PrepareInput{ + Context: ctx, + Request: translate.ChatRequest{ + Model: "logical", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, + Identity: auth.Identity{AllowedProviders: []string{"qoder:cn"}}, + CrossProviderPool: true, + BeforeSideEffects: func() error { admitted++; return nil }, + Aggregations: stubAggregationResolver{agg: agg, onResolve: func() { + if admitted != 1 { + t.Fatalf("resolver ran before exactly one admission: calls=%d", admitted) + } + }}, + }) + if err != nil { + t.Fatal(err) + } + if admitted != 1 || fake.calls != tc.wantCalls { + t.Fatalf("admission calls=%d classifier calls=%d, want 1 and %d", admitted, fake.calls, tc.wantCalls) + } + if fake.calls > 0 && (fake.accountID != "cn" || fake.conversation != "" || fake.requestID != "") { + t.Fatalf("classifier used account=%q conversation=%q requestID=%q, want cn with no parent metadata", fake.accountID, fake.conversation, fake.requestID) + } + if plan := got.Route.AggregatePlan; plan == nil || len(plan.Members) != 1 || plan.Members[0].Model != tc.wantMember { + t.Fatalf("plan=%+v, want member %q", plan, tc.wantMember) + } + if stats := ex.SessionAffinity.Stats(); stats.Bindings != 1 || stats.Hits != 0 || stats.Misses != 0 || stats.Escapes != 0 { + t.Fatalf("classifier touched affinity: %+v", stats) + } + }) + } +} + +type recordingIntentChat struct { + fakeInProcessChat + accountID string + conversation string + requestID string +} + +func (f *recordingIntentChat) ChatNonStream(ctx context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + f.accountID, f.conversation = accountID, providers.ConversationFromContext(ctx) + f.requestID = RequestIDFromContext(ctx) + return f.fakeInProcessChat.ChatNonStream(ctx, accountID, req) +} + +func TestPrepareDoesNotFallBackOnAggregationCatalogError(t *testing.T) { + for _, catalogErr := range []error{errors.New("backend detail"), accounts.ErrAggregationNotFound} { + got, err := (ChatExecutor{}).Prepare(PrepareInput{ + Request: translate.ChatRequest{Model: "same-name"}, + CrossProviderPool: true, + Aggregations: stubAggregationResolver{ + agg: accounts.Aggregation{ID: "same-name", Enabled: true, Document: `{"version":1,"steps":[{"id":"m","kind":"member","provider":"qoder","model":"real"}]}`}, + catalogErr: catalogErr, + }, + }) + var prepareErr *PrepareError + if !errors.As(err, &prepareErr) || prepareErr.Status != http.StatusServiceUnavailable || prepareErr.Code != "aggregation_unavailable" { + t.Fatalf("catalog error %v: prepared=%+v err=%v", catalogErr, got, err) + } + if prepareErr.Message == catalogErr.Error() { + t.Fatalf("prepare exposed catalog internals: %v", prepareErr) + } + } +} + +func TestPrepareDispatchesOnlyClassifiersInSelectedPipelineBranch(t *testing.T) { + root := accounts.Aggregation{ID: "logical", Enabled: true, Document: `{ + "version":1,"steps":[{"id":"root","kind":"branch","classifier":{"provider":"workbuddy","model":"root-classifier"},"paths":[ + {"id":"direct","label":"Direct","intent":"direct","steps":[{"id":"answer","kind":"member","provider":"workbuddy","model":"direct-answer"}]}, + {"id":"group","label":"Group","fallback":true,"steps":[{"id":"nested","kind":"group","aggregation_id":"nested"}]} + ]}]}`} + nested := accounts.Aggregation{ID: "nested", Enabled: true, Document: `{ + "version":1,"steps":[{"id":"child","kind":"branch","classifier":{"provider":"workbuddy","model":"nested-classifier"},"paths":[ + {"id":"deep","label":"Deep","intent":"deep","steps":[{"id":"answer","kind":"member","provider":"workbuddy","model":"nested-answer"}]} + ]}]}`} + for _, tc := range []struct { + name string + rootLabel string + want []string + }{ + {name: "unselected subtree makes no request", rootLabel: "direct", want: []string{"root-classifier", "direct-answer"}}, + {name: "selected subtree gets a label", rootLabel: "unknown", want: []string{"root-classifier", "nested-classifier", "nested-answer"}}, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &pipelineRecordingChat{replies: map[string]string{ + "root-classifier": tc.rootLabel, "nested-classifier": "deep", "nested-answer": "nested", "direct-answer": "direct", + }} + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "workbuddy", Provider: "workbuddy", Region: "cn", Runtime: "in_process", + Models: []string{"root-classifier", "nested-classifier", "direct-answer", "nested-answer"}, + }) + ex := NewChatExecutor(pool, "") + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "workbuddy", Chat: fake}) + prepared, err := ex.Prepare(PrepareInput{ + Request: translate.ChatRequest{ + Model: "logical", Messages: []translate.ChatMessage{{Role: "user", Content: "select a path"}}, + }, + Identity: auth.Identity{AllowedProviders: []string{"workbuddy:cn"}}, + CrossProviderPool: true, + Aggregations: stubAggregationResolver{agg: root, catalog: map[string]accounts.Aggregation{"nested": nested}}, + }) + if err != nil || prepared.Route.AggregatePlan == nil { + t.Fatalf("prepare route=%+v err=%v", prepared.Route, err) + } + result, err := ex.ChatNonStreamPrepared(prepared.Context, prepared.Request, prepared.Route) + if err != nil || result.Model != tc.want[len(tc.want)-1] || !reflect.DeepEqual(fake.models, tc.want) { + t.Fatalf("dispatch result=%+v err=%v calls=%v want=%v", result, err, fake.models, tc.want) + } + }) + } +} + +type pipelineRecordingChat struct { + fakeInProcessChat + replies map[string]string + models []string +} + +func (f *pipelineRecordingChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + f.models = append(f.models, req.Model) + return providers.ChatOutcome{Model: req.Model, Content: f.replies[req.Model]}, nil +} + +func TestClassifyIntentDoesNotOverrideInheritedHardRegion(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "qoder-cn", Provider: "qoder", Region: "cn", Runtime: "in_process", Models: []string{"glm-5.2"}}) + pool.Upsert(Item{ID: "qoder-global", Provider: "qoder", Region: "global", Runtime: "in_process", Models: []string{"glm-5.2"}}) + ex := NewChatExecutor(pool, "") + fake := &recordingIntentChat{} + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "qoder", Chat: fake}) + ctx := WithRegionFilter(context.Background(), " CN ") + conflict := accounts.ClassifierTarget{Provider: "qoder", Region: "gl", Model: "glm-5.2"} + if labels := ex.ClassifyIntent(ctx, []accounts.ClassifierTarget{conflict}, "hello"); len(labels) != 0 || fake.calls != 0 { + t.Fatalf("conflicting target dispatched: labels=%v calls=%d", labels, fake.calls) + } + for i, region := range []string{"cn", "", "auto"} { + target := accounts.ClassifierTarget{Provider: "qoder", Region: region, Model: "glm-5.2"} + if labels := ex.ClassifyIntent(ctx, []accounts.ClassifierTarget{target}, "hello"); labels[target.Key()] != "OK" || fake.calls != i+1 || fake.accountID != "qoder-cn" { + t.Fatalf("target %+v: labels=%v calls=%d account=%q", target, labels, fake.calls, fake.accountID) + } + } +} + func TestPrepareQoderWindowGoesToMaxInputTokens(t *testing.T) { ex := NewChatExecutor(NewPool(nil, nil), "") contexts := &stubContexts{value: 500000, ok: true} @@ -252,7 +523,7 @@ func TestPrepareNativeResponsesKeepsCompatSeedAndReasoning(t *testing.T) { if err != nil { t.Fatal(err) } - if sessionKeyFromContext(got.Context) == "" || sessionKeyFromContext(got.Context) != sessionKeyFromContext(chatOnly.Context) { + if got.Route.SessionKey == "" || got.Route.SessionKey != chatOnly.Route.SessionKey { t.Fatal("native request replaced the compatibility session seed") } if len(logs.entries) != 1 || logs.entries[0].RequestedReasoning != "high" { @@ -295,6 +566,106 @@ func TestPrepareBareModelEmptyFilterWhenPoolEnabled(t *testing.T) { } } +func TestPrepareDoesNotInheritLegacyRouteOrConversation(t *testing.T) { + t.Setenv("CLI2API_MSGSTAT_SHARDS", "0") + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "only", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"glm-5.2"}}) + ex := NewChatExecutor(pool, "") + fake := &recordingIntentChat{} + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "workbuddy", Chat: fake}) + ex.SessionAffinity.Bind("stale-session", "missing") + + ctx := WithRequestID(context.Background(), "stale-request") + ctx = WithClientUserAgent(ctx, "test-agent") + ctx = WithConversation(ctx, "stale-conversation") + ctx = WithSessionKey(ctx, "stale-session") + ctx = WithRegionFilter(ctx, "cn") + ctx = WithAllowedProviders(ctx, []string{"qoder:cn"}) + ctx = WithAggregatePlan(ctx, NewAggregatePlan(accounts.Aggregation{ + ID: "stale-plan", Members: []accounts.AggregationMember{{Provider: "qoder", Region: "cn", Model: "wrong"}}, + })) + got, err := ex.Prepare(PrepareInput{ + Context: ctx, + Request: translate.ChatRequest{Model: "glm-5.2"}, + Identity: auth.ConsoleIdentity(), + CrossProviderPool: true, + NewRequestID: func() string { return "new-request" }, + }) + if err != nil { + t.Fatal(err) + } + route := got.Route + if route.RequestID != "new-request" || route.PublicModel != "glm-5.2" || route.ProviderFilter != "" || + route.RegionFilter != "" || route.Prefer != "" || route.SessionKey != "" || + len(route.AllowedProviders) != 0 || route.AggregatePlan != nil { + t.Fatalf("prepared route inherited stale constraints: %+v", route) + } + if providers.ConversationFromContext(got.Context) != "" || RequestIDFromContext(got.Context) != route.RequestID || + ClientUserAgentFromContext(got.Context) != "test-agent" || providers.ConversationFromContext(ctx) != "stale-conversation" { + t.Fatal("prepared context did not replace request/conversation metadata or preserve the user agent") + } + before := ex.SessionAffinity.Stats() + result, err := ex.ChatNonStreamPrepared(got.Context, got.Request, route) + if err != nil || result.AccountID != "only" || fake.calls != 1 || fake.conversation != "" || fake.requestID != route.RequestID { + t.Fatalf("prepared result=%+v err=%v calls=%d conversation=%q requestID=%q", result, err, fake.calls, fake.conversation, fake.requestID) + } + if after := ex.SessionAffinity.Stats(); before != after { + t.Fatalf("empty explicit session touched the cache: before=%+v after=%+v", before, after) + } +} + +func TestRouteInputFromContextKeepsLegacySnapshot(t *testing.T) { + req := translate.ChatRequest{Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "from legacy"}}} + plan := NewAggregatePlan(accounts.Aggregation{ID: "legacy-plan"}) + ctx := WithRequestID(context.Background(), "req-legacy") + ctx = WithRegionFilter(ctx, "cn") + ctx = WithAllowedProviders(ctx, []string{"qoder:cn"}) + ctx = WithAggregatePlan(ctx, plan) + route := routeInputFromContext(ctx, req, " account ", " QODER ") + if route.RequestID != "req-legacy" || route.PublicModel != req.Model || route.RouteModel != req.Model || route.ProviderFilter != "qoder" || + route.RegionFilter != "cn" || route.Prefer != "account" || route.SessionKey != contentSessionKey(req) || + route.SessionKey == "" || route.AggregatePlan != plan || len(route.AllowedProviders) != 1 || route.AllowedProviders[0] != "qoder:cn" { + t.Fatalf("legacy route snapshot=%+v", route) + } + route.AllowedProviders[0] = "other" + if allowedProvidersFrom(ctx)[0] != "qoder:cn" { + t.Fatal("legacy context allowlist was aliased") + } + if keyed := routeInputFromContext(WithSessionKey(ctx, "legacy-key"), req, "", ""); keyed.SessionKey != "legacy-key" { + t.Fatalf("explicit key did not override content: %q", keyed.SessionKey) + } +} + +func TestRouteInputFromContextParsesPrefixOnce(t *testing.T) { + ctx := WithRegionFilter(context.Background(), "global") + req := translate.ChatRequest{Model: "qoder-cn/example"} + route := routeInputFromContext(ctx, req, "", "workbuddy") + if route.PublicModel != "qoder-cn/example" || route.RouteModel != "example" || route.ProviderFilter != "qoder" || route.RegionFilter != "cn" { + t.Fatalf("route with explicit prefix = %+v", route) + } + req.Model = "command/deepseek/example" + route = routeInputFromContext(ctx, req, "", "") + if route.RouteModel != "deepseek/example" || route.ProviderFilter != "command" || route.RegionFilter != "global" { + t.Fatalf("route with namespace and legacy region = %+v", route) + } +} + +func TestPreparedDispatchUsesRouteModelRatherThanDisplayName(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "workbuddy", Provider: "workbuddy", Runtime: "in_process", Models: []string{"glm-5.2"}}) + ex := NewChatExecutor(pool, "") + fake := &recordingIntentChat{} + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "workbuddy", Chat: fake}) + res, err := ex.ChatNonStreamPrepared(context.Background(), translate.ChatRequest{Model: "not-the-route-model"}, RouteInput{ + PublicModel: "qoder-cn/display-name", RouteModel: "glm-5.2", ProviderFilter: "workbuddy", RegionFilter: "global", + }) + if err != nil || res.Model != "glm-5.2" || fake.calls != 1 || fake.accountID != "workbuddy" { + t.Fatalf("dispatch disagrees with explicit route: res=%+v err=%v calls=%d account=%s", res, err, fake.calls, fake.accountID) + } +} + func TestPrepareSessionKeyIsolatesByIdentity(t *testing.T) { ex := NewChatExecutor(NewPool(nil, nil), "") req := translate.ChatRequest{Model: "qoder/glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}} @@ -311,10 +682,10 @@ func TestPrepareSessionKeyIsolatesByIdentity(t *testing.T) { if err != nil { t.Fatal(err) } - if sessionKeyFromContext(console.Context) == "" || sessionKeyFromContext(console.Context) == sessionKeyFromContext(keyed.Context) { + if console.Route.SessionKey == "" || console.Route.SessionKey == keyed.Route.SessionKey { t.Fatalf("session keys must differ by identity") } - if providers.ConversationFromContext(console.Context) != sessionKeyFromContext(console.Context) { + if providers.ConversationFromContext(console.Context) != console.Route.SessionKey { t.Fatal("conversation id source must follow the session key") } header, err := ex.Prepare(PrepareInput{ @@ -325,7 +696,7 @@ func TestPrepareSessionKeyIsolatesByIdentity(t *testing.T) { if err != nil { t.Fatal(err) } - if sessionKeyFromContext(header.Context) == sessionKeyFromContext(console.Context) { + if header.Route.SessionKey == console.Route.SessionKey { t.Fatal("header session must not reuse content seed") } } @@ -473,12 +844,12 @@ func TestPrepareStripsAutoPrefix(t *testing.T) { if got.Request.Model != "qwen3.8-max" { t.Errorf("Request.Model = %q, want qwen3.8-max (prefix stripped)", got.Request.Model) } - if r := regionFilterFromContext(got.Context); r != "" { + if r := got.Route.RegionFilter; r != "" { t.Errorf("region = %q, want empty (auto selects region in pool)", r) } } -func TestPrepareStripsRegionPrefixIntoContext(t *testing.T) { +func TestPrepareStripsRegionPrefixIntoRoute(t *testing.T) { ex := NewChatExecutor(NewPool(nil, nil), "") got, err := ex.Prepare(PrepareInput{ Request: translate.ChatRequest{Model: "workbuddy-cn/glm-5.3-flash", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}}, @@ -494,8 +865,8 @@ func TestPrepareStripsRegionPrefixIntoContext(t *testing.T) { if got.ProviderFilter != "workbuddy" || got.Request.Model != "glm-5.3-flash" || got.PublicModel != "workbuddy-cn/glm-5.3-flash" { t.Fatalf("provider=%q model=%q publicModel=%q", got.ProviderFilter, got.Request.Model, got.PublicModel) } - if r := regionFilterFromContext(got.Context); r != "cn" { - t.Fatalf("regionFilterFromContext = %q, want cn", r) + if r := got.Route.RegionFilter; r != "cn" { + t.Fatalf("regionFilter = %q, want cn", r) } } @@ -514,7 +885,7 @@ func TestPrepareBarePrefixSetsNoRegionFilter(t *testing.T) { if got.ProviderFilter != "qoder" || got.Request.Model != "qwen3.8-max" { t.Errorf("provider=%q model=%q, want qoder / qwen3.8-max", got.ProviderFilter, got.Request.Model) } - if r := regionFilterFromContext(got.Context); r != "" { + if r := got.Route.RegionFilter; r != "" { t.Errorf("region = %q, want empty (bare prefix must not pin cn)", r) } } diff --git a/internal/executor/probe.go b/internal/executor/probe.go index 6bc38402e..bc5a22886 100644 --- a/internal/executor/probe.go +++ b/internal/executor/probe.go @@ -55,10 +55,8 @@ const maxConcurrentProbeAttempts = 8 var probeAttemptSem = make(chan struct{}, maxConcurrentProbeAttempts) // ProbeModel checks publicModel against every currently routable account. It -// reuses normal routing and provider adapters, but caps output at one token so -// a full account/model matrix check stays cheap. Unlike a chat failover loop, -// it never stops after the first working account: the operator needs to know -// which accounts actually serve the model. +// uses the pool's availability checks and caps output at one token. Each +// account is checked independently of the request router and its feedback. func (e ChatExecutor) ProbeModel(ctx context.Context, publicModel string) ProbeModelResult { result := ProbeModelResult{Model: publicModel, Accounts: []ProbeAccountResult{}} publicModel = strings.TrimSpace(publicModel) @@ -86,89 +84,44 @@ func (e ChatExecutor) ProbeModel(ctx context.Context, publicModel string) ProbeM // bare when it is on. Resolve prefixes while allowing both; explicit // region prefixes still pin the route. providerFilter, modelRegion := ResolveProviderFilter(&request, true) - routeModel := request.Model - regionFilter := regionFilterFromContext(probeCtx) + regionFilter := strings.TrimSpace(regionFilterFromContext(probeCtx)) if regionFilter == "" { regionFilter = modelRegion + } else if modelRegion != "" && NormalizeRegion(regionFilter) != modelRegion { + result.Message = "no accounts available" + return result } - allowed := allowedProvidersFrom(probeCtx) - - items := e.probeAccounts(providerFilter, regionFilter, routeModel, allowed) + q := RouteQuery{ + PublicModel: request.Model, + ProviderFilter: providerFilter, + RegionFilter: regionFilter, + AllowedProviders: allowedProvidersFrom(probeCtx), + } + // Take a read-only snapshot of the matrix, excluding accounts that are + // already cooling or busy. Each row is rechecked before dispatch. + items := e.Pool.ReadyItems(q) if len(items) == 0 { result.Message = "no accounts available" return result } + sort.Slice(items, func(i, j int) bool { + if items[i].Provider != items[j].Provider { + return items[i].Provider < items[j].Provider + } + return items[i].ID < items[j].ID + }) started := time.Now() firstOK := -1 - firstFailure := -1 -probeAccountsLoop: - for _, item := range items { - // If the operator request (or the batch deadline) is gone, stop making - // new upstream calls instead of marking every remaining account as a - // client cancellation. - if err := probeCtx.Err(); err != nil { + for _, candidate := range items { + accountResult, checked := e.probeAccount(probeCtx, ctx, q, candidate, request) + if !checked { break } - accountResult := ProbeAccountResult{ - AccountID: item.ID, - Provider: firstNonEmpty(item.Provider, providerFilter), - Region: item.Region, - } - if !e.acquireInFlight("", item.ID) { - accountResult.Code = "account_busy" - accountResult.Kind = accounts.KindRateLimit - accountResult.Message = "account is at capacity" - result.Accounts = append(result.Accounts, accountResult) - if firstFailure < 0 { - firstFailure = len(result.Accounts) - 1 - } - continue - } - // Bound the number of simultaneous live calls across all probe batches. - select { - case probeAttemptSem <- struct{}{}: - case <-probeCtx.Done(): - e.releaseInFlight("", item.ID) - break probeAccountsLoop - } - accountStarted := time.Now() - accountCtx, accountCancel := context.WithTimeout(probeCtx, 15*time.Second) - probeErr := e.probeModelAttempt(accountCtx, item, request) - // Capture the deadline state before cancel(): cancel() always sets Err() - // to Canceled, which would hide a genuine probe-owned timeout. - accountTimedOut := errors.Is(accountCtx.Err(), context.DeadlineExceeded) - accountCancel() - <-probeAttemptSem - e.releaseInFlight("", item.ID) - accountResult.LatencyMS = int(time.Since(accountStarted).Milliseconds()) - if probeErr == nil { - accountResult.OK = true - accountResult.Status = http.StatusOK - result.Accounts = append(result.Accounts, accountResult) - if firstOK < 0 { - firstOK = len(result.Accounts) - 1 - } - continue - } - // A deadline owned by this probe is an upstream timeout, not a client - // cancellation. Only a cancelled parent request is a real cancellation. - if errors.Is(probeErr, context.DeadlineExceeded) && ctx.Err() == nil && accountTimedOut { - accountResult.Status = http.StatusBadGateway - accountResult.Code = "probe_timeout" - accountResult.Kind = accounts.KindUnavailable - accountResult.Message = "upstream probe timed out" - } else { - classified := classifyProbeError(probeErr) - accountResult.Status = classified.Status - accountResult.Code = classified.Code - accountResult.Kind = classified.Kind - accountResult.Message = classified.Message + if accountResult.OK && firstOK < 0 { + firstOK = len(result.Accounts) } result.Accounts = append(result.Accounts, accountResult) - if firstFailure < 0 { - firstFailure = len(result.Accounts) - 1 - } } result.AttemptCount = len(result.Accounts) @@ -181,8 +134,8 @@ probeAccountsLoop: result.LatencyMS = okAccount.LatencyMS return result } - if firstFailure >= 0 { - failed := result.Accounts[firstFailure] + if len(result.Accounts) > 0 { + failed := result.Accounts[0] result.Status = failed.Status result.Code = failed.Code result.Kind = failed.Kind @@ -191,30 +144,106 @@ probeAccountsLoop: return result } -// probeAccounts enumerates every currently routable account for the model. -// It uses a read-only Pool snapshot so probing never advances rotation cursors, -// region latches, or weight counters used by live traffic. -func (e ChatExecutor) probeAccounts(providerFilter, regionFilter, publicModel string, allowed []string) []Item { - if e.Pool == nil { - return nil +// probeAccount returns false if the batch stops before checking this row. +func (e ChatExecutor) probeAccount(ctx, parentCtx context.Context, q RouteQuery, candidate Item, request translate.ChatRequest) (ProbeAccountResult, bool) { + if ctx.Err() != nil { + return ProbeAccountResult{}, false } - q := RouteQuery{ - PublicModel: publicModel, - ProviderFilter: providerFilter, - RegionFilter: regionFilter, - AllowedProviders: allowed, + // Wait for the shared probe limit before occupying an account slot. + select { + case probeAttemptSem <- struct{}{}: + case <-ctx.Done(): + return ProbeAccountResult{}, false } - items := e.Pool.RoutableItems(q) - sort.Slice(items, func(i, j int) bool { - if items[i].Provider != items[j].Provider { - return items[i].Provider < items[j].Provider + defer func() { <-probeAttemptSem }() + + item, busy := e.Pool.reserveProbeAccount(ctx, candidate.ID, q) + if item.ID == "" { + if ctx.Err() != nil { + return ProbeAccountResult{}, false } - return items[i].ID < items[j].ID - }) - return items + result := ProbeAccountResult{ + AccountID: candidate.ID, + Provider: firstNonEmpty(candidate.Provider, q.ProviderFilter), + Region: candidate.Region, + } + if busy { + result.Code = "account_busy" + result.Kind = accounts.KindRateLimit + result.Message = "account is at capacity" + } else { + result.Status = http.StatusServiceUnavailable + result.Code = "account_unavailable" + result.Kind = accounts.KindUnavailable + result.Message = "account is no longer available for this model" + } + return result, true + } + defer e.Pool.Release(item.ID) + + started := time.Now() + accountCtx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + if accountCtx.Err() != nil { + return ProbeAccountResult{}, false + } + probeErr := e.probeModelAttempt(accountCtx, item, request) + result := ProbeAccountResult{ + AccountID: item.ID, + Provider: firstNonEmpty(item.Provider, q.ProviderFilter), + Region: item.Region, + LatencyMS: int(time.Since(started).Milliseconds()), + } + if probeErr == nil { + result.OK = true + result.Status = http.StatusOK + return result, true + } + // A probe-owned deadline is an upstream timeout while the parent request + // is still active. Check the deadline before the deferred cancel. + if errors.Is(probeErr, context.DeadlineExceeded) && parentCtx.Err() == nil && errors.Is(accountCtx.Err(), context.DeadlineExceeded) { + result.Status = http.StatusBadGateway + result.Code = "probe_timeout" + result.Kind = accounts.KindUnavailable + result.Message = "upstream probe timed out" + } else { + classified := classifyProbeError(probeErr) + result.Status = classified.Status + result.Code = classified.Code + result.Kind = classified.Kind + result.Message = classified.Message + } + return result, true +} + +// reserveProbeAccount rechecks a single matrix row and occupies its slot in +// the same critical section. Only that account can satisfy this reservation. +// The second result reports an otherwise eligible account at capacity. +func (p *Pool) reserveProbeAccount(ctx context.Context, id string, q RouteQuery) (Item, bool) { + p.mu.Lock() + defer p.mu.Unlock() + if ctx.Err() != nil { + return Item{}, false + } + i := p.itemIndexLocked(id) + if i < 0 { + return Item{}, false + } + item := &p.items[i] + now := time.Now() + q, _ = p.configureRouteLocked(q, now) + if !routeMatches(*item, q) || itemDown(*item, now) || itemModelDown(*item, q, now) { + return Item{}, false + } + if itemSaturated(*item) { + return Item{}, true + } + acquireItemLocked(item, now) + return item.clone(), false } func (e ChatExecutor) probeModelAttempt(ctx context.Context, item Item, request translate.ChatRequest) error { + request = sanitizeForItem(item, request) if isInProcessItem(item) || e.qoderDirect(item) { if e.Providers == nil { return fmt.Errorf("provider registry unavailable") @@ -223,7 +252,7 @@ func (e ChatExecutor) probeModelAttempt(ctx context.Context, item Item, request if !ok || adapter.Chat == nil { return fmt.Errorf("provider %s does not implement chat", itemProvider(item)) } - _, err := adapter.Chat.ChatNonStream(ctx, item.ID, sanitizeForItem(item, request)) + _, err := adapter.Chat.ChatNonStream(ctx, item.ID, request) return err } diff --git a/internal/executor/probe_test.go b/internal/executor/probe_test.go index 5a055618f..c0df9b95a 100644 --- a/internal/executor/probe_test.go +++ b/internal/executor/probe_test.go @@ -2,8 +2,13 @@ package executor import ( "context" + "encoding/json" + "io" "net/http" + "slices" + "strings" "testing" + "time" "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/providers" @@ -15,12 +20,18 @@ type probeCaptureChat struct { reqs []translate.ChatRequest accounts []string err error + onChat func(context.Context, string) error } -func (f *probeCaptureChat) ChatNonStream(_ context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { +func (f *probeCaptureChat) ChatNonStream(ctx context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { f.req = req f.reqs = append(f.reqs, req) f.accounts = append(f.accounts, accountID) + if f.onChat != nil { + if err := f.onChat(ctx, accountID); err != nil { + return providers.ChatOutcome{}, err + } + } if f.err != nil { return providers.ChatOutcome{}, f.err } @@ -68,6 +79,9 @@ func TestProbeModelUsesMinimalRequestAndDoesNotCoolAccount(t *testing.T) { if !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 { t.Fatalf("probe must not cool the account: down=%v model=%v", item.DownUntil, item.ModelDownUntil) } + if len(item.ProvenModels) != 0 || item.StateVersion != 0 { + t.Fatalf("probe must not persist model success: proven=%v version=%d", item.ProvenModels, item.StateVersion) + } if item.InFlight != 0 { t.Fatalf("probe leaked in-flight slot: %d", item.InFlight) } @@ -86,16 +100,19 @@ func TestProbeModelDoesNotMutateRoutingCursor(t *testing.T) { pool.mu.Lock() pool.ensureRotationKey(routeKey) pool.lastPicked[routeKey] = "wb1" - before := pool.lastPicked[routeKey] + pool.lastRegion[routeKey] = "cn" + pool.weightCounter = map[string]map[string]int64{routeKey: {"wb1": 7}} pool.mu.Unlock() - _ = e.ProbeModel(context.Background(), "glm-5.2") + if res := e.ProbeModel(context.Background(), "glm-5.2"); !res.OK || res.AttemptCount != 2 { + t.Fatalf("probe result: %+v", res) + } pool.mu.Lock() - after := pool.lastPicked[routeKey] + pick, region, weight := pool.lastPicked[routeKey], pool.lastRegion[routeKey], pool.weightCounter[routeKey]["wb1"] pool.mu.Unlock() - if after != before { - t.Fatalf("probe mutated routing cursor: before=%q after=%q", before, after) + if pick != "wb1" || region != "cn" || weight != 7 { + t.Fatalf("probe mutated routing state: account=%q region=%q weight counter=%d", pick, region, weight) } } @@ -141,9 +158,15 @@ func TestProbeModelFailureDoesNotCoolAccount(t *testing.T) { }} registry := providers.NewRegistry() registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) - e := ChatExecutor{Pool: pool, Providers: registry} + pool.SetObserver(func(Item) { t.Error("probe must not persist account state") }) + e := ChatExecutor{ + Pool: pool, Providers: registry, + OnAttempt: func(accounts.RequestAttempt) { t.Error("probe must not write request attempts") }, + OnInFlightAcquire: func(string, string) { t.Error("probe must not acquire a request recorder slot") }, + OnInFlightRelease: func(string, string) { t.Error("probe must not release a request recorder slot") }, + } - res := e.ProbeModel(context.Background(), "glm-5.2") + res := e.ProbeModel(WithRequestID(context.Background(), "probe"), "glm-5.2") if res.OK { t.Fatal("probe should report failure") } @@ -161,3 +184,202 @@ func TestProbeModelFailureDoesNotCoolAccount(t *testing.T) { t.Fatalf("probe leaked in-flight slot: %d", item.InFlight) } } + +func TestProbeModelRechecksAccountBeforeDispatch(t *testing.T) { + for _, tc := range []struct { + name, model, region string + allowed []string + update func(*Pool, Item) + wantCode string + }{ + {name: "provider", model: "workbuddy/glm-5.2", update: func(p *Pool, item Item) { + item.Provider = "qoder" + p.Upsert(item) + }}, + {name: "model region prefix", model: "workbuddy-cn/glm-5.2", update: func(p *Pool, item Item) { + item.Region = "global" + p.Upsert(item) + }}, + {name: "explicit region", model: "glm-5.2", region: "cn", update: func(p *Pool, item Item) { + item.Region = "global" + p.Upsert(item) + }}, + {name: "provider region grant", model: "glm-5.2", allowed: []string{"workbuddy:cn"}, update: func(p *Pool, item Item) { + item.Region = "global" + p.Upsert(item) + }}, + {name: "model grant", model: "glm-5.2", update: func(p *Pool, item Item) { + p.SetModelRouting(item.ID, nil, nil, true) + }}, + {name: "catalog", model: "glm-5.2", update: func(p *Pool, item Item) { + item.Models = []string{"another"} + p.Upsert(item) + }}, + {name: "removed", model: "glm-5.2", update: func(p *Pool, item Item) { + p.Remove(item.ID) + }}, + {name: "new account cooldown", model: "glm-5.2", update: func(p *Pool, item Item) { + item.DownUntil = time.Now().Add(time.Hour) + p.Upsert(item) + }}, + {name: "new model cooldown", model: "glm-5.2", update: func(p *Pool, item Item) { + item.ModelDownUntil = map[string]time.Time{"glm-5.2": time.Now().Add(time.Hour)} + p.Upsert(item) + }}, + {name: "newly busy", model: "glm-5.2", wantCode: "account_busy", update: func(p *Pool, item Item) { + p.Acquire(item.ID) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + pool := NewPool(nil, nil) + first := Item{ID: "a", Provider: "workbuddy", Region: "cn", Runtime: string(providers.RuntimeInProcess), Models: []string{"glm-5.2"}, MaxInFlight: 1} + second := first + second.ID = "b" + pool.Upsert(first) + pool.Upsert(second) + chat := &probeCaptureChat{onChat: func(_ context.Context, id string) error { + if id == first.ID { + live, _ := pool.ByID(id) + if live.InFlight != 1 { + t.Errorf("first account has %d in-flight slots, want 1", live.InFlight) + } + tc.update(pool, second) + } + return nil + }} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + registry.Register(providers.Adapter{ID: "qoder", Chat: chat}) + e := ChatExecutor{Pool: pool, Providers: registry} + ctx := WithAllowedProviders(WithRegionFilter(context.Background(), tc.region), tc.allowed) + + res := e.ProbeModel(ctx, tc.model) + if !slices.Equal(chat.accounts, []string{first.ID}) { + t.Fatalf("dispatched accounts=%v, want [%s]", chat.accounts, first.ID) + } + wantCode := firstNonEmpty(tc.wantCode, "account_unavailable") + if !res.OK || len(res.Accounts) != 2 || res.Accounts[1].AccountID != second.ID || res.Accounts[1].OK || res.Accounts[1].Code != wantCode { + t.Fatalf("probe results=%+v, want second row rejected with %s", res.Accounts, wantCode) + } + wantInFlight := 0 + if wantCode == "account_busy" { + wantInFlight = 1 + } + if live, _ := pool.ByID(second.ID); live.InFlight != wantInFlight { + t.Fatalf("second account has %d in-flight slots, want %d", live.InFlight, wantInFlight) + } + }) + } +} + +func TestProbeModelMatrixRespectsCooldownsAndScope(t *testing.T) { + pool := NewPool(nil, nil) + cn := Item{ID: "cn", Provider: "workbuddy", Region: "cn", Runtime: string(providers.RuntimeInProcess), Models: []string{"glm-5.2"}} + global, accountCooling, modelCooling := cn, cn, cn + global.ID, global.Region = "global", "global" + accountCooling.ID, accountCooling.DownUntil = "account-cooling", time.Now().Add(time.Hour) + modelCooling.ID, modelCooling.ModelDownUntil = "model-cooling", map[string]time.Time{"glm-5.2": time.Now().Add(time.Hour)} + for _, item := range []Item{cn, global, accountCooling, modelCooling} { + pool.Upsert(item) + } + for _, tc := range []struct { + name, model, region string + allowed, want []string + }{ + {name: "unqualified matrix", model: "glm-5.2", want: []string{"cn", "global"}}, + {name: "same explicit region", model: "workbuddy-gl/glm-5.2", region: "gl", want: []string{"global"}}, + {name: "conflicting region scopes", model: "workbuddy-cn/glm-5.2", region: "global"}, + {name: "conflicting region grant", model: "workbuddy-cn/glm-5.2", allowed: []string{"workbuddy:global"}}, + } { + t.Run(tc.name, func(t *testing.T) { + chat := &probeCaptureChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + e := ChatExecutor{Pool: pool, Providers: registry} + ctx := WithAllowedProviders(WithRegionFilter(context.Background(), tc.region), tc.allowed) + res := e.ProbeModel(ctx, tc.model) + if !slices.Equal(chat.accounts, tc.want) || res.AttemptCount != len(tc.want) { + t.Fatalf("checked accounts=%v, want %v (result=%+v)", chat.accounts, tc.want, res) + } + }) + } +} + +type probeRoundTripFunc func(*http.Request) (*http.Response, error) + +func (f probeRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestProbeModelWorkerUsesCurrentAliasAndNativeModel(t *testing.T) { + pool := NewPool([]string{"http://first.test", "http://old.test"}, []string{"a", "b"}) + for _, id := range []string{"a", "b"} { + item, _ := pool.ByID(id) + item.Models = []string{"old-model"} + item.ModelAliases = map[string]string{"friendly": "old-model"} + item.NativeModels = map[string]string{"old-model": "Old.Native"} + pool.Upsert(item) + } + var got []string + client := &http.Client{Transport: probeRoundTripFunc(func(r *http.Request) (*http.Response, error) { + defer r.Body.Close() + var payload struct { + Model string `json:"model"` + MaxTokens int `json:"max_tokens"` + } + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + return nil, err + } + id := r.Header.Get("X-Qoder-Account") + got = append(got, id+"/"+r.URL.Host+"/"+payload.Model) + if payload.MaxTokens != 1 { + t.Errorf("worker probe max_tokens=%d, want 1", payload.MaxTokens) + } + if id == "a" { + current, _ := pool.ByID("b") + current.URL = "http://new.test" + current.Models = []string{"new-model"} + current.ModelAliases = map[string]string{"friendly": "new-model"} + current.NativeModels = map[string]string{"new-model": "New.Native"} + pool.Upsert(current) + } + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"choices":[{"message":{"content":"OK"}}]}`))}, nil + })} + e := ChatExecutor{Pool: pool, HTTPClient: client} + res := e.ProbeModel(context.Background(), "qoder/friendly") + want := []string{"a/first.test/Old.Native", "b/new.test/New.Native"} + if !res.OK || !slices.Equal(got, want) { + t.Fatalf("worker probes=%v, want %v (result=%+v)", got, want, res) + } +} + +func TestProbeModelCancellationReleasesSlots(t *testing.T) { + pool := NewPool(nil, nil) + for _, id := range []string{"a", "b"} { + pool.Upsert(Item{ID: id, Provider: "workbuddy", Runtime: string(providers.RuntimeInProcess), Models: []string{"glm-5.2"}, MaxInFlight: 1}) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + chat := &probeCaptureChat{onChat: func(ctx context.Context, id string) error { + item, _ := pool.ByID(id) + if item.InFlight != 1 { + t.Errorf("account %s has %d in-flight slots, want 1", id, item.InFlight) + } + cancel() + return ctx.Err() + }} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + e := ChatExecutor{Pool: pool, Providers: registry} + before := len(probeAttemptSem) + res := e.ProbeModel(ctx, "glm-5.2") + if !slices.Equal(chat.accounts, []string{"a"}) || len(res.Accounts) != 1 || res.Accounts[0].Kind != accounts.KindCanceled { + t.Fatalf("dispatched=%v, result=%+v, want one canceled attempt", chat.accounts, res) + } + if after := len(probeAttemptSem); after != before { + t.Errorf("probe semaphore count changed: before=%d after=%d", before, after) + } + for _, item := range pool.Items() { + if item.InFlight != 0 || !item.InFlightSince.IsZero() { + t.Errorf("probe leaked reservation for %s: slots=%d since=%v", item.ID, item.InFlight, item.InFlightSince) + } + } +} diff --git a/internal/executor/providers_test.go b/internal/executor/providers_test.go index bfdf6149e..16fb8a857 100644 --- a/internal/executor/providers_test.go +++ b/internal/executor/providers_test.go @@ -11,6 +11,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -19,6 +20,68 @@ type fakeInProcessChat struct { provider string } +type recordingChat struct { + calls int + got translate.ChatRequest +} + +func (f *recordingChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + f.calls++ + f.got = req + outcome := providers.ChatOutcome{Model: req.Model, Content: "OK", FinishReason: "stop"} + if len(req.Tools) > 0 { + outcome.ToolCalls = json.RawMessage(`[{"id":"call_1","type":"function","function":{"name":"run","arguments":"{\"cmd\":\"echo ok\"}"}}]`) + outcome.FinishReason = "tool_calls" + } + return outcome, nil +} + +func (f *recordingChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, errors.New("stream unsupported in fake") +} + +func TestToolingContractReachesRegisteredAdapter(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "q1", Provider: "qoder", Runtime: "in_process", Models: []string{"glm-5.2"}}) + registry := providers.NewRegistry() + recorder := &recordingChat{} + registry.Register(providers.Adapter{ID: "qoder", Chat: recorder}) + ex := NewChatExecutor(pool, "") + ex.Providers = registry + + tools := json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]},"strict":true}}]`) + choice := json.RawMessage(`"required"`) + parallel := false + request := translate.ChatRequest{ + Model: "glm-5.2", + Protocol: string(toolcall.ProtocolChat), + Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + Tools: tools, + ToolChoice: choice, + ParallelToolCalls: ¶llel, + } + if _, err := ex.ChatNonStream(context.Background(), request, "q1", ""); err != nil { + t.Fatal(err) + } + if recorder.calls != 1 { + t.Fatalf("adapter calls=%d", recorder.calls) + } + if string(recorder.got.Tools) != string(tools) || string(recorder.got.ToolChoice) != string(choice) || recorder.got.ParallelToolCalls == nil || *recorder.got.ParallelToolCalls { + t.Fatalf("adapter received mutated tool contract: tools=%s choice=%s parallel=%v", recorder.got.Tools, recorder.got.ToolChoice, recorder.got.ParallelToolCalls) + } + + recorder.calls = 0 + item := Item{ID: "q1", Provider: "qoder", Runtime: "in_process", Models: []string{"glm-5.2"}, NoToolsModels: []string{"qoder/text-only"}} + pool.Upsert(item) + request.Model = "qoder/text-only" + if _, err := ex.ChatNonStream(context.Background(), request, "q1", ""); err == nil { + t.Fatal("catalog-declared no-tool model was routed") + } + if recorder.calls != 0 { + t.Fatalf("adapter was called for a no-tool model: %d", recorder.calls) + } +} + func (f *fakeInProcessChat) ChatNonStream(ctx context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { f.calls++ if req.Model != "glm-5.2" { @@ -482,7 +545,7 @@ func TestNoRoutableAccountsClassifiedAs503(t *testing.T) { // permission_error, never the generic 502. func TestPickProviderNotAllowedFallback(t *testing.T) { ex := NewChatExecutor(NewPool(nil, nil), "") - _, err := ex.pick("req", "", "trae", "", "glm-5.2", []string{"workbuddy:cn"}, nil, nil, nil) + _, err := ex.reserveTarget("req", RouteQuery{ProviderFilter: "trae", PublicModel: "glm-5.2", AllowedProviders: []string{"workbuddy:cn"}}, nil) if err == nil { t.Fatal("an ungranted provider filter must fail even with an empty pool") } diff --git a/internal/executor/public_error.go b/internal/executor/public_error.go new file mode 100644 index 000000000..c7a767b62 --- /dev/null +++ b/internal/executor/public_error.go @@ -0,0 +1,82 @@ +package executor + +import ( + "net/http" + "regexp" + "strings" +) + +var sensitivePatterns = []*regexp.Regexp{ + regexp.MustCompile(`(?i)bearer\s+[a-z0-9._~+/=-]{8,}`), + regexp.MustCompile(`(?i)(api[_-]?key|token|secret|password|authorization)\s*[:=]\s*[^\s,;]{6,}`), + regexp.MustCompile(`(?i)sk-[a-z0-9_-]{12,}`), + regexp.MustCompile(`(?i)gh[pousr]_[a-z0-9]{20,}`), + regexp.MustCompile(`(?i)xox[baprs]-[a-z0-9-]{10,}`), + regexp.MustCompile(`(?i)https?://[^\s]*[?&](token|key|secret|sig)=[^\s&]+`), + regexp.MustCompile(`[A-Za-z0-9+/]{40,}={0,2}`), +} + +// PublicErrorMessage returns the only text a client may see for a classified +// failure. Provider and transport failures use a stable generic sentence so an +// upstream body cannot smuggle credentials, URLs, account identifiers, or +// prompt fragments into an HTTP error or an SSE failure frame. Client-side +// validation errors keep their detail after redaction. +func PublicErrorMessage(classified Classified) string { + if classified.PublicMessage != "" { + return classified.PublicMessage + } + switch classified.Source { + case "provider_http", "provider_sse", "adapter", "worker", "transport": + return genericUpstreamMessage(classified) + } + message := strings.TrimSpace(RedactSensitive(classified.Message)) + if message == "" { + message = strings.TrimSpace(classified.Code) + } + if message == "" { + message = "request failed" + } + return message +} + +func genericUpstreamMessage(classified Classified) string { + switch classified.Kind { + case "quota": + return "upstream quota exhausted" + case "rate_limit": + if classified.Code == "upstream_queued" { + return "upstream queue is full; retry later" + } + return "upstream rate limit exceeded" + case "auth": + return "upstream authentication failed" + case "invalid_request": + return "upstream rejected the request" + case "model_not_available": + return "model is not available for this account" + case "not_ready": + return "upstream is not ready" + case "canceled": + return "request canceled" + } + switch { + case classified.Status == http.StatusGatewayTimeout: + return "upstream timed out" + case classified.Status == http.StatusTooManyRequests: + return "upstream rate limit exceeded" + case classified.Status >= 500 || classified.Status == 0: + return "upstream service error" + default: + return "upstream request failed" + } +} + +// RedactSensitive removes common credential shapes from a message that is +// safe to show a client. It is deliberately conservative for upstream bodies: +// those use genericUpstreamMessage instead of relying on pattern matching. +func RedactSensitive(message string) string { + for _, pattern := range sensitivePatterns { + message = pattern.ReplaceAllString(message, "[redacted]") + } + return message +} diff --git a/internal/executor/public_error_test.go b/internal/executor/public_error_test.go new file mode 100644 index 000000000..926699b2a --- /dev/null +++ b/internal/executor/public_error_test.go @@ -0,0 +1,35 @@ +package executor + +import ( + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func TestPublicErrorMessageDoesNotRelayUpstreamBody(t *testing.T) { + const marker = "SENSITIVE_MARKER_123" + classified := ClassifyError(&providers.Error{ + Kind: accounts.KindUnavailable, + Status: 502, + Message: "workbuddy rejected: " + marker + " Authorization: Bearer abcdefghijklmnop", + }) + public := PublicErrorMessage(classified) + if strings.Contains(public, marker) { + t.Fatalf("upstream body leaked to the public message: %q", public) + } + if strings.Contains(public, "Bearer") { + t.Fatalf("credential shape leaked to the public message: %q", public) + } + if public != "upstream service error" { + t.Fatalf("public message = %q", public) + } +} + +func TestRedactSensitiveCleansValidationText(t *testing.T) { + message := RedactSensitive("bad key sk-abcdefghijklmnopqrstuvw and url https://x.test/?token=secretvalue") + if strings.Contains(message, "sk-abcdefghijklmnopqrstuvw") || strings.Contains(message, "secretvalue") { + t.Fatalf("redaction missed a credential: %q", message) + } +} diff --git a/internal/executor/route_integration_regression_test.go b/internal/executor/route_integration_regression_test.go new file mode 100644 index 000000000..b418edcd6 --- /dev/null +++ b/internal/executor/route_integration_regression_test.go @@ -0,0 +1,360 @@ +package executor + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type routeRegressionHit struct { + endpoint, account, model string + stream bool +} + +// Keep a single wire trace across worker endpoints to verify where each +// dispatch really went and which model was in its request body. +type routeRegressionWire struct { + mu sync.Mutex + hits []routeRegressionHit +} + +func (wire *routeRegressionWire) add(t *testing.T, pool *Pool, item Item, respond func(http.ResponseWriter, routeRegressionHit)) { + t.Helper() + endpoint := item.ID + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/v1/chat/completions" { + t.Errorf("%s received %s %s", endpoint, r.Method, r.URL.Path) + w.WriteHeader(http.StatusBadRequest) + return + } + var body struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("%s decode request: %v", endpoint, err) + w.WriteHeader(http.StatusBadRequest) + return + } + hit := routeRegressionHit{endpoint: endpoint, account: r.Header.Get("X-Qoder-Account"), model: body.Model, stream: body.Stream} + wire.mu.Lock() + wire.hits = append(wire.hits, hit) + wire.mu.Unlock() + if respond != nil { + respond(w, hit) + } else { + routeRegressionOK(w, hit) + } + })) + t.Cleanup(server.Close) + item.URL = server.URL + item.Runtime = "child_process" + pool.Upsert(item) +} + +func routeRegressionDispatchTo(account, model string, stream bool) routeRegressionHit { + return routeRegressionHit{endpoint: account, account: account, model: model, stream: stream} +} + +func (wire *routeRegressionWire) require(t *testing.T, want ...routeRegressionHit) { + t.Helper() + wire.mu.Lock() + defer wire.mu.Unlock() + if !slices.Equal(wire.hits, want) { + t.Fatalf("upstream dispatches = %+v, want %+v", wire.hits, want) + } +} + +func routeRegressionOK(w http.ResponseWriter, hit routeRegressionHit) { + if hit.stream { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"ok"}}]}`+"\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}`) +} + +func routeRegressionLimited(w http.ResponseWriter) { + w.Header().Set("X-Qoder-Error-Kind", accounts.KindRateLimit) + w.Header().Set("Retry-After", "120") + http.Error(w, `{"error":{"message":"too many requests"}}`, http.StatusTooManyRequests) +} + +func routeRegressionPrepare(t *testing.T, executor ChatExecutor, in PrepareInput) PreparedRequest { + t.Helper() + in.Context = t.Context() + in.CrossProviderPool = true + in.SessionHeader = "routing-regression-session" + in.Request.Messages = []translate.ChatMessage{{Role: "user", Content: "test message"}} + if in.Identity.Kind == "" { + in.Identity = auth.ConsoleIdentity() + } + prepared, err := executor.Prepare(in) + if err != nil { + t.Fatalf("prepare %q: %v", in.Request.Model, err) + } + return prepared +} + +func routeRegressionExecute(t *testing.T, executor ChatExecutor, prepared PreparedRequest) (account string, attempts int, err error) { + t.Helper() + if !prepared.Request.Stream { + result, err := executor.ChatNonStreamPrepared(prepared.Context, prepared.Request, prepared.Route) + return result.AccountID, result.AttemptCount, err + } + result, err := executor.ChatStreamProxyPrepared(prepared.Context, prepared.Request, nil, prepared.Route) + if err != nil { + return result.AccountID, result.AttemptCount, err + } + if result.Response == nil || result.Response.Body == nil { + t.Fatal("stream dispatch returned no body") + } + defer result.Response.Body.Close() + body, err := io.ReadAll(result.Response.Body) + if err != nil || !strings.Contains(string(body), "data: [DONE]") { + t.Fatalf("read completed SSE: body=%q err=%v", body, err) + } + executor.FinishStream(prepared.Context, result, nil) + return result.AccountID, result.AttemptCount, nil +} + +func routeRegressionSeedBinding(t *testing.T, executor ChatExecutor, model string, identity auth.Identity, wantAccount string) { + t.Helper() + seed := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: model}, Identity: identity}) + account, attempts, err := routeRegressionExecute(t, executor, seed) + if err != nil || account != wantAccount || attempts != 1 { + t.Fatalf("seed binding: account=%q attempts=%d err=%v; want %q in one attempt", account, attempts, err, wantAccount) + } + if bound, ok := executor.SessionAffinity.Get(seed.Route.SessionKey); !ok || bound != wantAccount { + t.Fatalf("seed did not establish affinity: account=%q exists=%v want=%q", bound, ok, wantAccount) + } +} + +func routeRegressionRequireRateLimit(t *testing.T, err error) { + t.Helper() + var execution *ExecutionError + if !errors.As(err, &execution) || execution.Classified.Kind != accounts.KindRateLimit { + t.Fatalf("execution error = %v, want rate limit", err) + } +} + +func TestPreparedRouteRegressionUnscopedStickyEscape(t *testing.T) { + for _, tc := range []struct { + name string + saturated, stream bool + }{ + {name: "saturated_non_stream", saturated: true}, + {name: "saturated_stream", saturated: true, stream: true}, + {name: "first_failure_non_stream"}, + {name: "first_failure_stream", stream: true}, + } { + t.Run(tc.name, func(t *testing.T) { + const seed, shared = "affinity-seed", "shared-model" + const bound, fallback = "z-bound", "a-fallback" + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: bound, Provider: "workbuddy", Region: "cn", Models: []string{seed, shared}, MaxInFlight: 1}, func(w http.ResponseWriter, hit routeRegressionHit) { + if hit.model == shared { + routeRegressionLimited(w) + return + } + routeRegressionOK(w, hit) + }) + // The fallback sorts first in the ordinary pool, so skipping affinity + // cannot accidentally exercise the same first-failure path. + wire.add(t, pool, Item{ID: fallback, Provider: "qoder", Region: "global", Models: []string{shared}}, nil) + executor := NewChatExecutor(pool, "") + routeRegressionSeedBinding(t, executor, seed, auth.ConsoleIdentity(), bound) + want := []routeRegressionHit{routeRegressionDispatchTo(bound, seed, false)} + if tc.saturated { + if !pool.Acquire(bound) { + t.Fatal("occupy bound account slot") + } + defer pool.Release(bound) + } else { + want = append(want, routeRegressionDispatchTo(bound, shared, tc.stream)) + } + want = append(want, routeRegressionDispatchTo(fallback, shared, tc.stream)) + + prepared := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: shared, Stream: tc.stream}}) + account, attempts, err := routeRegressionExecute(t, executor, prepared) + if err != nil || account != fallback || attempts != len(want)-1 { + t.Errorf("dispatch: account=%q attempts=%d err=%v; want fallback in %d upstream attempt(s)", account, attempts, err, len(want)-1) + } + wire.require(t, want...) + if id, ok := executor.SessionAffinity.Peek(prepared.Route.SessionKey); !ok || id != fallback { + t.Fatalf("affinity after failover = %q, exists=%v; want %q", id, ok, fallback) + } + }) + } +} + +func TestPreparedRouteRegressionHardRegionSurvivesStickyEscape(t *testing.T) { + for _, constraint := range []string{"prefix", "grant"} { + for _, failure := range []string{"saturated", "first_failure"} { + t.Run(constraint+"/"+failure, func(t *testing.T) { + const seed, shared = "affinity-seed", "shared-model" + const global, cn, cnBackup = "a-global", "b-cn", "c-cn" + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: global, Provider: "qoder", Region: "global", Models: []string{seed, shared}}, nil) + limited := func(w http.ResponseWriter, _ routeRegressionHit) { + routeRegressionLimited(w) + } + wire.add(t, pool, Item{ID: cn, Provider: "qoder", Region: "cn", Models: []string{shared}, MaxInFlight: 1}, limited) + executor := NewChatExecutor(pool, "") + var seedIdentity, identity auth.Identity + model := "qoder-cn/" + shared + if constraint == "grant" { + // Tightening the grants keeps the identity and session cache key. + seedIdentity = auth.KeyIdentity(accounts.APIKey{ID: "same-key", Providers: []string{"qoder"}}) + identity = auth.KeyIdentity(accounts.APIKey{ID: "same-key", Providers: []string{"qoder:cn"}}) + model = shared + } + routeRegressionSeedBinding(t, executor, "qoder-gl/"+seed, seedIdentity, global) + want := []routeRegressionHit{routeRegressionDispatchTo(global, seed, false)} + stream := failure == "first_failure" + if stream { + // Another authorized CN account forces a genuine retry. The + // healthy global account must be skipped even though it sorts first. + wire.add(t, pool, Item{ID: cnBackup, Provider: "qoder", Region: "cn", Models: []string{shared}}, limited) + want = append(want, routeRegressionDispatchTo(cn, shared, true), routeRegressionDispatchTo(cnBackup, shared, true)) + } else { + if !pool.Acquire(cn) { + t.Fatal("occupy cn account slot") + } + defer pool.Release(cn) + } + + prepared := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: model, Stream: stream}, Identity: identity}) + _, attempts, err := routeRegressionExecute(t, executor, prepared) + wire.require(t, want...) + routeRegressionRequireRateLimit(t, err) + if attempts != len(want)-1 { + t.Fatalf("attempts = %d, want %d", attempts, len(want)-1) + } + }) + } + } +} + +func TestPreparedRouteRegressionSendsHealthyMemberOnSameAccount(t *testing.T) { + for _, tc := range []struct { + name string + preCool, stream bool + }{ + {name: "member_a_already_cooling", preCool: true, stream: true}, + {name: "member_a_fails_this_attempt"}, + } { + t.Run(tc.name, func(t *testing.T) { + const realID, a, b, logical = "shared-account", "member-a", "member-b", "pooled-model" + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: realID, Provider: "qoder", Region: "cn", Models: []string{a, b}}, func(w http.ResponseWriter, hit routeRegressionHit) { + if hit.model == a { + routeRegressionLimited(w) + return + } + routeRegressionOK(w, hit) + }) + executor := NewChatExecutor(pool, "") + var before time.Time + wantAttempts := 2 + if tc.preCool { + first := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: "qoder-cn/" + a}}) + _, _, err := routeRegressionExecute(t, executor, first) + routeRegressionRequireRateLimit(t, err) + item, _ := pool.ByID(realID) + before = item.ModelDownUntil[a] + if !time.Now().Before(before) { + t.Fatal("the upstream 429 did not put member A on cooldown") + } + wantAttempts = 1 + } + + resolver := &aggResolverStub{agg: accounts.Aggregation{ + ID: logical, Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 2, + Members: []accounts.AggregationMember{ + {Provider: "qoder", Region: "cn", AccountID: realID, Model: a, Priority: 0}, + {Provider: "qoder", Region: "cn", AccountID: realID, Model: b, Priority: 1}, + }, + }} + prepared := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: logical, Stream: tc.stream}, Aggregations: resolver}) + account, attempts, err := routeRegressionExecute(t, executor, prepared) + if err != nil || account != realID || attempts != wantAttempts { + t.Errorf("dispatch: account=%q attempts=%d err=%v; want %q in %d upstream attempt(s)", account, attempts, err, realID, wantAttempts) + } + wire.require(t, routeRegressionDispatchTo(realID, a, false), routeRegressionDispatchTo(realID, b, tc.stream)) + after, _ := pool.ByID(realID) + if !time.Now().Before(after.ModelDownUntil[a]) || (tc.preCool && !after.ModelDownUntil[a].Equal(before)) { + t.Fatalf("success on member B lost or changed member A cooldown: %v -> %v", before, after.ModelDownUntil[a]) + } + }) + } +} + +func TestPreparedRouteRegressionWorkerLabelDoesNotOwnFeedback(t *testing.T) { + for _, mode := range []string{"non_stream", "stream"} { + t.Run(mode, func(t *testing.T) { + const realID, displayID, concrete, otherModel, logical = "actual-pool-id", "reported-label", "real-member", "other-model", "pooled-model" + var wire routeRegressionWire + pool := NewPool(nil, nil) + wire.add(t, pool, Item{ID: realID, Provider: "qoder", Region: "cn", Models: []string{concrete, otherModel}}, func(w http.ResponseWriter, hit routeRegressionHit) { + if hit.model == concrete { + w.Header().Set("X-Qoder-Account", displayID) + routeRegressionLimited(w) + return + } + routeRegressionOK(w, hit) + }) + // A displayed label can happen to match a different pool ID. + wire.add(t, pool, Item{ID: displayID, Provider: "qoder", Region: "cn", Models: []string{concrete}}, nil) + executor := NewChatExecutor(pool, "") + var recorded []accounts.RequestAttempt + executor.OnAttempt = func(attempt accounts.RequestAttempt) { recorded = append(recorded, attempt) } + resolver := &aggResolverStub{agg: accounts.Aggregation{ + ID: logical, Enabled: true, Strategy: accounts.AggregationPriority, + Members: []accounts.AggregationMember{{Provider: "qoder", Region: "cn", AccountID: realID, Model: concrete}}, + }} + stream := mode == "stream" + prepared := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: logical, Stream: stream}, Aggregations: resolver}) + _, attempts, err := routeRegressionExecute(t, executor, prepared) + routeRegressionRequireRateLimit(t, err) + if attempts != 1 { + t.Errorf("attempts = %d, want 1", attempts) + } + wire.require(t, routeRegressionDispatchTo(realID, concrete, stream)) + actual, _ := pool.ByID(realID) + decoy, _ := pool.ByID(displayID) + if !time.Now().Before(actual.ModelDownUntil[concrete]) || len(actual.ModelDownUntil) != 1 || !actual.DownUntil.IsZero() { + t.Errorf("actual account cooldowns = %v, account-wide=%v; want cooldown only on %q, not virtual %q", actual.ModelDownUntil, actual.DownUntil, concrete, logical) + } + if len(decoy.ModelDownUntil) != 0 || !decoy.DownUntil.IsZero() { + t.Errorf("worker label pool account was cooled: models=%v account-wide=%v", decoy.ModelDownUntil, decoy.DownUntil) + } + if len(recorded) != 1 || recorded[0].AccountID != realID || recorded[0].ErrorKind != accounts.KindRateLimit { + t.Errorf("recorded feedback = %+v; want one rate-limit attempt on %q", recorded, realID) + } + + // Model-local failure must not take the actual account offline. + next := routeRegressionPrepare(t, executor, PrepareInput{Request: translate.ChatRequest{Model: "qoder-cn/" + otherModel}}) + account, _, err := routeRegressionExecute(t, executor, next) + if err != nil || account != realID { + t.Errorf("different model: account=%q err=%v, want %q", account, err, realID) + } + wire.require(t, routeRegressionDispatchTo(realID, concrete, stream), routeRegressionDispatchTo(realID, otherModel, false)) + }) + } +} diff --git a/internal/executor/route_refactor_test.go b/internal/executor/route_refactor_test.go new file mode 100644 index 000000000..0421ec19d --- /dev/null +++ b/internal/executor/route_refactor_test.go @@ -0,0 +1,143 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func TestConcurrentDispatchUsesFirstAttemptWhenPreferredSlotIsTaken(t *testing.T) { + entered, release := make(chan struct{}, 1), make(chan struct{}) + a := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + entered <- struct{}{} + select { + case <-release: + case <-r.Context().Done(): + } + _, _ = io.WriteString(w, `{"choices":[{"message":{"content":"a"}}]}`) + })) + defer a.Close() + b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("X-Qoder-Account"); got != "b" { + t.Errorf("worker header=%q, want actual selected account b", got) + } + _, _ = io.WriteString(w, `{"choices":[{"message":{"content":"b"}}]}`) + })) + defer b.Close() + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + defer unblock() + p := NewPool([]string{a.URL, b.URL}, []string{"a", "b"}) + for _, id := range []string{"a", "b"} { + item, _ := p.ByID(id) + item.MaxInFlight = 1 + p.Upsert(item) + } + e := NewChatExecutor(p, "") + e.MaxAttempts = 1 + attempts := make(chan accounts.RequestAttempt, 2) + e.OnAttempt = func(a accounts.RequestAttempt) { attempts <- a } + req := translate.ChatRequest{Model: "shared"} + route := RouteInput{PublicModel: "shared", Prefer: "a", RequestID: "attempt-a"} + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + first := make(chan error, 1) + go func(route RouteInput) { _, err := e.ChatNonStreamPrepared(ctx, req, route); first <- err }(route) + select { + case <-entered: + case <-ctx.Done(): + t.Fatal("the first request did not take the slot") + } + route.RequestID = "attempt-b" + result, err := e.ChatNonStreamPrepared(ctx, req, route) + if err != nil || result.PoolAccountID != "b" || result.AttemptCount != 1 { + t.Fatalf("second dispatch = %+v, %v", result, err) + } + select { + case attempt := <-attempts: + if attempt.RequestID != "attempt-b" || attempt.AccountID != "b" || attempt.AttemptIndex != 0 { + t.Fatalf("dispatch attempt = %+v, want first attempt on b", attempt) + } + default: + t.Fatal("second request did not record its single attempt") + } + amb, _ := p.ByID("a") + free, _ := p.ByID("b") + if amb.InFlight != 1 || free.InFlight != 0 || amb.LastError != "" || len(amb.ModelDownUntil) != 0 { + t.Fatalf("contention polluted accounts: a=%+v b=%+v", amb, free) + } + unblock() + if err := <-first; err != nil { + t.Fatal(err) + } +} + +func TestStreamCompletionPreservesNewerBindingAndCooldown(t *testing.T) { + for _, oldFails := range []bool{false, true} { + name := "old-success" + if oldFails { + name = "old-failure" + } + t.Run(name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"ok"}}]}`+"\n\n") + if oldFails == (r.Header.Get("X-Request-Id") == "older") { + _, _ = io.WriteString(w, `data: {"error":{"status":429,"message":"slow down"}}`+"\n\n") + } else { + _, _ = io.WriteString(w, "data: [DONE]\n\n") + } + })) + defer server.Close() + p := NewPool(nil, nil) + p.Upsert(Item{ID: "a", URL: server.URL, Provider: "qoder", MaxInFlight: 2, Models: []string{"model"}}) + e := NewChatExecutor(p, "") + req := translate.ChatRequest{Model: "model", Stream: true} + route := RouteInput{SessionKey: "shared-session", RouteModel: req.Model, RequestID: "older"} + older, err := e.ChatStreamProxyPrepared(t.Context(), req, nil, route) + if err != nil { + t.Fatal(err) + } + defer older.Response.Body.Close() + route.RequestID = "newer" + newer, err := e.ChatStreamProxyPrepared(t.Context(), req, nil, route) + if err != nil || newer.Routing != routingSticky { + t.Fatalf("newer stream = %+v, err=%v", newer, err) + } + defer newer.Response.Body.Close() + finish := func(result StreamResult) { + t.Helper() + body, err := io.ReadAll(result.Response.Body) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(body), "\n") { + if payload, ok := strings.CutPrefix(line, "data: "); ok && strings.Contains(payload, `"error"`) { + err = ClassifyUpstreamBody(0, payload) + break + } + } + e.FinishStream(t.Context(), result, err) + result.Response.Body.Close() + } + finish(newer) + finish(older) + account, _ := p.ByID("a") + if account.ModelDownUntil["model"].IsZero() || account.InFlight != 0 { + t.Fatalf("parallel completion lost the failure or slot: %+v", account) + } + bound, ok := e.SessionAffinity.Peek(route.SessionKey) + if ok != oldFails || (ok && bound != "a") { + t.Fatalf("binding=%q, found=%v, newer stream succeeds=%v", bound, ok, oldFails) + } + }) + } +} diff --git a/internal/executor/routing.go b/internal/executor/routing.go new file mode 100644 index 000000000..877035c9e --- /dev/null +++ b/internal/executor/routing.go @@ -0,0 +1,418 @@ +package executor + +import ( + "context" + "fmt" + "net/http" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/toolcall" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// dispatchTarget describes one reserved attempt. It is built from the exact +// account snapshot and member returned by the pool, never from response +// headers or a later view of the pool/catalog. +type dispatchTarget struct { + item Item + memberModel string + upstreamModel string + cooldownKey string + aggregateFEFO bool + // These flags describe a locked recheck of a planned session preference. + staleAffinityModel bool + widenedAffinityScope bool +} + +func targetFor(item Item, model string) dispatchTarget { + accountModel := AccountModelID(item, model) + return dispatchTarget{ + item: item, memberModel: model, upstreamModel: NativeModelID(item, accountModel), + cooldownKey: routeModel(accountModel), + } +} + +func (t dispatchTarget) request(req translate.ChatRequest) translate.ChatRequest { + req.Model = t.upstreamModel + return sanitizeChatForItem(t.item, req) +} + +func (t dispatchTarget) provider() string { return itemProvider(t.item) } + +// routeLoop holds request-local scheduling state. hard is never changed by +// affinity or by failover; working may narrow it but can only widen to hard. +type routeLoop struct { + requestID string + plan *AggregatePlan + hard RouteQuery + working RouteQuery + routing routingPlan + sticky bool + implicitRegion bool + legacyWorkerLabel string + affinityEscape string + missingBinding uint64 + attempts int + index int + lastErr error + lastTarget dispatchTarget + lastLabel string +} + +// routeScope returns only hard constraints and a provisional affinity hint. +// Even executions look up affinity read-only here: a miss at the pool must +// not mutate the session cache. Probe callers never commit the hint. +func (e ChatExecutor) routeScope(route RouteInput, model string, eligible func(Item) bool) routeLoop { + if route.RouteModel != "" { + model = route.RouteModel + } + if route.RequireModelAlias { + protocolEligible := eligible + eligible = func(item Item) bool { + return definesModelAlias(item, model) && (protocolEligible == nil || protocolEligible(item)) + } + } + provider := strings.TrimSpace(route.ProviderFilter) + if provider != "" { + provider = NormalizeProviderFamily(provider) + } + region := strings.TrimSpace(route.RegionFilter) + if region != "" { + region = NormalizeRegion(region) + } else if granted, ok := keyGrantedSingleRegion(provider, route.AllowedProviders); ok { + region = granted + } + q := e.routeQuery("", provider, region, model, route.AllowedProviders, make(map[string]struct{}), eligible, route.AggregatePlan) + if route.AggregatePlan != nil { + q.ExcludedModels = make(map[routeModelKey]struct{}) + } + l := routeLoop{requestID: route.RequestID, plan: route.AggregatePlan, hard: q, working: q, routing: routingPlan{Source: routingPool, SessionKey: strings.TrimSpace(route.SessionKey), PublicModel: model}} + if prefer := strings.TrimSpace(route.Prefer); prefer != "" { + l.routing.Source = routingPin + l.routing.SessionKey = "" + pinned, found := e.Pool.ByID(prefer) + if found && matchesRouteScope(pinned, q) && (l.plan == nil || l.plan.CanServeAccount(pinned)) { + l.working.PreferAccount = prefer + if l.plan == nil && region == "" { + l.hard.RegionFilter = itemRegion(pinned) + l.working.RegionFilter = l.hard.RegionFilter + } + } else if !found && l.plan == nil && provider == "" && region == "" && len(q.AllowedProviders) == 0 { + // Narrow compatibility for a legacy Qoder label not registered in + // the pool; never forward a known, out-of-scope account ID. + l.legacyWorkerLabel = prefer + } else if l.plan != nil { + l.routing.Source = routingPool + } + return l + } + accountID, version, ok := e.SessionAffinity.peekVersion(l.routing.SessionKey) + if !ok { + return l + } + item, found := e.Pool.ByID(accountID) + switch { + case !found: + l.affinityEscape, l.missingBinding = "account_missing", version + case q.ProviderFilter != "" && itemProvider(item) != q.ProviderFilter: + l.affinityEscape = "provider_mismatch" + case q.RegionFilter != "" && itemRegion(item) != q.RegionFilter: + l.affinityEscape = "region_mismatch" + case !accounts.ProviderRegionAllowed(itemProvider(item), itemRegion(item), q.AllowedProviders): + l.affinityEscape = "provider_not_allowed" + case eligible != nil && !eligible(item): + l.affinityEscape = "protocol_unavailable" + case l.plan != nil && !l.plan.CanServeAccount(item), l.plan == nil && !stickyAccountCanServeModel(item, model): + l.affinityEscape = "model_unavailable" + default: + l.working.PreferAccount = accountID + l.routing.Source, l.routing.BoundAccount = routingSticky, accountID + l.routing.BoundVersion = version + if l.plan == nil { + l.working.preferAffinity = true + l.working.ProviderFilter, l.working.RegionFilter = itemProvider(item), itemRegion(item) + l.sticky = l.working.ProviderFilter != l.hard.ProviderFilter || l.working.RegionFilter != l.hard.RegionFilter + } + } + return l +} + +func matchesRouteScope(item Item, q RouteQuery) bool { + return (q.ProviderFilter == "" || q.ProviderFilter == itemProvider(item)) && + (q.RegionFilter == "" || q.RegionFilter == itemRegion(item)) && + accounts.ProviderRegionAllowed(itemProvider(item), itemRegion(item), q.AllowedProviders) && + (q.Eligible == nil || q.Eligible(item)) +} + +func (e ChatExecutor) newRouteLoop(route RouteInput, model string, eligible func(Item) bool) routeLoop { + tooling := route.Tooling + originalEligible := eligible + if tooling.HasTools() { + previous := eligible + eligible = func(item Item) bool { + if previous != nil && !previous(item) { + return false + } + return e.itemSupportsTooling(item, routeModel(model), tooling) + } + } + l := e.routeScope(route, model, eligible) + if l.plan == nil { + l.attempts = e.attemptsFor(l.hard.ProviderFilter, l.hard.RegionFilter, l.hard.PublicModel, l.hard.AllowedProviders, l.hard.Eligible) + } else if !l.plan.AllowFallbacks || l.plan.MaxAttempts < 1 { + l.attempts = 1 + } else { + l.attempts = l.plan.MaxAttempts + } + if tooling.HasTools() && !e.routeAvailable(l) { + base := route + base.Tooling = toolcall.Request{} + baseLoop := e.routeScope(base, model, originalEligible) + if e.routeAvailable(baseLoop) { + l.lastErr = toolCapabilityError(baseLoop.hard.ProviderFilter, model, tooling) + l.attempts = 0 + } + } + return l +} + +func (e ChatExecutor) routeAvailable(l routeLoop) bool { + if e.Pool == nil { + return false + } + if l.plan != nil { + return e.Pool.HasAggregateRoute(l.plan, l.hard) + } + return e.Pool.HasRoute(l.hard) +} + +// pickNextReserved is the sole commit point for an attempt. A saturated +// candidate is never picked, and a cooldown hint is never given a slot. +func (l *routeLoop) pickNextReserved(e ChatExecutor) (dispatchTarget, int, error) { + var hardScope *RouteQuery + if l.index == 0 && l.sticky && l.working.preferAffinity { + hardScope = &l.hard + } + target, err := e.reserveTargetWithFallback(l.requestID, l.working, l.plan, hardScope) + // A bare cross-provider request can leave its sticky scope after a real + // upstream failure. A provider-scoped route keeps the usual region pin + // on upstream failure. The pool has already handled a stale model; a + // pre-dispatch capacity miss may also drop a valid but contended pin. + if err != nil && l.sticky && ((l.index == 0 && !target.staleAffinityModel && capacityError(err)) || (l.index > 0 && l.hard.ProviderFilter == "")) { + // Try the wider, authorized route directly rather than check capacity + // in a different snapshot. Commit the escape only if it took a slot. + if alternate, wideErr := e.reserveTarget(l.requestID, l.hard, l.plan); wideErr == nil { + if l.index == 0 { + l.routing.Source = routingPool + l.affinityEscape = "concurrency_saturated" + } + l.working, l.sticky = l.hard, false + target, err = alternate, nil + } + } + if err != nil { + return dispatchTarget{}, l.index, err + } + if target.widenedAffinityScope { + l.working, l.sticky = l.hard, false + } + if target.staleAffinityModel && target.item.ID != l.routing.BoundAccount { + l.routing.Source = routingStickyEscape + l.affinityEscape = "model_unavailable" + } + if l.index == 0 && l.routing.SessionKey != "" && e.SessionAffinity != nil { + e.SessionAffinity.Get(l.routing.SessionKey) // commit hit/miss and LRU only after reservation + if l.affinityEscape != "" { + e.SessionAffinity.RecordEscape(l.affinityEscape) + } + if l.missingBinding != 0 { + e.SessionAffinity.forgetVersion(l.routing.SessionKey, l.missingBinding) + } + } + e.observeRouting(&l.routing, target.item.ID) + l.working.PreferAccount = "" + l.working.preferAffinity = false + if l.plan == nil && l.working.RegionFilter == "" { + l.working.RegionFilter = itemRegion(target.item) + l.implicitRegion = true + } + index := l.index + l.index++ + if e.OnInFlightAcquire != nil && l.requestID != "" { + e.OnInFlightAcquire(l.requestID, target.item.ID) + } + return target, index, nil +} + +func (l *routeLoop) failover(e ChatExecutor, target dispatchTarget, label string, classified Classified, err error) bool { + l.lastTarget, l.lastLabel, l.lastErr = target, label, err + if !classified.Failover { + return false + } + if l.plan != nil { + l.hard.ExcludedModels[accountRouteModelKey(target.item, target.memberModel)] = struct{}{} + } else { + l.hard.Excluded[target.item.ID] = struct{}{} + if l.implicitRegion && l.hard.ProviderFilter == "" { + l.working.RegionFilter = l.hard.RegionFilter + l.implicitRegion = false + } + } + if target.item.ID == l.routing.BoundAccount { + e.SessionAffinity.forgetVersion(l.routing.SessionKey, l.routing.BoundVersion) + } + return l.index < l.attempts +} + +func (l routeLoop) headerAccount(target dispatchTarget, attempt int) string { + if attempt == 0 && l.legacyWorkerLabel != "" && target.provider() == "qoder" { + return l.legacyWorkerLabel + } + return target.item.ID +} + +func (l routeLoop) chatError(err error) (ChatResult, error) { + if l.lastErr != nil { + return ChatResult{AttemptCount: l.index, AccountID: l.lastLabel, PoolAccountID: l.lastTarget.item.ID, Provider: l.lastTarget.provider(), CooldownModel: l.lastTarget.cooldownKey, AggregateFEFO: l.lastTarget.aggregateFEFO}, l.lastErr + } + return ChatResult{}, err +} + +func (l routeLoop) streamError(err error) (StreamResult, error) { + if l.lastErr != nil { + return StreamResult{AttemptCount: l.index, AccountID: l.lastLabel, PoolAccountID: l.lastTarget.item.ID, Provider: l.lastTarget.provider(), CooldownModel: l.lastTarget.cooldownKey, AggregateFEFO: l.lastTarget.aggregateFEFO}, l.lastErr + } + return StreamResult{}, err +} + +func (e ChatExecutor) nativeResponsesEligible(item Item) bool { + adapter, ok := e.Providers.Get(itemProvider(item)) + return ok && adapter.NativeResponses != nil +} + +func (e ChatExecutor) HasNativeResponsesRoute(ctx context.Context, req translate.ChatRequest, prefer, providerFilter string) bool { + return e.HasNativeResponsesRoutePrepared(ctx, req, routeInputFromContext(ctx, req, prefer, providerFilter)) +} + +// HasNativeResponsesRoutePrepared is a capability probe, not a dispatch +// attempt. Temporarily busy or cooling accounts still advertise capability. +func (e ChatExecutor) HasNativeResponsesRoutePrepared(_ context.Context, req translate.ChatRequest, route RouteInput) bool { + if e.Pool == nil || e.Providers == nil { + return false + } + l := e.routeScope(route, req.Model, e.nativeResponsesEligible) + if l.plan != nil { + return e.Pool.HasAggregateRoute(l.plan, l.hard) + } + return e.Pool.HasRoute(l.hard) +} + +// dispatchContext carries only adapter/logging metadata. Routing decisions +// consume RouteInput directly, not values written back onto the context. +func dispatchContext(ctx context.Context, route RouteInput) context.Context { + if ctx == nil { + ctx = context.Background() + } + return WithConversation(context.WithValue(ctx, requestIDKey{}, route.RequestID), route.SessionKey) +} + +func capacityPickError() error { + return NewExecutionError(Classified{ + Kind: accounts.KindRateLimit, Status: http.StatusTooManyRequests, Code: "rate_limit", + Type: "api_error", Message: "all accounts at capacity", + Cooldown: 5 * time.Second, RetryAfter: 5 * time.Second, Failover: true, + }, nil) +} + +func (e ChatExecutor) reserveTarget(requestID string, query RouteQuery, plan *AggregatePlan) (dispatchTarget, error) { + return e.reserveTargetWithFallback(requestID, query, plan, nil) +} + +func (e ChatExecutor) reserveTargetWithFallback(requestID string, query RouteQuery, plan *AggregatePlan, hardScope *RouteQuery) (dispatchTarget, error) { + if e.Pool != nil { + if plan != nil { + pick := e.Pool.selectAggregate(plan, query, true) + switch { + case pick.Available: + target := targetFor(pick.Item, pick.Member.Model) + target.aggregateFEFO = pick.FEFO + return target, nil + case pick.Item.ID != "": + return dispatchTarget{}, coolingPickError(pick.Item, query.PublicModel, cooldownModel(pick.Item, pick.Member.Model), pick.RetryAfter) + case pick.Saturated: + return dispatchTarget{}, capacityPickError() + case pick.QuotaBlocked: + return dispatchTarget{}, quotaPickError(query.PublicModel) + case pick.Scoped && !pick.HasRoute && routeModel(query.PublicModel) != "": + return dispatchTarget{}, e.modelPickError(requestID, query) + } + } else { + pick := e.Pool.selectRoute(query, true, hardScope) + if pick.reserved { + target := targetFor(pick.item, query.PublicModel) + target.staleAffinityModel, target.widenedAffinityScope = pick.staleAffinityModel, pick.widened + return target, nil + } + if pick.found { + retryAfter := max(e.Pool.RetryAfter(pick.item, query.PublicModel), time.Millisecond) + return dispatchTarget{}, coolingPickError(pick.item, query.PublicModel, cooldownModel(pick.item, query.PublicModel), retryAfter) + } + if pick.saturated { + return dispatchTarget{staleAffinityModel: pick.staleAffinityModel}, capacityPickError() + } + if _, ok := e.Pool.QuotaBlockedForModel(query); ok { + return dispatchTarget{}, quotaPickError(query.PublicModel) + } + if routeModel(query.PublicModel) != "" { + unfiltered := query + unfiltered.PublicModel = "" + if e.Pool.LenRoute(unfiltered) > 0 { + return dispatchTarget{}, e.modelPickError(requestID, query) + } + } + } + } + provider, region, allowed := query.ProviderFilter, query.RegionFilter, query.AllowedProviders + if len(allowed) > 0 && provider != "" && !accounts.ProviderAllowed(provider, allowed) { + return dispatchTarget{}, NewExecutionError(Classified{ + Kind: accounts.KindAuth, Status: http.StatusForbidden, Code: "provider_not_allowed", + Type: "permission_error", Message: fmt.Sprintf("api key cannot use provider %s", provider), + }, nil) + } + if provider != "" { + if region == "" { + region, _ = keyGrantedSingleRegion(provider, allowed) + } + if region != "" { + return dispatchTarget{}, noAccountsError(fmt.Sprintf("no %s/%s accounts available", provider, region)) + } + return dispatchTarget{}, noAccountsError(fmt.Sprintf("no %s accounts available", provider)) + } + if len(allowed) > 0 { + return dispatchTarget{}, noAccountsError("no accounts available for this api key") + } + return dispatchTarget{}, NewExecutionError(Classified{ + Kind: accounts.KindUnavailable, Status: http.StatusServiceUnavailable, + Code: "no_accounts_configured", Type: "api_error", Message: "no worker accounts configured", + }, nil) +} + +func quotaPickError(model string) error { + retryAfter := NextLocalMidnightCooldown() + return NewExecutionError(Classified{ + Kind: accounts.KindQuota, Status: http.StatusTooManyRequests, Code: "insufficient_quota", + Type: "insufficient_quota", Cooldown: retryAfter, RetryAfter: retryAfter, + Message: quotaBlockedMessage(model), + }, nil) +} + +func (e ChatExecutor) modelPickError(requestID string, query RouteQuery) error { + e.logModelRouteMiss(requestID, query) + return NewExecutionError(Classified{ + Kind: accounts.KindModelNotAvailable, Status: http.StatusBadRequest, + Code: "model_not_available", Type: "invalid_request_error", + Message: fmt.Sprintf("model_not_available: %s is not available for the selected accounts", query.PublicModel), + }, nil) +} diff --git a/internal/executor/routing_tooling_test.go b/internal/executor/routing_tooling_test.go new file mode 100644 index 000000000..82401ff36 --- /dev/null +++ b/internal/executor/routing_tooling_test.go @@ -0,0 +1,177 @@ +package executor + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/toolcall" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func strictToolingRequest(t *testing.T) toolcall.Request { + t.Helper() + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]},"strict":true}}]`), json.RawMessage(`"required"`), boolPointer(false), toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + +func TestToolingCapabilityMatrixAcrossAllProviders(t *testing.T) { + type expectation struct { + choices []toolcall.ChoiceMode + parallelOff bool + strict bool + } + // This table is deliberately independent of providers.ToolProfileFor: it is + // the routing contract the adapters are expected to satisfy, not a copy of + // whatever the profile currently returns. + want := map[string]expectation{ + "qoder": {allChoicesForTest(), true, true}, + "workbuddy": {allChoicesForTest(), false, false}, + "trae": {allChoicesForTest(), false, false}, + "devin": {allChoicesForTest(), false, false}, + "command": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto}, false, false}, + "codex": {allChoicesForTest(), false, false}, + "meta": {allChoicesForTest(), false, false}, + "zhipu": {allChoicesForTest(), false, true}, + "kimi": {allChoicesForTest(), false, true}, + "codearts": {allChoicesForTest(), false, true}, + "qwenwork": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "kiro": {[]toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone}, false, false}, + "doubaowork": {allChoicesForTest(), false, false}, + "minimaxcode": {allChoicesForTest(), false, false}, + "opencode": {allChoicesForTest(), false, false}, + } + tools := map[bool]json.RawMessage{ + false: json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}}]`), + true: json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]},"strict":true}}]`), + } + choices := map[toolcall.ChoiceMode]json.RawMessage{ + toolcall.ChoiceUnspecified: nil, + toolcall.ChoiceAuto: json.RawMessage(`"auto"`), + toolcall.ChoiceNone: json.RawMessage(`"none"`), + toolcall.ChoiceRequired: json.RawMessage(`"required"`), + toolcall.ChoiceNamed: json.RawMessage(`{"type":"function","function":{"name":"run"}}`), + } + for _, provider := range []string{"qoder", "workbuddy", "trae", "devin", "command", "codex", "meta", "zhipu", "kimi", "codearts", "qwenwork", "kiro", "doubaowork", "minimaxcode", "opencode"} { + expected, ok := want[provider] + if !ok { + t.Fatalf("missing independent contract for %s", provider) + } + for mode, choice := range choices { + for _, parallel := range []*bool{nil, boolPointer(true), boolPointer(false)} { + for _, strict := range []bool{false, true} { + request, err := canonicalTooling(translate.ChatRequest{Tools: tools[strict], ToolChoice: choice, ParallelToolCalls: parallel}, nil) + if err != nil { + t.Fatalf("%s/%s/%v/%v parse: %v", provider, mode, parallel, strict, err) + } + choiceOK := mode == toolcall.ChoiceUnspecified + for _, supported := range expected.choices { + choiceOK = choiceOK || supported == mode + } + wantOK := choiceOK && + (parallel == nil || *parallel || expected.parallelOff) && + (!strict || expected.strict) + item := Item{Provider: provider} + if got := (ChatExecutor{}).itemSupportsTooling(item, "m", request); got != wantOK { + t.Fatalf("%s choice=%s parallel=%v strict=%v got=%v want=%v expected=%+v", provider, mode, parallel, strict, got, wantOK, expected) + } + } + } + } + } +} + +func allChoicesForTest() []toolcall.ChoiceMode { + return []toolcall.ChoiceMode{toolcall.ChoiceAuto, toolcall.ChoiceNone, toolcall.ChoiceRequired, toolcall.ChoiceNamed} +} + +func TestModelCatalogToolCapabilityFiltersRouting(t *testing.T) { + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object"}}}]`), nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + e := ChatExecutor{} + withTools := Item{Provider: "qoder", NoToolsModels: []string{"qoder/text-only"}} + if !e.itemSupportsTooling(withTools, "qoder/chat-model", request) { + t.Fatal("a model without a negative catalog fact must stay fail-open") + } + withoutTools := Item{Provider: "qoder", NoToolsModels: []string{"qoder/text-only"}} + if e.itemSupportsTooling(withoutTools, "qoder/text-only", request) { + t.Fatal("a model whose catalog declares no tools must not be routed with tools") + } +} + +func TestPlainRouteRejectsProviderWithoutToolCapability(t *testing.T) { + e := ChatExecutor{Pool: aggTestPool()} + loop := e.newRouteLoop(RouteInput{ProviderFilter: "workbuddy", Tooling: strictToolingRequest(t)}, "model-b", nil) + if loop.lastErr == nil || loop.attempts != 0 { + t.Fatalf("loop = attempts:%d lastErr:%v", loop.attempts, loop.lastErr) + } + if !strings.Contains(loop.lastErr.Error(), "cannot enforce") { + t.Fatalf("tool capability error = %v", loop.lastErr) + } + if _, _, err := loop.pickNextReserved(e); err == nil { + t.Fatal("a rejected tool request must not reserve an account") + } +} + +func TestPlainRoutePicksProviderThatSupportsToolPolicy(t *testing.T) { + e := ChatExecutor{Pool: aggTestPool()} + loop := e.newRouteLoop(RouteInput{ProviderFilter: "qoder", Tooling: strictToolingRequest(t)}, "model-a", nil) + if loop.lastErr != nil || loop.attempts != 1 { + t.Fatalf("loop = attempts:%d lastErr:%v", loop.attempts, loop.lastErr) + } + target, _, err := loop.pickNextReserved(e) + if err != nil { + t.Fatal(err) + } + if target.provider() != "qoder" || target.memberModel != "model-a" { + t.Fatalf("target = %+v", target) + } +} + +func TestAggregateSkipsMembersThatCannotEnforceToolPolicy(t *testing.T) { + e := ChatExecutor{Pool: aggTestPool()} + plan := aggPlan( + accounts.AggregationMember{Provider: "qoder", Model: "model-a", Priority: 0}, + accounts.AggregationMember{Provider: "workbuddy", Model: "model-b", Priority: 1}, + ) + loop := e.newRouteLoop(RouteInput{AggregatePlan: plan, PublicModel: plan.ID, Tooling: strictToolingRequest(t)}, plan.ID, nil) + if loop.lastErr != nil { + t.Fatalf("aggregate must keep the capable member: %v", loop.lastErr) + } + target, _, err := loop.pickNextReserved(e) + if err != nil { + t.Fatal(err) + } + if target.provider() != "qoder" || target.memberModel != "model-a" { + t.Fatalf("aggregate picked %s/%s, want qoder/model-a", target.provider(), target.memberModel) + } +} + +func TestAggregateFailsWhenNoMemberCanEnforceToolPolicy(t *testing.T) { + e := ChatExecutor{Pool: aggTestPool()} + plan := aggPlan( + accounts.AggregationMember{Provider: "workbuddy", Model: "model-b", Priority: 0}, + accounts.AggregationMember{Provider: "trae", Model: "model-c", Priority: 1}, + ) + loop := e.newRouteLoop(RouteInput{AggregatePlan: plan, PublicModel: plan.ID, Tooling: strictToolingRequest(t)}, plan.ID, nil) + if loop.lastErr == nil || loop.attempts != 0 { + t.Fatalf("aggregate without capable members = attempts:%d lastErr:%v", loop.attempts, loop.lastErr) + } + if !strings.Contains(loop.lastErr.Error(), "cannot enforce") { + t.Fatalf("tool capability error = %v", loop.lastErr) + } +} + +func TestPinnedProviderWithoutToolCapabilityIsRejected(t *testing.T) { + e := ChatExecutor{Pool: aggTestPool()} + loop := e.newRouteLoop(RouteInput{Prefer: "workbuddy", Tooling: strictToolingRequest(t)}, "model-b", nil) + if loop.lastErr == nil || loop.attempts != 0 { + t.Fatalf("pinned loop = attempts:%d lastErr:%v", loop.attempts, loop.lastErr) + } +} diff --git a/internal/executor/session_affinity.go b/internal/executor/session_affinity.go index a4152b382..d268e1412 100644 --- a/internal/executor/session_affinity.go +++ b/internal/executor/session_affinity.go @@ -53,6 +53,7 @@ func resolveSessionKey(ctx context.Context, req translate.ChatRequest) string { type sessionBinding struct { key string accountID string + version uint64 expiresAt time.Time } @@ -78,6 +79,7 @@ type SessionAffinity struct { capacity int entries map[string]*list.Element lru *list.List + version uint64 hits uint64 misses uint64 escapes uint64 @@ -102,6 +104,32 @@ func NewSessionAffinity(ttl time.Duration, capacity int) *SessionAffinity { } } +// Peek reads a live binding without changing the LRU, statistics or entries. +// In particular, a capability probe does not delete an expired binding. +func (a *SessionAffinity) Peek(key string) (string, bool) { + accountID, _, ok := a.peekVersion(key) + return accountID, ok +} + +// peekVersion returns the token for the exact binding observed by a route. +func (a *SessionAffinity) peekVersion(key string) (string, uint64, bool) { + key = strings.TrimSpace(key) + if a == nil || key == "" { + return "", 0, false + } + a.mu.Lock() + defer a.mu.Unlock() + element, ok := a.entries[key] + if !ok { + return "", 0, false + } + binding := element.Value.(sessionBinding) + if !binding.expiresAt.After(time.Now()) { + return "", 0, false + } + return binding.accountID, binding.version, true +} + func (a *SessionAffinity) Get(key string) (string, bool) { if a == nil { return "", false @@ -131,30 +159,60 @@ func (a *SessionAffinity) Get(key string) (string, bool) { } func (a *SessionAffinity) Bind(key, accountID string) { - if a == nil { - return - } - key = strings.TrimSpace(key) - accountID = strings.TrimSpace(accountID) - if key == "" || accountID == "" { - return + a.bindVersion(key, accountID) +} + +// bindVersion identifies this write, even if the account has not changed. +func (a *SessionAffinity) bindVersion(key, accountID string) uint64 { + key, accountID = strings.TrimSpace(key), strings.TrimSpace(accountID) + if a == nil || key == "" || accountID == "" { + return 0 } a.mu.Lock() defer a.mu.Unlock() + a.version++ + if a.version == 0 { // Reserve zero for a missing binding. + a.version++ + } + binding := sessionBinding{key: key, accountID: accountID, version: a.version, expiresAt: time.Now().Add(a.ttl)} if element, ok := a.entries[key]; ok { previous := element.Value.(sessionBinding) if previous.accountID != accountID { a.rebindings++ } - element.Value = sessionBinding{key: key, accountID: accountID, expiresAt: time.Now().Add(a.ttl)} + element.Value = binding a.lru.MoveToFront(element) - return + return binding.version } - element := a.lru.PushFront(sessionBinding{key: key, accountID: accountID, expiresAt: time.Now().Add(a.ttl)}) + element := a.lru.PushFront(binding) a.entries[key] = element for a.lru.Len() > a.capacity { a.remove(a.lru.Back()) } + return binding.version +} + +// touchVersion extends only a live, unchanged binding. +func (a *SessionAffinity) touchVersion(key string, version uint64) bool { + key = strings.TrimSpace(key) + if a == nil || key == "" || version == 0 { + return false + } + a.mu.Lock() + defer a.mu.Unlock() + element, ok := a.entries[key] + if !ok { + return false + } + binding := element.Value.(sessionBinding) + now := time.Now() + if binding.version != version || !binding.expiresAt.After(now) { + return false + } + binding.expiresAt = now.Add(a.ttl) + element.Value = binding + a.lru.MoveToFront(element) + return true } func (a *SessionAffinity) RecordEscape(reason string) { @@ -202,6 +260,22 @@ func (a *SessionAffinity) Forget(key string) { } } +// forgetVersion cannot remove a newer binding, even on the same account. +func (a *SessionAffinity) forgetVersion(key string, version uint64) bool { + key = strings.TrimSpace(key) + if a == nil || key == "" || version == 0 { + return false + } + a.mu.Lock() + defer a.mu.Unlock() + element, ok := a.entries[key] + if !ok || element.Value.(sessionBinding).version != version { + return false + } + a.remove(element) + return true +} + func (a *SessionAffinity) remove(element *list.Element) { if element == nil { return diff --git a/internal/executor/session_affinity_test.go b/internal/executor/session_affinity_test.go index fa17685a6..5442139b8 100644 --- a/internal/executor/session_affinity_test.go +++ b/internal/executor/session_affinity_test.go @@ -52,6 +52,105 @@ func TestSessionAffinityStatsTrackRoutingEvents(t *testing.T) { } } +func TestSessionAffinityPeekDoesNotMutateCache(t *testing.T) { + affinity := NewSessionAffinity(time.Minute, 2) + affinity.Bind("one", "a") + affinity.Bind("two", "b") + before := affinity.Stats() + if id, ok := affinity.Peek(" one "); !ok || id != "a" { + t.Fatalf("peek hit = %q, %v", id, ok) + } + if id, ok := affinity.Peek("missing"); ok || id != "" { + t.Fatalf("peek miss = %q, %v", id, ok) + } + if after := affinity.Stats(); before != after { + t.Fatalf("peeks changed stats: before=%+v after=%+v", before, after) + } + affinity.Bind("three", "c") + if _, ok := affinity.Peek("one"); ok { + t.Fatal("peek changed LRU order") + } + + setAffinityExpiry(affinity, "two", time.Now().Add(-time.Minute)) + before = affinity.Stats() + if id, ok := affinity.Peek("two"); ok || id != "" { + t.Fatalf("peek expired = %q, %v", id, ok) + } + if after := affinity.Stats(); before != after { + t.Fatalf("expired peek changed cache: before=%+v after=%+v", before, after) + } + if _, ok := affinity.Get("two"); ok || affinity.Stats().LastMissReason != "expired" { + t.Fatal("real lookup must still observe and remove the expired entry") + } +} + +func TestSessionAffinityVersionDistinguishesSameAccountRebind(t *testing.T) { + affinity := NewSessionAffinity(time.Hour, 2) + old := affinity.bindVersion("session", "account") + // A newer request can legitimately choose the same account. Its binding + // is independent of the older stream's eventual success or failure. + affinity.Bind("session", "account") + id, current, ok := affinity.peekVersion("session") + if !ok || id != "account" || old == 0 || current == 0 || current == old { + t.Fatalf("same-account rebind: id=%q old=%d current=%d ok=%v", id, old, current, ok) + } + before := affinity.Stats() + if affinity.touchVersion("session", old) || affinity.forgetVersion("session", old) || affinity.touchVersion("missing", current) { + t.Fatal("late feedback changed a newer binding to the same account") + } + if _, version, ok := affinity.peekVersion("session"); !ok || version != current || affinity.Stats() != before { + t.Fatalf("new binding or statistics changed: version=%d ok=%v stats=%+v", version, ok, affinity.Stats()) + } + expires := time.Now().Add(time.Minute) + setAffinityExpiry(affinity, "session", expires) + affinity.Bind("other", "account") + if !affinity.touchVersion("session", current) { + t.Fatal("current binding was not renewed") + } + affinity.mu.Lock() + renewed := affinity.entries["session"].Value.(sessionBinding).expiresAt + affinity.mu.Unlock() + if !renewed.After(expires) { + t.Fatalf("touch did not extend TTL: before=%v after=%v", expires, renewed) + } + if _, version, ok := affinity.peekVersion("session"); !ok || version != current { + t.Fatalf("renewal replaced version: %d ok=%v", version, ok) + } + affinity.Bind("new", "account") + if _, _, ok := affinity.peekVersion("other"); ok { + t.Fatal("versioned touch did not update LRU") + } + if !affinity.forgetVersion("session", current) || affinity.forgetVersion("session", current) { + t.Fatal("current version should be removed exactly once") + } +} + +func TestSessionAffinityVersionIsNotReusedAfterEviction(t *testing.T) { + affinity := NewSessionAffinity(time.Hour, 1) + old := affinity.bindVersion("session", "account") + affinity.Bind("evicts-session", "account") + current := affinity.bindVersion("session", "account") + if current == old || affinity.touchVersion("session", old) || affinity.forgetVersion("session", old) { + t.Fatal("recreated binding used an old version") + } + setAffinityExpiry(affinity, "session", time.Now().Add(-time.Minute)) + if affinity.touchVersion("session", current) { + t.Fatal("touch revived an expired binding") + } + if _, version, ok := affinity.peekVersion("session"); ok || version != 0 { + t.Fatalf("expired binding still visible: version=%d ok=%v", version, ok) + } +} + +func setAffinityExpiry(affinity *SessionAffinity, key string, expiry time.Time) { + affinity.mu.Lock() + defer affinity.mu.Unlock() + element := affinity.entries[key] + binding := element.Value.(sessionBinding) + binding.expiresAt = expiry + element.Value = binding +} + // Cache affinity is account/session scoped, not a global region latch. A // bound conversation must stay on its account even when the route spans // providers and ordinary round-robin would pick another one first. diff --git a/internal/executor/session_key_test.go b/internal/executor/session_key_test.go index 13d85a255..fedb80ee3 100644 --- a/internal/executor/session_key_test.go +++ b/internal/executor/session_key_test.go @@ -61,7 +61,7 @@ func TestPrepareUsesConversationID(t *testing.T) { if err != nil { t.Fatal(err) } - if sessionKeyFromContext(plain.Context) == sessionKeyFromContext(withID.Context) { + if plain.Route.SessionKey == withID.Route.SessionKey { t.Fatal("conversation id must change the affinity key") } if providers.ConversationFromContext(withID.Context) == "" { @@ -100,7 +100,7 @@ func TestMessageStatShardsEnvAndFallback(t *testing.T) { t.Fatal(err) } contentKey := sessionKeyFor("", "", auth.ConsoleIdentity(), req) - if got := sessionKeyFromContext(prepared.Context); got != contentKey || got == a { + if got := prepared.Route.SessionKey; got != contentKey || got == a { t.Fatalf("shard replaced content seed: got %q seed %q shard %q", got, contentKey, a) } // No user anchor and no conversation id: the shard key is the only affinity. @@ -112,7 +112,7 @@ func TestMessageStatShardsEnvAndFallback(t *testing.T) { t.Fatal(err) } wantShard := ShardFallbackKey(auth.ConsoleIdentity(), anchorless) - if got := sessionKeyFromContext(fallback.Context); got == "" || got != wantShard { + if got := fallback.Route.SessionKey; got == "" || got != wantShard { t.Fatalf("anchorless request did not use shard: got %q want %q", got, wantShard) } t.Setenv("CLI2API_MSGSTAT_SHARDS", "bad") diff --git a/internal/executor/sticky_model_rejection_test.go b/internal/executor/sticky_model_rejection_test.go new file mode 100644 index 000000000..171fe8026 --- /dev/null +++ b/internal/executor/sticky_model_rejection_test.go @@ -0,0 +1,227 @@ +package executor + +import ( + "errors" + "net/http" + "sync/atomic" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func TestStickyModelRejectionEscapesToHealthyAccount(t *testing.T) { + for _, tc := range []struct { + name string + stream bool + }{ + {"chat", false}, + {"stream", true}, + } { + t.Run(tc.name, func(t *testing.T) { + const model, alias = "model-a", "public-alias" + const public = "qoder-cn/" + alias + pool := NewPool(nil, nil) + wire := &routeRegressionWire{} + var reject atomic.Bool + aliases := map[string]string{alias: model} + wire.add(t, pool, Item{ID: "a", Provider: "qoder", Region: "cn", ModelAliases: aliases}, func(w http.ResponseWriter, hit routeRegressionHit) { + if reject.Load() { + w.Header().Set("X-Qoder-Error-Kind", accounts.KindModelNotAvailable) + http.Error(w, `{"error":{"message":"model does not exist"}}`, http.StatusBadRequest) + return + } + routeRegressionOK(w, hit) + }) + wire.add(t, pool, Item{ID: "b", Provider: "qoder", Region: "cn", Models: []string{model}, ModelAliases: aliases}, nil) + wire.add(t, pool, Item{ID: "0-out-of-region", Provider: "qoder", Region: "global", Models: []string{model}, ModelAliases: aliases}, nil) + e := NewChatExecutor(pool, "") + identity := auth.Identity{Kind: auth.KindKey, KeyID: "sticky-test", AllowedProviders: []string{"qoder:cn"}} + + routeRegressionSeedBinding(t, e, public, identity, "a") + reject.Store(true) + // A pin bypasses affinity, so this rejection does not update the old session. + rejection := routeRegressionPrepare(t, e, PrepareInput{Request: translate.ChatRequest{Model: public}, Identity: identity, PreferAccount: "a"}) + if account, attempts, err := routeRegressionExecute(t, e, rejection); err != nil || account != "b" || attempts != 2 { + t.Fatalf("rejection and fallback: account=%q attempts=%d err=%v", account, attempts, err) + } + item, _ := pool.ByID("a") + if item.Models != nil || len(item.ProvenModels) != 0 || ItemCouldServeModel(item, alias) { + t.Fatal("expected the explicit rejection of the last proven model on an unknown catalog") + } + + follow := routeRegressionPrepare(t, e, PrepareInput{Request: translate.ChatRequest{Model: public, Stream: tc.stream}, Identity: identity}) + if account, attempts, err := routeRegressionExecute(t, e, follow); err != nil || account != "b" || attempts != 1 { + t.Fatalf("old session: account=%q attempts=%d err=%v, want b in one attempt", account, attempts, err) + } + if account, ok := e.SessionAffinity.Get(follow.Route.SessionKey); !ok || account != "b" { + t.Fatalf("session was not rebound: account=%q bound=%v", account, ok) + } + wire.require(t, + routeRegressionDispatchTo("a", model, false), routeRegressionDispatchTo("a", model, false), + routeRegressionDispatchTo("b", model, false), routeRegressionDispatchTo("b", model, tc.stream), + ) + }) + } +} + +func TestStickyModelRejectionBetweenScopeAndReserve(t *testing.T) { + const model = "model-a" + pool := NewPool(nil, nil) + for _, item := range []Item{ + {ID: "a", Provider: "qoder", Region: "cn"}, + {ID: "b", Provider: "qoder", Region: "cn"}, + {ID: "0-other-region", Provider: "qoder", Region: "global"}, + {ID: "0-other-provider", Provider: "workbuddy", Region: "cn"}, + } { + item.Models = []string{model} + item.MaxInFlight = 1 + pool.Upsert(item) + } + e := NewChatExecutor(pool, "") + e.SessionAffinity.Bind("old-session", "a") + route := RouteInput{ + RouteModel: model, SessionKey: "old-session", + ProviderFilter: "qoder", RegionFilter: "cn", AllowedProviders: []string{"qoder:cn"}, + } + sticky := e.newRouteLoop(route, model, nil) + route.Prefer = "a" + explicit := e.newRouteLoop(route, model, nil) + if sticky.routing.Source != routingSticky || sticky.working.PreferAccount != "a" || explicit.working.PreferAccount != "a" { + t.Fatal("both routes must see the original model before the pool changes") + } + + // Place the rejection deterministically between the two snapshots. + pool.RemoveModel("a", model) + if target, _, err := explicit.pickNextReserved(e); target.item.ID != "" || explicit.index != 0 { + pool.Release(target.item.ID) + t.Fatalf("explicit model pin changed: picked %q after %d attempts (err=%v)", target.item.ID, explicit.index, err) + } else { + var execErr *ExecutionError + if !errors.As(err, &execErr) || execErr.Classified.Code != "model_not_available" { + t.Fatalf("explicit model pin error=%v, want model_not_available", err) + } + } + target, index, err := sticky.pickNextReserved(e) + defer pool.Release(target.item.ID) + if err != nil || target.item.ID != "b" || target.upstreamModel != model || index != 0 || sticky.index != 1 { + t.Fatalf("soft recheck: account=%q model=%q index=%d attempts=%d err=%v, want b in one attempt", target.item.ID, target.upstreamModel, index, sticky.index, err) + } + if sticky.routing.Source != routingStickyEscape || target.item.InFlight != 1 { + t.Fatalf("soft recheck: routing=%q in-flight=%d", sticky.routing.Source, target.item.InFlight) + } +} + +func TestStickyModelRejectionPrefersSoftThenHardScope(t *testing.T) { + const model = "model-a" + for _, tc := range []struct { + name string + route RouteInput + healthy Item + others []Item + wantSoft bool + }{ + { + name: "healthy-soft-scope-first", + route: RouteInput{RegionFilter: "cn", AllowedProviders: []string{"qoder:cn", "workbuddy:cn"}}, + healthy: Item{ID: "b", Provider: "qoder", Region: "cn"}, + others: []Item{{ID: "0-healthy-in-hard-scope", Provider: "workbuddy", Region: "cn"}}, + wantSoft: true, + }, + { + name: "hard-provider", + route: RouteInput{ProviderFilter: "qoder", AllowedProviders: []string{"qoder", "workbuddy:cn"}}, + healthy: Item{ID: "b", Provider: "qoder", Region: "global"}, + others: []Item{{ID: "0-outside-provider", Provider: "workbuddy", Region: "cn"}}, + }, + { + name: "hard-region-and-key", + route: RouteInput{RegionFilter: "cn", AllowedProviders: []string{"qoder:cn", "workbuddy"}}, + healthy: Item{ID: "b", Provider: "workbuddy", Region: "cn"}, + others: []Item{ + {ID: "0-outside-region", Provider: "workbuddy", Region: "global"}, + {ID: "0-outside-key", Provider: "trae", Region: "cn"}, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + pool := NewPool(nil, nil) + items := append([]Item{ + {ID: "a", Provider: "qoder", Region: "cn"}, + {ID: "a-cooling", Provider: "qoder", Region: "cn", DownUntil: time.Now().Add(time.Hour)}, + tc.healthy, + }, tc.others...) + for _, item := range items { + item.Models = []string{model} + pool.Upsert(item) + } + e := NewChatExecutor(pool, "") + e.SessionAffinity.Bind("old-session", "a") + route := tc.route + route.RouteModel = model + route.SessionKey = "old-session" + loop := e.newRouteLoop(route, model, nil) + if !loop.sticky || loop.working.PreferAccount != "a" { + t.Fatal("expected to start with a narrower session preference") + } + softKey, hardKey := rotationKey(loop.working), rotationKey(loop.hard) + pool.RemoveModel("a", model) + + target, index, err := loop.pickNextReserved(e) + defer pool.Release(target.item.ID) + if err != nil || target.item.ID != tc.healthy.ID || index != 0 || loop.index != 1 { + t.Fatalf("fallback: target=%q index=%d attempts=%d err=%v, want b in one attempt", target.item.ID, index, loop.index, err) + } + if loop.sticky != tc.wantSoft || loop.routing.Source != routingStickyEscape { + t.Fatalf("fallback: kept soft scope=%v, want %v; routing=%q", loop.sticky, tc.wantSoft, loop.routing.Source) + } + winningKey, unusedKey := hardKey, softKey + if tc.wantSoft { + winningKey, unusedKey = softKey, hardKey + } + if pool.lastPicked[unusedKey] != "" || pool.lastPicked[winningKey] != tc.healthy.ID || len(pool.lastPicked) != 1 { + t.Fatalf("fallback must commit only the winning rotation: %v", pool.lastPicked) + } + for _, item := range pool.Items() { + want := 0 + if item.ID == tc.healthy.ID { + want = 1 + } + if item.InFlight != want { + t.Errorf("%s owns %d slots; want %d", item.ID, item.InFlight, want) + } + } + }) + } +} + +func TestStickyModelRejectionRechecksAliasEligibility(t *testing.T) { + const model, alias = "model-a", "public-alias" + pool := NewPool(nil, nil) + for _, item := range []Item{ + {ID: "a", Provider: "qoder", Region: "cn", Models: []string{alias, model}, ModelAliases: map[string]string{alias: model}}, + {ID: "b", Provider: "workbuddy", Region: "cn", Models: []string{model}, ModelAliases: map[string]string{alias: model}}, + {ID: "0-raw-model", Provider: "workbuddy", Region: "cn", Models: []string{alias}}, + } { + pool.Upsert(item) + } + e := NewChatExecutor(pool, "") + e.SessionAffinity.Bind("old-session", "a") + loop := e.newRouteLoop(RouteInput{ + RouteModel: alias, RegionFilter: "cn", SessionKey: "old-session", RequireModelAlias: true, + AllowedProviders: []string{"qoder:cn", "workbuddy:cn"}, + }, alias, nil) + if !loop.sticky || loop.working.PreferAccount != "a" { + t.Fatal("expected initial alias preference") + } + // A still advertises the equally named raw model. Neither it nor the + // equally named raw model on another provider can serve an alias-only key. + pool.SetModelRouting("a", nil, nil, false) + target, _, err := loop.pickNextReserved(e) + defer pool.Release(target.item.ID) + if err != nil || target.item.ID != "b" || target.upstreamModel != model || loop.index != 1 { + t.Fatalf("alias fallback: target=%q model=%q attempts=%d err=%v, want b/%s in one attempt", target.item.ID, target.upstreamModel, loop.index, err, model) + } +} diff --git a/internal/executor/timeout_attribution_test.go b/internal/executor/timeout_attribution_test.go new file mode 100644 index 000000000..cf3c6dd65 --- /dev/null +++ b/internal/executor/timeout_attribution_test.go @@ -0,0 +1,76 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "net" + "net/url" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" +) + +func TestTransportSendStateSeesInnerDialUnderPost(t *testing.T) { + dial := &url.Error{Op: "Post", URL: "https://example.test", Err: &net.OpError{Op: "dial", Net: "tcp", Err: errors.New("connection refused")}} + if got := transportSendState(dial); got != RequestStateNotSent { + t.Fatalf("state = %q, want not_sent", got) + } + classified := ClassifyError(dial) + if !classified.Failover { + t.Fatalf("a proven-not-sent dial must allow failover: %+v", classified) + } + if classified.RequestState != RequestStateNotSent { + t.Fatalf("request state = %q", classified.RequestState) + } +} + +func TestTransportSendStateWriteIsMaybeSent(t *testing.T) { + write := &url.Error{Op: "Post", URL: "https://example.test", Err: &net.OpError{Op: "write", Net: "tcp", Err: errors.New("broken pipe")}} + if got := transportSendState(write); got != RequestStateMaybeSent { + t.Fatalf("state = %q, want maybe_sent", got) + } + if classified := ClassifyError(write); classified.Failover { + t.Fatalf("a partial write must not allow a replay: %+v", classified) + } +} + +func TestFirstByteTimeoutDoesNotFailover(t *testing.T) { + err := fmt.Errorf("qoder: %w: no response head", providers.ErrFirstByteTimeout) + classified := ClassifyError(err) + if classified.RequestState != RequestStateMaybeSent || classified.RequestSent != true { + t.Fatalf("first-byte state = %+v", classified) + } + if classified.Failover { + t.Fatalf("first-byte timeout must not switch accounts: %+v", classified) + } +} + +func TestTaggedInternalRetriesSurviveClassification(t *testing.T) { + err := providers.TagInternalRetries(errors.New("read workbuddy stream: unexpected EOF"), 1) + if got := ClassifyError(err); got.InternalRetries != 1 { + t.Fatalf("internal retries lost: %+v", got) + } +} + +func TestLiveParentStreamReadTimeoutIsUpstreamNotCanceled(t *testing.T) { + ctx := context.Background() + readErr := StreamReadError(context.DeadlineExceeded) + classified := ClassifyError(readErr) + if classified.Kind == accounts.KindCanceled { + t.Fatalf("live parent read timeout was classified as client cancellation: %+v", classified) + } + if classified.RequestState != RequestStateSent { + t.Fatalf("stream body timeout state = %q, want sent", classified.RequestState) + } + if dispatchCancellation(ctx, readErr, classified) != nil { + t.Fatal("live parent must not synthesize cancellation") + } + + canceled, cancel := context.WithCancel(context.Background()) + cancel() + if got := dispatchCancellation(canceled, readErr, classified); !errors.Is(got, context.Canceled) { + t.Fatalf("a canceled parent must win over the read timeout, got %v", got) + } +} diff --git a/internal/executor/tooling.go b/internal/executor/tooling.go new file mode 100644 index 000000000..e3530c0a2 --- /dev/null +++ b/internal/executor/tooling.go @@ -0,0 +1,147 @@ +package executor + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/toolcall" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func canonicalTooling(req translate.ChatRequest, native *translate.NativeResponsesRequest) (toolcall.Request, error) { + tools, choice, parallel := req.Tools, req.ToolChoice, req.ParallelToolCalls + protocol := toolcall.NormalizeProtocol(req.Protocol) + if native != nil { + protocol = toolcall.ProtocolResponses + var nativeParallel json.RawMessage + tools, choice, nativeParallel = native.ToolingFields() + parsedParallel, parseErr := parseParallelFlag(nativeParallel) + if parseErr != nil { + return toolcall.Request{}, &PrepareError{Status: http.StatusBadRequest, Code: "invalid_tool_request", Message: parseErr.Error()} + } + parallel = parsedParallel + } + request, err := toolcall.ParseRequest(protocol, tools, choice, parallel, toolcall.RepairSafe) + if err != nil { + return toolcall.Request{}, &PrepareError{Status: http.StatusBadRequest, Code: "invalid_tool_request", Message: err.Error()} + } + if request.HasTools() { + request.Policy.NativeStrict = request.Policy.Schema == toolcall.SchemaStrict + } + return request, nil +} + +func parseParallelFlag(raw json.RawMessage) (*bool, error) { + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + var value bool + if err := json.Unmarshal(raw, &value); err != nil { + return nil, fmt.Errorf("parallel_tool_calls must be a boolean") + } + return &value, nil +} + +func toolingFromRequest(req translate.ChatRequest) toolcall.Request { + request, err := canonicalTooling(req, nil) + if err != nil { + return toolcall.Request{} + } + return request +} + +// validateChatToolResult validates a buffered Chat result before dispatch +// accounting is allowed to mark the account and attempt successful. +func validateChatToolResult(request toolcall.Request, result ChatResult) error { + turn, err := toolcall.ReduceChatCompletion(request, result.Content, result.Reasoning, result.FinishReason, result.ToolCalls) + if err != nil { + return err + } + return turn.Validate() +} + +func validateNativeToolResult(request toolcall.Request, result NativeResponseResult) error { + if len(result.Response) == 0 { + return nil + } + // The SSE terminal event's finish reason is authoritative: a body that + // claims status:"completed" inside response.incomplete (or vice versa) must + // not be accepted by the non-stream path just because it has no visible + // stream to reconcile against. + return toolcall.ValidateNativeResponsesTurn(result.Response, request, result.FinishReason) +} + +func upstreamToolValidationError(err error) (Classified, error) { + classified := Classified{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadGateway, + Code: "invalid_upstream_tool_call", + Type: "api_error", + Message: err.Error(), + } + return classified, NewExecutionError(classified, err) +} + +func (e ChatExecutor) itemSupportsTooling(item Item, model string, request toolcall.Request) bool { + if !request.HasTools() { + return true + } + accountModel := AccountModelID(item, model) + nativeModel := NativeModelID(item, accountModel) + if itemDeclaresNoTools(item, accountModel, nativeModel) { + return false + } + profile := providers.ToolProfileFor(itemProvider(item), nativeModel) + if !profile.SupportsTools() { + return false + } + if !profile.SupportsChoice(request.Choice.Mode) { + return false + } + if request.Policy.Parallel != nil && !*request.Policy.Parallel && !profile.ParallelOff { + return false + } + if request.Policy.Schema == toolcall.SchemaStrict && !profile.StrictSchema { + return false + } + return true +} + +func itemDeclaresNoTools(item Item, models ...string) bool { + for _, listed := range item.NoToolsModels { + listedID := CanonicalModelID(listed) + if listedID == "" { + continue + } + for _, candidate := range models { + if CanonicalModelID(candidate) == listedID { + return true + } + } + } + return false +} + +func toolCapabilityError(provider, model string, request toolcall.Request) error { + reason := "tools" + if request.Choice.Mode != "" && request.Choice.Mode != toolcall.ChoiceUnspecified { + reason = "tool_choice " + string(request.Choice.Mode) + } + if request.Policy.Parallel != nil && !*request.Policy.Parallel { + reason = "parallel_tool_calls=false" + } + if request.Policy.Schema == toolcall.SchemaStrict { + reason = "strict tool schema" + } + provider = firstNonEmpty(provider, "the selected provider") + return NewExecutionError(Classified{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadRequest, + Code: "tool_capability_unavailable", + Type: "invalid_request_error", + Message: fmt.Sprintf("%s cannot enforce %s for model %s", provider, reason, model), + }, nil) +} diff --git a/internal/executor/tooling_test.go b/internal/executor/tooling_test.go new file mode 100644 index 000000000..3d4499928 --- /dev/null +++ b/internal/executor/tooling_test.go @@ -0,0 +1,120 @@ +package executor + +import ( + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +func TestCanonicalToolingParsesChatAndNativeResponses(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`) + request, err := canonicalTooling(translate.ChatRequest{Tools: tools, ToolChoice: json.RawMessage(`"required"`)}, nil) + if err != nil { + t.Fatal(err) + } + if !request.HasTools() || request.Protocol != toolcall.ProtocolChat || request.Choice.Mode != toolcall.ChoiceRequired || len(request.Specs) != 1 { + t.Fatalf("chat tooling = %+v", request) + } + native, err := translate.ParseNativeResponses([]byte(`{"model":"m","input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"auto","parallel_tool_calls":false}`)) + if err != nil { + t.Fatal(err) + } + request, err = canonicalTooling(translate.ChatRequest{}, native) + if err != nil { + t.Fatal(err) + } + if request.Protocol != toolcall.ProtocolResponses || !request.HasTools() || request.Policy.Parallel == nil || *request.Policy.Parallel { + t.Fatalf("native tooling = %+v", request) + } +} + +func TestCanonicalToolingRejectsMalformedNativeParallelFlag(t *testing.T) { + native, err := translate.ParseNativeResponses([]byte(`{"model":"m","input":"hi","tools":[{"type":"function","name":"run","parameters":{"type":"object"}}],"parallel_tool_calls":"false"}`)) + if err != nil { + t.Fatal(err) + } + _, err = canonicalTooling(translate.ChatRequest{}, native) + if err == nil || !strings.Contains(err.Error(), "parallel_tool_calls") { + t.Fatalf("malformed parallel flag error = %v", err) + } +} + +func TestCanonicalToolingRejectsUnenforceableChoice(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`) + _, err := canonicalTooling(translate.ChatRequest{Tools: tools, ToolChoice: json.RawMessage(`{"type":"function","function":{"name":"missing"}}`)}, nil) + if err == nil || !strings.Contains(err.Error(), "missing") { + t.Fatalf("named choice error = %v", err) + } + var prepareErr *PrepareError + if !errors.As(err, &prepareErr) || prepareErr.Code != "invalid_tool_request" || prepareErr.Status != 400 { + t.Fatalf("prepare error = %#v", err) + } +} + +func TestItemSupportsToolingUsesProviderContract(t *testing.T) { + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object"},"strict":true}}]`), json.RawMessage(`"required"`), boolPointer(false), toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + cases := []struct { + provider string + want bool + }{ + {"qoder", true}, + {"codearts", false}, // required is native, but parallel=false is not guaranteed + {"zhipu", false}, // required is native, but parallel=false is not guaranteed + {"workbuddy", false}, // required is native, but strict is dropped by the normalizer + {"trae", false}, // strict is dropped and parallel=false is not guaranteed + {"codex", false}, // Chat-compat normalizer drops strict + {"minimaxcode", false}, // Anthropic payload drops strict + {"devin", false}, // only auto/none are enforceable + {"command", false}, // only auto is enforceable + {"qwenwork", false}, // auto/none only + {"kiro", false}, // prompted auto/none only + } + for _, tc := range cases { + item := Item{Provider: tc.provider} + if got := (ChatExecutor{}).itemSupportsTooling(item, "m", request); got != tc.want { + t.Fatalf("%s supports = %v, want %v", tc.provider, got, tc.want) + } + } +} + +func TestItemSupportsToolingChoiceWithoutStrictOrParallelLimit(t *testing.T) { + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, json.RawMessage(`[{"type":"function","function":{"name":"run","parameters":{"type":"object"}}}]`), json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + cases := []struct { + provider string + want bool + }{ + {"qoder", true}, + {"workbuddy", true}, + {"trae", true}, + {"codearts", true}, + {"zhipu", true}, + {"kimi", true}, + {"codex", true}, + {"meta", true}, + {"minimaxcode", true}, + {"opencode", true}, + {"doubaowork", true}, + {"devin", true}, + {"command", false}, + {"qwenwork", false}, + {"kiro", false}, + } + for _, tc := range cases { + item := Item{Provider: tc.provider} + if got := (ChatExecutor{}).itemSupportsTooling(item, "m", request); got != tc.want { + t.Fatalf("%s supports = %v, want %v", tc.provider, got, tc.want) + } + } +} + +func boolPointer(value bool) *bool { return &value } diff --git a/internal/executor/transport_failure_test.go b/internal/executor/transport_failure_test.go index bd40f114a..19a1fd491 100644 --- a/internal/executor/transport_failure_test.go +++ b/internal/executor/transport_failure_test.go @@ -23,13 +23,16 @@ func qoderHandshakeTimeout() error { } } -func TestClassifyErrorTransportFailureKeepsAccountRoutable(t *testing.T) { +func TestClassifyErrorTransportFailureAllowsFailover(t *testing.T) { c := ClassifyError(qoderHandshakeTimeout()) if c.Kind != accounts.KindUnavailable || c.Status != 502 || c.Code != "upstream_unreachable" { t.Fatalf("transport classified=%+v", c) } - if c.Cooldown != 0 || c.RetryAfter != 0 || c.Failover { - t.Fatalf("transport failure must not cool or fail over: %+v", c) + if c.Cooldown != 0 || c.RetryAfter != 0 || !c.Failover { + t.Fatalf("a proven-not-sent transport failure must fail over without cooling: %+v", c) + } + if c.RequestState != RequestStateNotSent || c.RequestSent { + t.Fatalf("transport send state = %q", c.RequestState) } if !strings.Contains(c.Message, "TLS handshake timeout") { t.Fatalf("message must keep the transport cause: %q", c.Message) @@ -79,7 +82,7 @@ func TestClassifyErrorUpstreamQuotedHandshakeTimeoutStillCools(t *testing.T) { func TestClassifyErrorWrappedTransportFailure(t *testing.T) { wrapped := fmt.Errorf("qoder chat: %w", qoderHandshakeTimeout()) c := ClassifyError(wrapped) - if c.Cooldown != 0 || c.Failover || c.Code != "upstream_unreachable" { + if c.Cooldown != 0 || !c.Failover || c.Code != "upstream_unreachable" || c.RequestState != RequestStateNotSent { t.Fatalf("wrapped transport classified=%+v", c) } } diff --git a/internal/executor/upstream_align_test.go b/internal/executor/upstream_align_test.go index a469526bb..ea32ad9fd 100644 --- a/internal/executor/upstream_align_test.go +++ b/internal/executor/upstream_align_test.go @@ -40,7 +40,7 @@ func TestClassifyErrorTLSVerifyNoFailover(t *testing.T) { func TestClassifyErrorImageConversionTimeoutNoFailover(t *testing.T) { c := ClassifyError(&providers.Error{ Kind: accounts.KindUnavailable, Status: 502, - Code: providers.CodeUpstreamImageConversionTimeout, + Code: providers.CodeUpstreamImageConversionTimeout, Message: "Image conversion timeout", }) if c.Failover || c.Cooldown != 0 || c.Code != providers.CodeUpstreamImageConversionTimeout { From 9dae282fb4ab9bf04e419995028345eafa3dcab2 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:42:30 +0800 Subject: [PATCH 4/4] feat(runtime): single dispatch plan, canonical tool delivery, and honest terminal accounting Route through one dispatch plan: the account reservation and rotation update together, the provider and region stay inside what the request and API key allow, and a member that cannot enforce the requested tool contract is skipped before any upstream attempt. Cooldowns and stream feedback follow the selected account and concrete model, including native Responses. Tool calls reach the client from the canonical contract. A malformed, truncated, or undeclared call is rejected before a success frame or buffered message is written, and one call identity survives from the upstream event to the final frame. Upstream terminal state and the downstream terminal write are recorded separately, flush failures propagate, and timeouts are attributed to the transport stage that failed. Public HTTP and SSE errors are redacted, native failure frames are sanitized, and the upstream Retry-After passes through CORS. Add a gateway quality model (TTFT, head wait, throughput, TPOT, delivery completeness) plus request statistics for TTFT percentiles, incompletion rate and average throughput. Attempt buffers are bounded and reclaimed, attempt sequence is stable, and entry rejections carry the request ID. Aggregation keeps member order, caps dispatches per requested model across tiers, and keeps previews in sync with configured members. The public model list follows API-key grants and routing, and a canceled stream no longer cools a healthy account. --- .../runtime-route-toolcall-delivery.md | 27 + docs/NATIVE_PROTOCOL_REQUESTS.md | 31 +- internal/api/auth_test.go | 2 +- internal/api/chat_usage_test.go | 8 +- internal/api/compat_test.go | 6 +- internal/api/entry_matrix_test.go | 72 ++ internal/api/logs_api_key_test.go | 4 +- internal/api/s01_protocol_contract_test.go | 20 +- .../app/aggregation_catalog_contract_test.go | 172 ++++ internal/app/aggregation_models.go | 33 +- internal/app/gateway.go | 8 +- internal/app/model_catalog.go | 12 +- internal/console/aggregation_preview_test.go | 94 ++ internal/console/aggregations.go | 52 +- internal/console/aggregations_test.go | 55 ++ internal/console/live.go | 16 +- internal/console/live_test.go | 16 +- internal/control/aggregation.go | 36 +- internal/control/aggregation_catalog.go | 232 ++++- internal/control/aggregation_catalog_test.go | 87 ++ internal/control/aggregation_test.go | 247 +++++- internal/control/catalog_policy.go | 73 +- internal/control/provider_settings.go | 6 +- internal/gateway/anthropic.go | 145 +++- internal/gateway/compat.go | 67 +- internal/gateway/compat_stream.go | 418 ++++----- internal/gateway/entry_body_test.go | 68 ++ internal/gateway/entry_rejection.go | 69 ++ internal/gateway/fefo_quota_test.go | 102 ++- internal/gateway/first_frame.go | 127 +++ internal/gateway/first_frame_test.go | 85 ++ internal/gateway/handler.go | 12 +- internal/gateway/http.go | 69 +- internal/gateway/http_error_type_test.go | 147 ++++ internal/gateway/keylimit.go | 37 +- internal/gateway/keylimit_test.go | 136 +++ internal/gateway/native_delivery_test.go | 545 ++++++++++++ internal/gateway/native_responses.go | 369 +++++++- internal/gateway/native_responses_test.go | 271 +++++- internal/gateway/openai.go | 144 ++-- internal/gateway/openai_stream.go | 274 +++--- internal/gateway/openai_tool_normalizer.go | 217 +++-- internal/gateway/prepare.go | 17 +- internal/gateway/public_error_exit_test.go | 51 ++ internal/gateway/quality.go | 34 + internal/gateway/quality_test.go | 42 + internal/gateway/responses.go | 250 ++++-- internal/gateway/responses_test.go | 87 +- internal/gateway/route_lifecycle_test.go | 803 ++++++++++++++++++ internal/gateway/session_context.go | 28 +- internal/gateway/stream_flush_error_test.go | 80 ++ internal/gateway/stream_heartbeat.go | 144 +--- .../gateway/stream_heartbeat_followup_test.go | 76 +- internal/gateway/stream_heartbeat_test.go | 138 +-- .../gateway/stream_route_identity_test.go | 183 ++++ internal/gateway/stream_terminal_test.go | 144 ++++ internal/gateway/toolargs_stream_test.go | 106 +-- internal/gateway/toolcall_acceptance_test.go | 282 ++++++ internal/gateway/toolcall_result.go | 69 ++ internal/gateway/toolcall_result_test.go | 55 ++ internal/gateway/toolcall_stream_test.go | 170 ++++ internal/gateway/usage.go | 2 +- internal/logs/attempt_buffer_test.go | 145 ++++ internal/logs/recent_completions_test.go | 2 +- internal/logs/recorder.go | 164 ++++ internal/providers/kiro/tools_test.go | 7 +- internal/quality/completeness.go | 59 ++ internal/quality/doc.go | 19 + internal/quality/gate.go | 128 +++ internal/quality/quality_test.go | 195 +++++ internal/quality/sample.go | 148 ++++ internal/quality/timing.go | 82 ++ internal/runtime/checkin_status_test.go | 6 +- internal/runtime/manager_catalog.go | 16 + internal/runtime/manager_fefo.go | 30 +- internal/runtime/manager_fefo_test.go | 77 ++ internal/runtime/manager_maintenance.go | 4 +- internal/server/http.go | 37 + internal/server/middleware.go | 61 +- internal/server/protocol_error_test.go | 95 +++ internal/server/router.go | 2 +- internal/server/server.go | 3 + internal/store/backup_test.go | 1 + internal/store/migrations.go | 15 + .../store/request_attempt_outcome_test.go | 51 ++ internal/store/request_logs.go | 38 +- internal/store/request_logs_test.go | 21 + internal/store/request_quality_stats_test.go | 74 ++ internal/store/request_stats_singlepass.go | 39 +- internal/translate/toolargs.go | 276 ------ internal/translate/toolargs_normalize_test.go | 36 - internal/translate/toolargs_test.go | 41 - 92 files changed, 7555 insertions(+), 1689 deletions(-) create mode 100644 changelog/unreleased/runtime-route-toolcall-delivery.md create mode 100644 internal/api/entry_matrix_test.go create mode 100644 internal/app/aggregation_catalog_contract_test.go create mode 100644 internal/console/aggregation_preview_test.go create mode 100644 internal/console/aggregations_test.go create mode 100644 internal/gateway/entry_body_test.go create mode 100644 internal/gateway/entry_rejection.go create mode 100644 internal/gateway/first_frame.go create mode 100644 internal/gateway/first_frame_test.go create mode 100644 internal/gateway/http_error_type_test.go create mode 100644 internal/gateway/native_delivery_test.go create mode 100644 internal/gateway/public_error_exit_test.go create mode 100644 internal/gateway/quality.go create mode 100644 internal/gateway/quality_test.go create mode 100644 internal/gateway/route_lifecycle_test.go create mode 100644 internal/gateway/stream_flush_error_test.go create mode 100644 internal/gateway/stream_route_identity_test.go create mode 100644 internal/gateway/stream_terminal_test.go create mode 100644 internal/gateway/toolcall_acceptance_test.go create mode 100644 internal/gateway/toolcall_result.go create mode 100644 internal/gateway/toolcall_result_test.go create mode 100644 internal/gateway/toolcall_stream_test.go create mode 100644 internal/logs/attempt_buffer_test.go create mode 100644 internal/quality/completeness.go create mode 100644 internal/quality/doc.go create mode 100644 internal/quality/gate.go create mode 100644 internal/quality/quality_test.go create mode 100644 internal/quality/sample.go create mode 100644 internal/quality/timing.go create mode 100644 internal/server/protocol_error_test.go create mode 100644 internal/store/request_attempt_outcome_test.go create mode 100644 internal/store/request_quality_stats_test.go delete mode 100644 internal/translate/toolargs.go delete mode 100644 internal/translate/toolargs_normalize_test.go delete mode 100644 internal/translate/toolargs_test.go diff --git a/changelog/unreleased/runtime-route-toolcall-delivery.md b/changelog/unreleased/runtime-route-toolcall-delivery.md new file mode 100644 index 000000000..09fac7a84 --- /dev/null +++ b/changelog/unreleased/runtime-route-toolcall-delivery.md @@ -0,0 +1,27 @@ +### English + +- Route through a single dispatch plan: reserve the account and update rotation together, keep the provider and region allowed by the request and API key, and skip an incapable member before any upstream attempt. +- Use the selected account and concrete model for cooldowns and stream feedback, including native Responses, and check API-key concurrency before an aggregation classifier can send a request. +- Deliver tool calls from the canonical contract: reject malformed, truncated, or undeclared calls before a success frame or buffered message is written, and keep one call identity from the upstream event through the final frame. +- Record the upstream terminal state and the downstream terminal write separately, propagate flush failures, and classify connect, write, read and first-frame timeouts by the transport stage that actually failed. +- Return only generic or redacted text on public HTTP and SSE errors, sanitize native failure frames, and preserve the upstream `Retry-After` through CORS. +- Add a gateway quality model that separates TTFT, head wait, full and decode throughput, TPOT, and a delivery-completeness verdict, and extend request statistics with TTFT percentiles, an incompletion rate, and average throughput. +- Bound and reclaim the per-request attempt buffer, assign a stable attempt sequence, and log entry rejections with the request ID. +- Priority aggregations rotate among the best-tier targets in member order, `max_attempts` caps dispatches of the requested model across tiers, and previews stay in sync with configured members. +- Keep the public model list consistent with API-key grants and routing, including namespaced models and group names that shadow account aliases, and stop a canceled stream from cooling a healthy account. +- Run bulk account operations fully concurrent, push real runtime state to the console, and show provider, model and cooldown detail for a failed quota refresh. +- Remove the superseded tool-argument helpers in `internal/translate` now that `internal/toolcall` owns parsing, repair and validation. + +### 中文 + +- 路由收敛到单一调度计划:账号预留与轮转一起更新,只使用请求与密钥允许的供应商和地区,能力不满足的成员在上游请求之前就被跳过。 +- 冷却与流反馈按最终选中的账号和具体模型记录(含原生 Responses),API 密钥并发在聚合分类器发请求之前就校验。 +- 工具调用按规范契约交付:损坏、截断或未声明的调用在成功帧或缓冲消息写出之前就拒绝,同一次调用从上游事件到最终帧保持同一身份。 +- 上游终态与下游终态写出分开记录,冲刷失败向上传播,连接、写、读、首帧超时按真实失败的传输阶段归类。 +- 公开 HTTP 与 SSE 错误只返回通用或脱敏文案,原生失败帧同样脱敏,上游 `Retry-After` 经 CORS 透出。 +- 新增网关质量模型,把首字节、等待响应头、整体与解码吞吐、TPOT 和交付完整性分开衡量;请求统计补充首字节分位、未完成率与平均吞吐。 +- 每次请求的尝试缓冲加上限并回收,尝试序号稳定,入口拒绝会带上请求 ID。 +- 优先级聚合在最优档位内按成员顺序轮转,`max_attempts` 限制的是所请求模型跨档位的派发次数,预览与配置成员保持一致。 +- 公开模型列表与密钥授权、路由保持一致,包含带命名空间的模型和遮蔽账号别名的组名;被取消的流不再冷却健康账号。 +- 批量账号操作完全并发执行,控制台收到真实运行状态,配额刷新失败时会指出供应商、模型与冷却情况。 +- `internal/toolcall` 接管解析、修复与校验之后,删除 `internal/translate` 中已被取代的工具参数辅助函数。 diff --git a/docs/NATIVE_PROTOCOL_REQUESTS.md b/docs/NATIVE_PROTOCOL_REQUESTS.md index 9d0a17914..ff4c4a2df 100644 --- a/docs/NATIVE_PROTOCOL_REQUESTS.md +++ b/docs/NATIVE_PROTOCOL_REQUESTS.md @@ -4,9 +4,9 @@ title: 原生协议请求的现状与后续 scope: [gateway, executor, translate, providers] status: current read-when: 理解三个公共入口与上游协议的关系、改 Responses 原生链路或评估 ChatRequest 边界时 -summary: 三个公共入口的当前转发方式。Responses 在 adapter 声明原生能力时保留原文;Chat 与 Messages 仍先译成 ChatRequest。Codex 两条路径共用同一套上游约束。 +summary: 三个公共入口的当前转发方式。Responses 保留原文;可兼容转换的命名聚合组先按组策略选择成员,再决定是否原生派发。Chat 与 Messages 仍先译成 ChatRequest。 related: [AGENTS.md, docs/ARCHITECTURE_SUMMARY.md, docs/REFACTORING.md, docs/DEVELOPMENT.md] -last-updated: 2026-09-25 +last-updated: 2026-12-02 --- # 原生协议请求的现状与后续 @@ -17,7 +17,7 @@ last-updated: 2026-09-25 - `translate.ChatRequest` 仍是兼容表示,不再是所有请求的强制中间表示。 - 客户端入口决定返回协议,adapter 决定怎么访问上游。两边互不绑定。 -- `/v1/responses` 先保留原文。候选账号的 adapter 实现了 `NativeResponsesStreamer` 时走原生路径;否则才在兼容转换能成功时走 `ChatRequest`。 +- `/v1/responses` 先保留原文。普通请求优先走实现了 `NativeResponsesStreamer` 的候选账号;可兼容转换的命名聚合组先按组策略选成员,再按成员的 adapter 能力派发。 - `/v1/chat/completions` 和 `/v1/messages` 没有原生路径。它们仍先变成 `ChatRequest`。选中 Codex 时,adapter 再把它建成 Responses 请求。 - 路由、权限、冷却、重试和日志仍在 executor。没有第二套直通执行器。 - 原生能力看接口,不看 provider 名字。gateway 里没有 `if provider == "codex"`。 @@ -29,9 +29,9 @@ last-updated: 2026-09-25 ```text /v1/messages Messages → ChatRequest ─────────────┐ /v1/chat/completions ChatRequest ────────────────────────┼─→ 选号 -/v1/responses 保留原文 ──→ 有原生 adapter? │ - ├─ 是:原文副本 + 本次执行参数 ──┤ - └─ 否:能转 Chat 才继续 ────────┘ +/v1/responses 保留原文,尝试 Chat 兼容转换 ─────────┘ + 普通请求:有原生候选时只选原生 + 命名聚合组:转换成功时不按协议重排成员 │ 选中的 adapter 决定上游协议 Codex:两条路径都打 Responses,并套同一套上游约束 @@ -46,14 +46,18 @@ last-updated: 2026-09-25 `HandleResponses` 有上限地读完 body,解析为 `translate.NativeResponsesRequest`。非法 JSON、非对象、尾随值、缺 `model` 或 `input`、以及 `previous_response_id` / `conversation` 直接拒绝。 -兼容转换 `Compat()` 会试一次,但失败不再挡住请求。随后: +网关先尝试兼容转换 `Compat()`;转换失败只限制候选协议,不直接挡住请求。随后: -1. 有实现 `NativeResponsesStreamer` 的候选账号时,只在这些账号里选。每次尝试从原文取一份副本,带上 `providers.RequestOptions`(本次上游模型、是否去掉 system/developer)。流式转发上游 SSE;`stream:false` 仍向上游要 SSE,再由 `translate.CollectResponses` 取出终态 `response` 对象。失败不降级到 Chat 重建。 -2. 没有原生账号,且原文能转成 `ChatRequest` 时,走原来的 `ChatStream` / `ChatNonStream`,网关再把结果拼回 Responses。 -3. 两边都不行,返回 `unsupported_request`。 +1. **普通请求**:有原生候选时只选原生账号,暂时满载或冷却并不会让它降级到兼容路径。没有原生候选且转换成功时,使用 `ChatStream` / `ChatNonStream`,由网关把结果编码回 Responses。 +2. **命名聚合组且转换成功**:与 Chat 使用同一组选成员规则,不为了协议优先级重排。每次尝试由选中成员决定:支持 `NativeResponsesStreamer` 就用原文,否则用兼容 `ChatRequest`。组允许回退时,两种路径共用同一个 `max_attempts` 派发预算。 +3. **转换失败**:无论是否命名聚合组,都只允许原生成员;若没有符合条件的原生候选,返回 `unsupported_request`,不丢字段重建请求。 + +每次原生尝试用原文副本和 `providers.RequestOptions`(本次上游模型、是否去掉 system/developer)。流式请求转发 SSE;`stream:false` 仍向上游要 SSE,再由 `translate.CollectResponses` 取出终态 `response` 对象。 现在只有 Codex 实现了这个接口。 +**English summary:** Ordinary Responses requests remain native-only when the route has a native-capable candidate. A named aggregation whose request can be translated to Chat selects members using its configured strategy, then chooses native or Chat dispatch per member. Both share the group’s attempt budget. Requests that cannot be translated to Chat still require a native member. + ### 2.2 `/v1/chat/completions` 和 `/v1/messages` 这两条没有原文保留,也没有原生分派。 @@ -70,7 +74,7 @@ last-updated: 2026-09-25 | 内容 | 现在的位置 | 约束 | | --- | --- | --- | | Responses 原文 | `translate.NativeResponsesRequest` | 自有 body。`Fields()` 每次返回副本,failover 不能改到下一次 | -| 兼容表示 | `translate.ChatRequest` | Chat/Messages 的唯一内容;Responses 仅在没有原生账号且转换成功时使用 | +| 兼容表示 | `translate.ChatRequest` | Chat/Messages 的唯一内容;Responses 转换成功且本次路由使用兼容 adapter 时使用 | | 本次执行决定 | `providers.RequestOptions` | 显式参数,不放进 context。目前是上游模型 id 和 `DropSystemPrompt` | | 原生能力 | `NativeResponsesStreamer.ResponsesStream` | 入参是原文指针和 `RequestOptions`,返回上游 Responses SSE | | 事件判定 | `translate.ParseResponsesEvent` | relay 和 collector 共用。`response.failed` 是终态错误,不再补第二条错误帧 | @@ -115,9 +119,10 @@ Chat/Messages 翻译路径还会先做消息到 item 的重建(tool 结果变 - 原生流式转发上游事件,不压成 chat delta。namespace 工具名在响应里还原。 - 原生非流式只取 `response.completed` 或 `response.incomplete` 上的完整 `response` 对象,不经 `ChatOutcome`。 - `response.failed` 记为错误。事件已经转给客户端时,不再追加第二条错误帧。 -- 原生候选耗尽后不自动改走有损的 Chat 重建。没有原生候选且兼容转换也失败时,请求直接失败。 +- 普通请求的原生候选耗尽后不自动走兼容路径。只有转换成功的命名聚合组可以在同一派发预算内按配置回退到兼容成员,仍遵守上游明确禁止回退的错误。 - 协议不兼容不给账号加冷却。上游的限流、认证和可用性错误仍走原来的分类。 -- 响应已经开始写给客户端之后不换上游再拼一段。 +- 流式请求在接受首个有效上游事件后不换上游再拼一段。Chat 的早期 heartbeat 注释不是上游事件,只保活、不公布尚未确定的账号。 +- 如果客户端已取消,且流只给出 EOF 或无法确定来源的读取错误,不将其计作账号故障;已确认的终态成功或明确的上游错误保留原结果。 - 原文、加密内容和凭证不进默认日志。 fake 测试证明字段按上面的清单改写、其余成员留下来、失败终态不会被当成成功。它不证明某个真实 ChatGPT 账号接受全部保留字段,也不证明加密 reasoning 可以跨账号回放。 diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 4fbb75e60..ffc430776 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -51,7 +51,7 @@ func TestCORSHeadersOnUnauthorizedChat(t *testing.T) { if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" { t.Fatalf("allow-origin=%q", got) } - if got := rec.Header().Get("Access-Control-Expose-Headers"); !strings.Contains(got, "X-Request-Id") { + if got := rec.Header().Get("Access-Control-Expose-Headers"); !strings.Contains(got, "X-Request-Id") || !strings.Contains(got, "Retry-After") { t.Fatalf("expose-headers=%q", got) } } diff --git a/internal/api/chat_usage_test.go b/internal/api/chat_usage_test.go index 9d2138d5a..dfa7bea20 100644 --- a/internal/api/chat_usage_test.go +++ b/internal/api/chat_usage_test.go @@ -139,7 +139,7 @@ func TestBuildChatUsagePreservesZeroPromptCacheTokens(t *testing.T) { func TestStreamFlushWriterFlushesEachWrite(t *testing.T) { recorder := httptest.NewRecorder() - writer := streamFlushWriter{W: recorder, F: recorder} + writer := streamFlushWriter{W: recorder, RC: http.NewResponseController(recorder)} if _, err := writer.Write([]byte("data: test\n\n")); err != nil { t.Fatal(err) } @@ -229,15 +229,15 @@ func TestRelayOpenAIStreamClassifiesAndSuppressesStructuredError(t *testing.T) { if !errors.As(err, &execErr) || execErr == nil { t.Fatalf("error=%T %v", err, err) } - if execErr.Classified.Kind != accounts.KindRateLimit || execErr.Classified.Code != "RESOURCE_EXHAUSTED" || execErr.Classified.RetryAfter != 30*time.Second { + if execErr.Classified.Kind != accounts.KindRateLimit || execErr.Classified.Code != "RESOURCE_EXHAUSTED" || execErr.Classified.RetryAfter != time.Second || execErr.Classified.Cooldown != 30*time.Second { t.Fatalf("execution error=%+v", execErr.Classified) } output := recorder.Body.String() if strings.Contains(output, "event: error") { t.Fatalf("internal error event leaked to client: %s", output) } - if !strings.Contains(output, `"message":"provider busy"`) || !strings.Contains(output, `"code":"RESOURCE_EXHAUSTED"`) { - t.Fatalf("structured error was not emitted: %s", output) + if !strings.Contains(output, `"message":"upstream rate limit exceeded"`) || !strings.Contains(output, `"code":"RESOURCE_EXHAUSTED"`) { + t.Fatalf("structured error was not emitted safely: %s", output) } } diff --git a/internal/api/compat_test.go b/internal/api/compat_test.go index 8060ead51..6007be141 100644 --- a/internal/api/compat_test.go +++ b/internal/api/compat_test.go @@ -381,7 +381,7 @@ func TestResponsesStreamKeepsDistinctFunctionCallIDs(t *testing.T) { }) defer closeServer() - request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"input":"hi"}`)) + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"input":"hi","tools":[{"type":"function","name":"first","parameters":{"type":"object"}},{"type":"function","name":"second","parameters":{"type":"object"}}]}`)) recorder := httptest.NewRecorder() server.handleResponses(recorder, request) body := recorder.Body.String() @@ -409,7 +409,7 @@ func TestResponsesNonStreamRestoresCustomToolCall(t *testing.T) { }) defer closeServer() - request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","input":"hi"}`)) + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","input":"hi","tools":[{"type":"custom","name":"exec","description":"run a command"}]}`)) recorder := httptest.NewRecorder() server.handleResponses(recorder, request) if recorder.Code != http.StatusOK { @@ -440,7 +440,7 @@ func TestResponsesStreamWritesCustomToolCallEvents(t *testing.T) { }) defer closeServer() - request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"input":"hi"}`)) + request := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"input":"hi","tools":[{"type":"custom","name":"exec","description":"run a command"}]}`)) recorder := httptest.NewRecorder() server.handleResponses(recorder, request) body := recorder.Body.String() diff --git a/internal/api/entry_matrix_test.go b/internal/api/entry_matrix_test.go new file mode 100644 index 000000000..2f9325bc6 --- /dev/null +++ b/internal/api/entry_matrix_test.go @@ -0,0 +1,72 @@ +package api + +import ( + "net/http" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/endpoint" +) + +// The three public protocols share one entry rule: one JSON object followed by +// EOF. Rejections must also be visible in the request log, not only in the +// response body. +func TestEntryBodyMatrixRejectsTrailingJSONAndLogs(t *testing.T) { + cases := []struct { + name string + path string + body string + }{ + { + name: "chat trailing object", + path: endpoint.ChatCompletionsPath, + body: `{"model":"glm-5.2","messages":[{"role":"user","content":"hello"}]}{"extra":true}`, + }, + { + name: "messages trailing object", + path: endpoint.MessagesPath, + body: `{"model":"glm-5.2","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}{"extra":true}`, + }, + { + name: "responses trailing object", + path: endpoint.ResponsesPath, + body: `{"model":"glm-5.2","input":"hello"}{"extra":true}`, + }, + { + name: "chat truncated body", + path: endpoint.ChatCompletionsPath, + body: `{"model":"glm-5.2"`, + }, + { + name: "messages truncated body", + path: endpoint.MessagesPath, + body: `{"model":"glm-5.2","max_tokens":32`, + }, + { + name: "responses truncated body", + path: endpoint.ResponsesPath, + body: `{"model":"glm-5.2","input":"hello"`, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + server := newS01HTTPServer(t) + response := serveS01(t, server, http.MethodPost, tc.path, tc.body, "secret") + if response.Code != http.StatusBadRequest { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), "extra") { + t.Fatalf("rejection leaked parser detail: %s", response.Body.String()) + } + requestID := response.Header().Get("X-Request-Id") + if requestID == "" { + t.Fatal("rejection did not expose a request id") + } + entry := waitForRequestLog(t, server.Recorder.Store(), requestID, accounts.RequestStatusError) + if entry.ErrorKind != accounts.KindInvalidRequest { + t.Fatalf("rejection log = %+v", entry) + } + }) + } +} diff --git a/internal/api/logs_api_key_test.go b/internal/api/logs_api_key_test.go index 6df62e616..c81e01039 100644 --- a/internal/api/logs_api_key_test.go +++ b/internal/api/logs_api_key_test.go @@ -40,10 +40,10 @@ func keyedFixture(t *testing.T, server *Server, store *sqlstore.Store) accounts. server.Handler().ServeHTTP(rec, req) return rec } - if rec := send(stored.Secret, `{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}]}`); rec.Code != http.StatusOK { + if rec := send(stored.Secret, `{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]}`); rec.Code != http.StatusOK { t.Fatalf("keyed call status=%d body=%s", rec.Code, rec.Body.String()) } - if rec := send("secret", `{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}]}`); rec.Code != http.StatusOK { + if rec := send("secret", `{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]}`); rec.Code != http.StatusOK { t.Fatalf("console call status=%d body=%s", rec.Code, rec.Body.String()) } return stored diff --git a/internal/api/s01_protocol_contract_test.go b/internal/api/s01_protocol_contract_test.go index fc43095d4..0efff18bc 100644 --- a/internal/api/s01_protocol_contract_test.go +++ b/internal/api/s01_protocol_contract_test.go @@ -80,7 +80,7 @@ func TestOpenAINonStreamContractThroughHandler(t *testing.T) { server.Auth = auth.NewVerifier("secret", store) server.RebuildHTTP() - req := httptest.NewRequest(http.MethodPost, endpoint.ChatCompletionsPath, strings.NewReader(`{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}]}`)) + req := httptest.NewRequest(http.MethodPost, endpoint.ChatCompletionsPath, strings.NewReader(`{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]}`)) req.Header.Set("Authorization", "Bearer secret") req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() @@ -147,7 +147,7 @@ func TestOpenAIStreamAndConsoleChatShareHandler(t *testing.T) { server.RebuildHTTP() for _, path := range []string{endpoint.ChatCompletionsPath, "/api/chat"} { - req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"qoder/glm-5.2","stream":true,"messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]}`)) req.Header.Set("Authorization", "Bearer secret") req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() @@ -247,7 +247,7 @@ func TestPinnedMissingAccountFallsBackToPool(t *testing.T) { _, _ = io.WriteString(w, openaiNonStreamBody()) }) defer closeServer() - req := httptest.NewRequest(http.MethodPost, endpoint.ChatCompletionsPath, strings.NewReader(`{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}]}`)) + req := httptest.NewRequest(http.MethodPost, endpoint.ChatCompletionsPath, strings.NewReader(`{"model":"qoder/glm-5.2","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}]}`)) req.Header.Set("X-Qoder-Account", "missing") rec := httptest.NewRecorder() server.handleChatCompletions(rec, req) @@ -312,7 +312,7 @@ func (chat *canceledStreamChat) ChatStream(context.Context, string, translate.Ch }, providers.ResolvedChat{}, nil } -func TestStreamBodyCancellationKeepsAccountHealthyAcrossEndpoints(test *testing.T) { +func TestStreamBodyUpstreamTimeoutRecordsAccountFailure(test *testing.T) { for _, cause := range []error{context.Canceled, context.DeadlineExceeded} { for _, path := range []string{endpoint.ChatCompletionsPath, "/api/chat", endpoint.MessagesPath, endpoint.ResponsesPath} { test.Run(cause.Error()+path, func(test *testing.T) { @@ -344,12 +344,14 @@ func TestStreamBodyCancellationKeepsAccountHealthyAcrossEndpoints(test *testing. test.Fatalf("context=%v status=%d calls=%d body=%s", request.Context().Err(), response.Code, chat.calls.Load(), response.Body.String()) } item, _ := server.Pool.ByID(account.ID) - if item.LastKind != "" || !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 { - test.Fatalf("canceled stream polluted account state: %+v", item) + if item.LastKind != accounts.KindUnavailable || len(item.ModelDownUntil) != 0 { + // A stream timeout is recorded as upstream evidence but carries + // no cooldown: the account may be perfectly healthy next time. + test.Fatalf("live upstream stream failure was not recorded: %+v", item) } - entry := waitForRequestLog(test, server.Recorder.Store(), response.Header().Get("X-Request-Id"), accounts.RequestStatusCanceled) - if entry.ErrorKind != accounts.KindCanceled { - test.Fatalf("canceled stream log=%+v", entry) + entry := waitForRequestLog(test, server.Recorder.Store(), response.Header().Get("X-Request-Id"), accounts.RequestStatusError) + if entry.ErrorKind != accounts.KindUnavailable { + test.Fatalf("stream timeout log=%+v", entry) } }) } diff --git a/internal/app/aggregation_catalog_contract_test.go b/internal/app/aggregation_catalog_contract_test.go new file mode 100644 index 000000000..852c68d6e --- /dev/null +++ b/internal/app/aggregation_catalog_contract_test.go @@ -0,0 +1,172 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "net/http/httptest" + "slices" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/control" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type syntheticNamedGroupFixture struct { + control.AggregationStore + groups []accounts.Aggregation +} + +func (f syntheticNamedGroupFixture) ListAggregations(context.Context) ([]accounts.Aggregation, error) { + return f.groups, nil +} + +func syntheticGroupApp(groups []accounts.Aggregation, cross bool, items ...executor.Item) *App { + pool := executor.NewPool(nil, nil) + for _, item := range items { + pool.Upsert(item) + } + a := &App{ + Pool: pool, Executor: executor.NewChatExecutor(pool, ""), + Control: &control.Services{Aggregations: control.NewAggregations(syntheticNamedGroupFixture{groups: groups})}, + } + a.CrossProviderModelPool.Store(cross) + return a +} + +func syntheticListedIDs(t *testing.T, a *App, identity auth.Identity, rows []map[string]any) []string { + t.Helper() + h := a.newGateway() + h.Models = func(bool, string) ([]map[string]any, error) { return rows, nil } + h.DecorateModels = nil + req := httptest.NewRequest("GET", "/v1/models", nil).WithContext(auth.WithIdentity(t.Context(), identity)) + rec := httptest.NewRecorder() + h.HandleModels(rec, req) + var response struct { + Data []struct { + ID string `json:"id"` + } `json:"data"` + } + if rec.Code != 200 { + t.Fatalf("list: HTTP %d: %s", rec.Code, rec.Body.String()) + } + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { + t.Fatalf("decode model list: %v", err) + } + var ids []string + for _, x := range response.Data { + ids = append(ids, x.ID) + } + return ids +} + +func syntheticPrepare(t *testing.T, a *App, identity auth.Identity, model string) (executor.PreparedRequest, error) { + t.Helper() + return a.Executor.Prepare(executor.PrepareInput{ + Context: t.Context(), Request: translate.ChatRequest{Model: model}, Identity: identity, + CrossProviderPool: a.CrossProviderModelPool.Load(), ModelAggregation: identity.ModelAggregation, Aggregations: a.Control.Aggregations, + }) +} + +func TestAggregationModelCatalogDoesNotReadvertiseShadowedAlias(t *testing.T) { + group := accounts.Aggregation{ID: "logical", Enabled: true, Members: []accounts.AggregationMember{{Provider: "workbuddy", Model: "hidden-member"}}} + a := syntheticGroupApp([]accounts.Aggregation{group}, true, executor.Item{ + ID: "allowed", Provider: "qoder", Runtime: "in_process", Models: []string{"real"}, + ModelAliases: map[string]string{"logical": "real", "independent": "real"}, + }) + identity := auth.Identity{AllowedProviders: []string{"qoder"}, ModelAggregation: true} + ids := syntheticListedIDs(t, a, identity, []map[string]any{{"id": "real", "provider": "qoder"}}) + _, err := syntheticPrepare(t, a, identity, "logical") + var prep *executor.PrepareError + if !errors.As(err, &prep) || prep.Code != "model_not_available" { + t.Fatalf("unexpected prepare: %v", err) + } + if !slices.Equal(ids, []string{"independent"}) { + t.Fatalf("listed uncallable same-name alias %v; prepare gives %s", ids, prep.Code) + } +} + +func TestAggregationModelCatalogKeepsNamespacedEnabledMember(t *testing.T) { + member := accounts.AggregationMember{Provider: "command", Model: "alpha/shared"} + a := syntheticGroupApp([]accounts.Aggregation{{ID: "logical", Enabled: true, Members: []accounts.AggregationMember{member}}}, true, executor.Item{ID: "allowed", Provider: "command", Runtime: "in_process", Models: []string{"alpha/shared"}, ModelsRestricted: true, EnabledModels: []string{"alpha/shared"}}) + identity := auth.Identity{AllowedProviders: []string{"command"}} + prepared, err := syntheticPrepare(t, a, identity, "logical") + if err != nil || !a.Pool.HasAggregateRoute(prepared.Route.AggregatePlan, executor.RouteQuery{AllowedProviders: identity.AllowedProviders}) { + t.Fatalf("expected usable route: %v", err) + } + ids := syntheticListedIDs(t, a, identity, []map[string]any{{"id": "alpha/shared", "provider": "command"}}) + if !slices.Contains(ids, "logical") { + t.Fatalf("usable named group missing with full-ID allowlist: %v", ids) + } +} + +func TestAggregationModelCatalogDoesNotBorrowUnallowedMergedRegion(t *testing.T) { + member := accounts.AggregationMember{Provider: "workbuddy", Region: "cn", Model: "shared"} + a := syntheticGroupApp([]accounts.Aggregation{{ID: "logical", Enabled: true, Members: []accounts.AggregationMember{member}}}, true, + executor.Item{ID: "cn", Provider: "workbuddy", Region: "cn", Runtime: "in_process", Models: []string{"shared"}}, + executor.Item{ID: "global", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"shared"}}) + rows := []map[string]any{{"id": "shared", "provider": "workbuddy", "regions": []string{"cn", "global"}}} + for _, aggregationKey := range []bool{false, true} { + for _, region := range []string{"cn", "global"} { + identity := auth.Identity{AllowedProviders: []string{"workbuddy:" + region}, ModelAggregation: aggregationKey} + want := region == "cn" + prepared, err := syntheticPrepare(t, a, identity, "logical") + if err != nil || a.Pool.HasAggregateRoute(prepared.Route.AggregatePlan, executor.RouteQuery{AllowedProviders: identity.AllowedProviders}) != want { + t.Fatalf("key=%+v: expected route=%v, prepare err=%v", identity, want, err) + } + ids := syntheticListedIDs(t, a, identity, rows) + if slices.Contains(ids, "logical") != want { + t.Fatalf("key=%+v: listed %v, want logical=%v", identity, ids, want) + } + } + } +} + +func TestAggregationModelCatalogPrefixesForeignNamespaceWithGlobalPoolOff(t *testing.T) { + a := syntheticGroupApp(nil, false, executor.Item{ID: "command", Provider: "command", Runtime: "in_process", Models: []string{"alpha/shared"}}) + identity := auth.Identity{AllowedProviders: []string{"command"}} + ids := syntheticListedIDs(t, a, identity, []map[string]any{{"id": "alpha/shared", "provider": "command"}}) + if !slices.Equal(ids, []string{"command/alpha/shared"}) { + t.Fatalf("want provider-prefixed full name, got %v", ids) + } + if _, err := syntheticPrepare(t, a, identity, ids[0]); err != nil { + t.Fatalf("global pool off advertised rejected ID %q: %v", ids[0], err) + } +} + +func TestAggregationModelCatalogDoesNotBorrowDifferentAccountForPin(t *testing.T) { + member := accounts.AggregationMember{Provider: "workbuddy", AccountID: "cn-only", Model: "shared"} + a := syntheticGroupApp([]accounts.Aggregation{{ID: "logical", Enabled: true, Members: []accounts.AggregationMember{member}}}, true, + executor.Item{ID: "cn-only", Provider: "workbuddy", Region: "cn", Runtime: "in_process", Models: []string{"shared"}}, + executor.Item{ID: "global", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"shared"}}) + identity := auth.Identity{AllowedProviders: []string{"workbuddy:global"}, ModelAggregation: true} + prepared, err := syntheticPrepare(t, a, identity, "logical") + if err != nil || a.Pool.HasAggregateRoute(prepared.Route.AggregatePlan, executor.RouteQuery{AllowedProviders: identity.AllowedProviders}) { + t.Fatalf("expected no granted pinned route: %v", err) + } + ids := syntheticListedIDs(t, a, identity, []map[string]any{{"id": "shared", "provider": "workbuddy", "regions": []string{"global"}}}) + if slices.Contains(ids, "logical") { + t.Fatalf("even a global-only row advertises a group pinned to an ungranted cn account: %v", ids) + } +} + +func TestAggregationModelCatalogListsValidMemberAliasForAggregationKey(t *testing.T) { + const childID = "team/child" + member := accounts.AggregationMember{Provider: "workbuddy", Region: "cn", Model: "member-alias"} + a := syntheticGroupApp([]accounts.Aggregation{ + {ID: "team/root", Enabled: true, Document: `{"steps":[{"kind":"group","aggregation_id":"team/child"}]}`}, + {ID: childID, Enabled: true, Members: []accounts.AggregationMember{member}}, + }, true, executor.Item{ID: "cn", Provider: "workbuddy", Region: "cn", Runtime: "in_process", Models: []string{"real"}, ModelAliases: map[string]string{"member-alias": "real"}}) + identity := auth.Identity{AllowedProviders: []string{"workbuddy:cn"}, ModelAggregation: true} + prepared, err := syntheticPrepare(t, a, identity, "team/root") + if err != nil || !a.Pool.HasAggregateRoute(prepared.Route.AggregatePlan, executor.RouteQuery{AllowedProviders: identity.AllowedProviders}) { + t.Fatalf("expected available nested member alias: %v", err) + } + ids := syntheticListedIDs(t, a, identity, []map[string]any{{"id": "real", "provider": "workbuddy", "regions": []string{"cn"}}}) + if !slices.Contains(ids, "team/root") { + t.Fatalf("routable named group based on a member alias is not advertised: %v", ids) + } +} diff --git a/internal/app/aggregation_models.go b/internal/app/aggregation_models.go index b38da21bb..f4e0278e4 100644 --- a/internal/app/aggregation_models.go +++ b/internal/app/aggregation_models.go @@ -3,7 +3,6 @@ package app import ( "context" "net/http" - "sort" "github.com/caigee-cmd/cli2api/internal/control" ) @@ -21,37 +20,9 @@ func (a *App) aggregationKeyModels(ctx context.Context, r *http.Request, models if !identity.ModelAggregation { return models } - aliases := control.AggregateModelEntries(models, identity, a.accountModelAllows()) var lister control.AggregationLister - if a.Control != nil { + if a.Control != nil && a.Control.Aggregations != nil { lister = a.Control.Aggregations } - merged := control.MergeAggregationModels(ctx, lister, models) - out := make([]map[string]any, 0, len(merged)+len(aliases)) - seen := make(map[string]bool, len(merged)+len(aliases)) - for _, model := range merged { - if provider, _ := model["provider"].(string); provider != "aggregation" { - continue - } - id, _ := model["id"].(string) - if id == "" || seen[id] { - continue - } - seen[id] = true - out = append(out, model) - } - for _, model := range aliases { - id, _ := model["id"].(string) - if id == "" || seen[id] { - continue - } - seen[id] = true - out = append(out, model) - } - sort.SliceStable(out, func(i, j int) bool { - left, _ := out[i]["id"].(string) - right, _ := out[j]["id"].(string) - return left < right - }) - return out + return control.AggregationKeyModelEntries(ctx, lister, models, identity, a.accountModelAllows()) } diff --git a/internal/app/gateway.go b/internal/app/gateway.go index cfb361b3f..f45585554 100644 --- a/internal/app/gateway.go +++ b/internal/app/gateway.go @@ -4,6 +4,7 @@ import ( "context" "net/http" + "github.com/caigee-cmd/cli2api/internal/auth" "github.com/caigee-cmd/cli2api/internal/control" apigateway "github.com/caigee-cmd/cli2api/internal/gateway" ) @@ -30,10 +31,11 @@ func (a *App) newGateway() *apigateway.Handler { return a.fetchDisplayModels(refresh, accountID, control.CatalogModeMerge) }, MergeAggregationModels: func(ctx context.Context, models []map[string]any) []map[string]any { - if a.Control == nil { + if a.Control == nil || a.Control.Aggregations == nil { return models } - return control.MergeAggregationModels(ctx, a.Control.Aggregations, models) + identity, _ := auth.IdentityFrom(ctx) + return control.MergeAggregationModelsForIdentity(ctx, a.Control.Aggregations, models, identity, a.accountModelAllows()) }, AggregationKeyModels: a.aggregationKeyModels, CatalogStatus: func() map[string]any { @@ -56,7 +58,7 @@ func (a *App) newGateway() *apigateway.Handler { } if a.Manager != nil { h.Catalogs = a.Manager - h.AfterAccountUse = a.Manager.RefreshFEFOQuotaAfterUse + h.AfterAccountUse = a.Manager.RefreshRouteQuotaAfterUse } if a.Recorder != nil { h.Logs = a.Recorder diff --git a/internal/app/model_catalog.go b/internal/app/model_catalog.go index 738ff64e5..bdb0fc8ba 100644 --- a/internal/app/model_catalog.go +++ b/internal/app/model_catalog.go @@ -1,9 +1,11 @@ package app import ( + "net/http" + "github.com/caigee-cmd/cli2api/internal/control" "github.com/caigee-cmd/cli2api/internal/endpoint" - "net/http" + "github.com/caigee-cmd/cli2api/internal/executor" ) func (a *App) RequestedAccount(r *http.Request) string { return endpoint.RequestedAccount(r) } @@ -17,9 +19,6 @@ func (a *App) filterModelsForIdentity(r *http.Request, models []map[string]any) } models = control.FilterModelsByAccountAllow(models, identity, allow) models = control.FilterModelsForIdentity(identity, models) - if !identity.ModelAggregation { - models = control.AggregateModelEntries(models, identity, allow) - } // Aggregation keys get their final provider-neutral list from // aggregationKeyModels after this filter: configured logical models first, // then account aliases. Returning the filtered catalog here keeps every @@ -36,17 +35,16 @@ func (a *App) accountModelAllows() []control.AccountModelAllow { return nil } items := a.Pool.Items() - if len(items) == 0 { - return nil - } out := make([]control.AccountModelAllow, 0, len(items)) for _, item := range items { out = append(out, control.AccountModelAllow{ + AccountID: item.ID, Provider: item.Provider, Region: item.Region, ModelsRestricted: item.ModelsRestricted, EnabledModels: item.EnabledModels, Aliases: item.ModelAliases, + CanRouteModel: func(model string) bool { return executor.ItemCouldServeModel(item, model) }, }) } return out diff --git a/internal/console/aggregation_preview_test.go b/internal/console/aggregation_preview_test.go new file mode 100644 index 000000000..16e3e6f7a --- /dev/null +++ b/internal/console/aggregation_preview_test.go @@ -0,0 +1,94 @@ +package console + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/control" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +func TestHandleAggregationPreviewReturnsOneCurrentCandidate(t *testing.T) { + const nestedDoc = `{"version":1,"steps":[{"id":"z","kind":"member","provider":"qoder","model":"nested-z"},{"id":"a","kind":"member","provider":"qoder","model":"nested-a"}]}` + store := &aggregationPreviewStore{ + rows: map[string]accounts.Aggregation{ + "inner": {ID: "inner", Enabled: true, Strategy: accounts.AggregationPriority, Document: nestedDoc}, + }, + } + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "z-account", Provider: "qoder", Models: []string{"nested-z"}}) + pool.Upsert(executor.Item{ID: "a-account", Provider: "qoder", Models: []string{"nested-a"}}) + pool.Upsert(executor.Item{ID: "fallback-account", Provider: "workbuddy", Models: []string{"fallback"}}) + h := &Handler{ + Control: &control.Services{Aggregations: control.NewAggregations(store)}, + Executor: &executor.ChatExecutor{Pool: pool}, + Pool: pool, + } + body := `{"id":"outer","strategy":"priority","document":{"version":1,"steps":[{"id":"group","kind":"group","aggregation_id":"inner"},{"id":"fallback","kind":"member","provider":"workbuddy","model":"fallback"}]},"message":""}` + req := httptest.NewRequest(http.MethodPost, "/api/aggregations/preview", strings.NewReader(body)) + rec := httptest.NewRecorder() + h.HandleAggregationPreview(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + var response struct { + Path string `json:"path"` + Attempts []executor.AggregatePreviewCandidate `json:"attempts"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + if len(response.Attempts) != 1 { + t.Fatalf("attempts=%+v, want only one current candidate", response.Attempts) + } + got := response.Attempts[0] + if got.Provider != "qoder" || got.Model != "nested-z" || got.Status != "candidate" { + t.Fatalf("candidate=%+v, want first nested priority winner", got) + } + if strings.Contains(rec.Body.String(), "z-account") { + t.Fatalf("preview must not expose account ID: %s", rec.Body.String()) + } +} + +type aggregationPreviewStore struct { + rows map[string]accounts.Aggregation +} + +func (s *aggregationPreviewStore) InsertAggregation(_ context.Context, agg accounts.Aggregation) (accounts.Aggregation, error) { + s.rows[agg.ID] = agg + return agg, nil +} + +func (s *aggregationPreviewStore) SaveAggregation(_ context.Context, agg accounts.Aggregation) (accounts.Aggregation, error) { + s.rows[agg.ID] = agg + return agg, nil +} + +func (s *aggregationPreviewStore) ListAggregations(context.Context) ([]accounts.Aggregation, error) { + rows := make([]accounts.Aggregation, 0, len(s.rows)) + for _, agg := range s.rows { + rows = append(rows, agg) + } + return rows, nil +} + +func (s *aggregationPreviewStore) GetAggregation(_ context.Context, id string) (accounts.Aggregation, error) { + agg, ok := s.rows[id] + if !ok { + return accounts.Aggregation{}, accounts.ErrAggregationNotFound + } + return agg, nil +} + +func (s *aggregationPreviewStore) DeleteAggregation(_ context.Context, id string) error { + if _, ok := s.rows[id]; !ok { + return accounts.ErrAggregationNotFound + } + delete(s.rows, id) + return nil +} diff --git a/internal/console/aggregations.go b/internal/console/aggregations.go index 6a5ca7842..c25652e34 100644 --- a/internal/console/aggregations.go +++ b/internal/console/aggregations.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "net/http" + "net/url" "strings" "github.com/caigee-cmd/cli2api/internal/accounts" @@ -71,25 +72,25 @@ func (h *Handler) HandleAggregationPreview(w http.ResponseWriter, r *http.Reques } catalog = loaded } - labels := map[string]string{} - if h.Executor != nil && strings.TrimSpace(input.Message) != "" { - targets, err := accounts.ClassifierTargets(agg.ID, agg.Document, catalog) - if err != nil { - writeErr(w, http.StatusBadRequest, "invalid_request", err.Error()) - return - } - labels = h.Executor.ClassifyIntent(r.Context(), targets, input.Message) + var plan *executor.AggregatePlan + var path string + var err error + if h.Executor != nil { + plan, path, err = h.Executor.CompileAggregationPreview(r.Context(), agg, catalog, input.Message) + } else { + plan, path, err = executor.CompileAggregatePreview(agg, catalog, input.Message, nil) } - compiled, seats, path, err := accounts.CompilePipeline(agg, catalog, input.Message, labels, nil) if err != nil { writeErr(w, http.StatusBadRequest, "invalid_request", err.Error()) return } - plan := executor.NewAggregatePlan(compiled) - plan.Seats = seats + attempts := make([]executor.AggregatePreviewCandidate, 0, 1) + if candidate, ok := h.Pool.PreviewAggregate(plan, executor.RouteQuery{PublicModel: plan.ID}); ok { + attempts = append(attempts, candidate) + } writeJSON(w, http.StatusOK, map[string]any{ "path": path, - "attempts": executor.ExplainSeats(h.Pool, plan), + "attempts": attempts, }) } @@ -154,7 +155,11 @@ func (h *Handler) HandleAggregations(w http.ResponseWriter, r *http.Request) { } func (h *Handler) HandleAggregationByID(w http.ResponseWriter, r *http.Request) { - id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/aggregations/"), "/") + id, err := aggregationIDFromRequestPath(r) + if err != nil { + writeErr(w, http.StatusBadRequest, "invalid_request", "invalid aggregation id path") + return + } if id == "" { writeErr(w, http.StatusNotFound, "aggregation_not_found", "aggregation id required") return @@ -222,3 +227,24 @@ func (h *Handler) HandleAggregationByID(w http.ResponseWriter, r *http.Request) writeErr(w, http.StatusMethodNotAllowed, "method_not_allowed", "GET, PATCH, or DELETE only") } } + +// aggregationIDFromRequestPath preserves encoded slashes in IDs. Historically, +// unencoded leading/trailing slashes around the path suffix were trimmed, so keep +// that convenience while requiring encodeURIComponent-style escaping when a +// stored ID itself begins or ends with '/'. +func aggregationIDFromRequestPath(r *http.Request) (string, error) { + const prefix = "/api/aggregations/" + if r == nil || r.URL == nil { + return "", errors.New("aggregation request path is missing") + } + escapedPath := r.URL.EscapedPath() + if !strings.HasPrefix(escapedPath, prefix) { + return "", errors.New("aggregation request path has an invalid prefix") + } + rawID := strings.Trim(strings.TrimPrefix(escapedPath, prefix), "/") + id, err := url.PathUnescape(rawID) + if err != nil { + return "", err + } + return id, nil +} diff --git a/internal/console/aggregations_test.go b/internal/console/aggregations_test.go new file mode 100644 index 000000000..768c4c2cb --- /dev/null +++ b/internal/console/aggregations_test.go @@ -0,0 +1,55 @@ +package console + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/control" +) + +func TestHandleAggregationByIDPreservesEncodedBoundarySlashes(t *testing.T) { + const id = "/legacy/review/" + // Simulate a pre-existing row. The current schema has no ID CHECK constraint, + // even though current create validation rejects empty path segments. + store := &aggregationPreviewStore{rows: map[string]accounts.Aggregation{id: {ID: id, Name: "legacy"}}} + h := &Handler{Control: &control.Services{Aggregations: control.NewAggregations(store)}} + encodedPath := "/api/aggregations/%2Flegacy%2Freview%2F" + + get := httptest.NewRecorder() + h.HandleAggregationByID(get, httptest.NewRequest(http.MethodGet, encodedPath, nil)) + if get.Code != http.StatusOK || !strings.Contains(get.Body.String(), id) { + t.Fatalf("GET status=%d body=%s", get.Code, get.Body.String()) + } + + patch := httptest.NewRecorder() + h.HandleAggregationByID(patch, httptest.NewRequest(http.MethodPatch, encodedPath, strings.NewReader("{\"name\":\"patched\"}"))) + if patch.Code != http.StatusOK { + t.Fatalf("PATCH status=%d body=%s", patch.Code, patch.Body.String()) + } + if got := store.rows[id].Name; got != "patched" { + t.Fatalf("updated aggregation name=%q, want patched", got) + } + + del := httptest.NewRecorder() + h.HandleAggregationByID(del, httptest.NewRequest(http.MethodDelete, encodedPath, nil)) + if del.Code != http.StatusNoContent { + t.Fatalf("DELETE status=%d body=%s", del.Code, del.Body.String()) + } + if _, ok := store.rows[id]; ok { + t.Fatal("encoded boundary-slash ID was not deleted") + } +} + +func TestHandleAggregationByIDKeepsUnencodedTrailingSlashConvenience(t *testing.T) { + const id = "team/review" + store := &aggregationPreviewStore{rows: map[string]accounts.Aggregation{id: {ID: id, Name: "legacy"}}} + h := &Handler{Control: &control.Services{Aggregations: control.NewAggregations(store)}} + rec := httptest.NewRecorder() + h.HandleAggregationByID(rec, httptest.NewRequest(http.MethodGet, "/api/aggregations/team/review/", nil)) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), id) { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } +} diff --git a/internal/console/live.go b/internal/console/live.go index cb76b5abc..944eadb29 100644 --- a/internal/console/live.go +++ b/internal/console/live.go @@ -24,14 +24,14 @@ type LiveAccount struct { // card. Stage-1 UI still mocks jobs/depth; Stage-3 swaps workers/rate_limits/ // sticky onto this shape without a parallel /api/inflight*. type LiveWorker struct { - ID string `json:"id"` - Name string `json:"name"` - Provider string `json:"provider"` - Busy bool `json:"busy"` - InFlight int `json:"in_flight"` - MaxInFlight int `json:"max_inflight"` - Enabled bool `json:"enabled"` - RateLimited bool `json:"rate_limited"` + ID string `json:"id"` + Name string `json:"name"` + Provider string `json:"provider"` + Busy bool `json:"busy"` + InFlight int `json:"in_flight"` + MaxInFlight int `json:"max_inflight"` + Enabled bool `json:"enabled"` + RateLimited bool `json:"rate_limited"` // Progress is a legacy occupancy ratio (in_flight/max_inflight). The // Overview card no longer treats it as % toward completion — busy slots // use an indeterminate shimmer; keep the field for API compat. diff --git a/internal/console/live_test.go b/internal/console/live_test.go index 781d3cfab..90dc41e6b 100644 --- a/internal/console/live_test.go +++ b/internal/console/live_test.go @@ -18,15 +18,15 @@ func TestBuildLiveSnapshot(t *testing.T) { views := []accounts.AccountView{ { - Account: accounts.Account{ID: "a", Name: "wb-a1", Provider: "workbuddy", Enabled: true, MaxInFlight: 4}, - InFlight: 4, - InFlightSince: now.Add(-12 * time.Second).Format(time.RFC3339), + Account: accounts.Account{ID: "a", Name: "wb-a1", Provider: "workbuddy", Enabled: true, MaxInFlight: 4}, + InFlight: 4, + InFlightSince: now.Add(-12 * time.Second).Format(time.RFC3339), }, { - Account: accounts.Account{ID: "b", Name: "wb-a2", Provider: "workbuddy", Enabled: true}, - InFlight: 1, // default max 4 - DownUntil: coolingUntil, - ModelCooldowns: map[string]string{"glm-5": modelUntil, "stale": expiredUntil}, + Account: accounts.Account{ID: "b", Name: "wb-a2", Provider: "workbuddy", Enabled: true}, + InFlight: 1, // default max 4 + DownUntil: coolingUntil, + ModelCooldowns: map[string]string{"glm-5": modelUntil, "stale": expiredUntil}, }, {Account: accounts.Account{ID: "c", Enabled: false, MaxInFlight: 8}}, } @@ -116,7 +116,7 @@ func TestBuildLiveSnapshotLastErrorKind(t *testing.T) { Account: accounts.Account{ ID: "ok1", Name: "ok-slot", Provider: "qoder", Enabled: true, }, - InFlight: 1, + InFlight: 1, InFlightSince: now.Add(-2 * time.Second).Format(time.RFC3339), }, } diff --git a/internal/control/aggregation.go b/internal/control/aggregation.go index 526f1d1a9..04ad8a038 100644 --- a/internal/control/aggregation.go +++ b/internal/control/aggregation.go @@ -193,11 +193,16 @@ func (a *Aggregations) Catalog(ctx context.Context) (map[string]accounts.Aggrega if err != nil { return nil, err } + return snapshot.catalog(), nil +} + +// catalog copies the map; the aggregation values remain read-only. +func (snapshot aggregationSnapshot) catalog() map[string]accounts.Aggregation { out := make(map[string]accounts.Aggregation, len(snapshot)) for id, agg := range snapshot { out[id] = agg } - return out, nil + return out } func (a *Aggregations) validateMembers(ctx context.Context, members []accounts.AggregationMember) error { @@ -250,12 +255,33 @@ func (a *Aggregations) resolveSnapshot(ctx context.Context) (aggregationSnapshot // filtered by the caller's allowed providers. The executor calls this once per // request before taking the Pool lock, and the result is read-only. The hot // path is served from an in-memory snapshot, so normal requests add no SQL. +// An enabled aggregation still resolves when filtering leaves no members; +// only a missing or disabled name can be treated as an ordinary model. func (a *Aggregations) Resolve(ctx context.Context, id string, allowedProviders map[string]bool) (accounts.Aggregation, error) { snapshot, err := a.resolveSnapshot(ctx) if err != nil { return accounts.Aggregation{}, err } - agg, ok := snapshot[id] + return snapshot.resolve(id, allowedProviders) +} + +// ResolveWithCatalog resolves a root and its nested group catalog from the +// same snapshot even if a concurrent write invalidates the cache. Flat roots +// need no catalog; pipeline compilation filters members of the copied catalog. +func (a *Aggregations) ResolveWithCatalog(ctx context.Context, id string, allowedProviders map[string]bool) (accounts.Aggregation, map[string]accounts.Aggregation, error) { + snapshot, err := a.resolveSnapshot(ctx) + if err != nil { + return accounts.Aggregation{}, nil, err + } + agg, err := snapshot.resolve(id, allowedProviders) + if err != nil || strings.TrimSpace(agg.Document) == "" { + return agg, nil, err + } + return agg, snapshot.catalog(), nil +} + +func (snapshot aggregationSnapshot) resolve(id string, allowedProviders map[string]bool) (accounts.Aggregation, error) { + agg, ok := snapshot[strings.ToLower(strings.TrimSpace(id))] if !ok || !agg.Enabled { return accounts.Aggregation{}, ErrAggregationNotFound } @@ -273,12 +299,6 @@ func (a *Aggregations) Resolve(ctx context.Context, id string, allowedProviders } members = append(members, member) } - // A document-only row has no persisted members. Keep it so the compiler - // can build seats from the document. An empty member list with no - // document is still not found. - if len(members) == 0 && strings.TrimSpace(agg.Document) == "" { - return accounts.Aggregation{}, ErrAggregationNotFound - } // Stable priority order; DoS-safe cap even if a stale row has more members. if len(members) > accounts.MaxAggregationMembers { members = members[:accounts.MaxAggregationMembers] diff --git a/internal/control/aggregation_catalog.go b/internal/control/aggregation_catalog.go index e2803f52c..eb7bd97d5 100644 --- a/internal/control/aggregation_catalog.go +++ b/internal/control/aggregation_catalog.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" "github.com/caigee-cmd/cli2api/internal/providers" ) @@ -13,6 +14,32 @@ type AggregationLister interface { List(ctx context.Context) ([]accounts.Aggregation, error) } +// aggregateCatalogSnapshot uses the same copy-on-write snapshot as dispatch +// when backed by the control facade. Lightweight listers may supply one list. +func aggregateCatalogSnapshot(ctx context.Context, lister AggregationLister) (map[string]accounts.Aggregation, error) { + if lister == nil { + return nil, nil + } + if source, ok := lister.(interface { + Catalog(context.Context) (map[string]accounts.Aggregation, error) + }); ok { + return source.Catalog(ctx) + } + aggs, err := lister.List(ctx) + if err != nil { + return nil, err + } + catalog := make(map[string]accounts.Aggregation, len(aggs)) + for _, agg := range aggs { + catalog[logicalCatalogID(agg.ID)] = agg + } + return catalog, nil +} + +func logicalCatalogID(id string) string { + return strings.ToLower(strings.TrimSpace(id)) +} + // aggregationCatalogMember is one configured member resolved to the catalog // entry that actually serves it. Provider and region are honored so a member // never borrows another provider's copy of the same model name. @@ -65,51 +92,116 @@ var inheritedAggregationFields = []string{ // The catalog slices passed in/out are plain value maps, so this never mutates // the shared catalog cache. func MergeAggregationModels(ctx context.Context, lister AggregationLister, models []map[string]any) []map[string]any { - if lister == nil || len(models) == 0 { + return MergeAggregationModelsForIdentity(ctx, lister, models, auth.Identity{}, nil) +} + +// MergeAggregationModelsForIdentity also checks live account policy when a +// pool snapshot is supplied. A nil pool means the caller has no live view. +func MergeAggregationModelsForIdentity(ctx context.Context, lister AggregationLister, models []map[string]any, identity auth.Identity, pool []AccountModelAllow) []map[string]any { + if len(models) == 0 { return models } - aggs, err := lister.List(ctx) - if err != nil || len(aggs) == 0 { + catalog, err := aggregateCatalogSnapshot(ctx, lister) + if err != nil || len(catalog) == 0 { return models } + view := buildAggregationCatalog(models, catalog, identity, pool) + out := make([]map[string]any, 0, len(models)+len(view.entries)) + for _, model := range models { + id, _ := model["id"].(string) + key := logicalCatalogID(id) + if !view.shadowed[key] && !view.members[key] { + out = append(out, model) + } + } + out = append(out, view.entries...) + sortAggregationCatalog(out) + return out +} + +// AggregationKeyModelEntries publishes logical entries and unshadowed public +// aliases. Both group visibility and name ownership use the same snapshot, +// including enabled groups that a key cannot currently route to. +func AggregationKeyModelEntries(ctx context.Context, lister AggregationLister, models []map[string]any, identity auth.Identity, pool []AccountModelAllow) []map[string]any { + catalog, err := aggregateCatalogSnapshot(ctx, lister) + if err != nil { + // Without the logical namespace, an alias cannot be safely advertised. + return []map[string]any{} + } + view := buildAggregationCatalog(models, catalog, identity, pool) + out := view.entries + for _, alias := range AggregateModelEntries(models, identity, pool) { + id, _ := alias["id"].(string) + if !view.shadowed[logicalCatalogID(id)] { + out = append(out, alias) + } + } + sortAggregationCatalog(out) + return out +} +type aggregationCatalogView struct { + entries []map[string]any + shadowed map[string]bool + members map[string]bool +} + +func buildAggregationCatalog(models []map[string]any, catalog map[string]accounts.Aggregation, identity auth.Identity, pool []AccountModelAllow) aggregationCatalogView { + view := aggregationCatalogView{ + entries: make([]map[string]any, 0, len(catalog)), + shadowed: make(map[string]bool, len(catalog)), + members: make(map[string]bool), + } + if len(catalog) == 0 { + return view + } index := aggregationCatalogIndex(models) - hidden := map[string]bool{} - entries := make([]map[string]any, 0, len(aggs)) - for _, agg := range aggs { - if !agg.Enabled || len(agg.Members) == 0 { + scope := aggregationCatalogScope{identity: identity, aggregationOnly: identity.ModelAggregation && accounts.IsAggregationOnly(identity.AllowedProviders)} + if pool != nil { + scope.byProvider = make(map[string][]AccountModelAllow) + for _, account := range pool { + provider := accounts.NormalizeProviderFamily(account.Provider) + if scope.allows(provider, account.Region) { + scope.byProvider[provider] = append(scope.byProvider[provider], account) + } + } + } + for _, agg := range catalog { + if !agg.Enabled || logicalCatalogID(agg.ID) == "" { + continue + } + if provider, _, _ := accounts.SplitProviderModelPrefix(agg.ID); provider != "" { + // A legacy name using a reserved prefix routes directly, not here. + continue + } + // The runtime looks up the enabled logical ID before raw models. + // Avoid listing a duplicate or falsely advertising a shadowed model. + view.shadowed[logicalCatalogID(agg.ID)] = true + current, err := accounts.PipelineCatalogMembers(agg, catalog) + if err != nil { continue } - members := resolveAggregationCatalogMembers(agg, index) + agg.Members = current + members := scope.resolveMembers(agg, index) if len(members) == 0 { // Every member is filtered out by the caller's provider policy. Do // not advertise a logical ID that cannot route to any real model. continue } for _, member := range members { - hidden[member.id] = true + view.members[logicalCatalogID(member.id)] = true } - entries = append(entries, buildAggregationEntry(agg, members)) - } - if len(entries) == 0 && len(hidden) == 0 { - return models + view.entries = append(view.entries, buildAggregationEntry(agg, members)) } + return view +} - out := make([]map[string]any, 0, len(models)-len(hidden)+len(entries)) - for _, model := range models { - id, _ := model["id"].(string) - if hidden[id] { - continue - } - out = append(out, model) - } - out = append(out, entries...) - sort.SliceStable(out, func(i, j int) bool { - left, _ := out[i]["id"].(string) - right, _ := out[j]["id"].(string) +func sortAggregationCatalog(models []map[string]any) { + sort.SliceStable(models, func(i, j int) bool { + left, _ := models[i]["id"].(string) + right, _ := models[j]["id"].(string) return left < right }) - return out } // aggregationCatalogIndex groups catalog rows by (provider family, canonical @@ -122,7 +214,8 @@ func aggregationCatalogIndex(models []map[string]any) map[string][]map[string]an if strings.TrimSpace(id) == "" { continue } - key := aggregationCatalogKey(modelEntryProvider(model), modelAllowKey(id)) + provider := modelEntryProvider(model) + key := aggregationCatalogKey(provider, id) if key == "" { continue } @@ -131,34 +224,85 @@ func aggregationCatalogIndex(models []map[string]any) map[string][]map[string]an return index } -func aggregationCatalogKey(provider, modelKey string) string { - provider = accounts.NormalizeProviderFamily(provider) - if provider == "" || modelKey == "" { +func aggregationCatalogKey(provider, model string) string { + if model = modelAllowKey(provider, model); model == "" { return "" } - return provider + "\x00" + modelKey + return provider + "\x00" + model +} + +type aggregationCatalogScope struct { + identity auth.Identity + aggregationOnly bool + byProvider map[string][]AccountModelAllow } -func resolveAggregationCatalogMembers(agg accounts.Aggregation, index map[string][]map[string]any) []aggregationCatalogMember { +func (s aggregationCatalogScope) allows(provider, region string) bool { + return s.aggregationOnly || s.identity.AllowsProviderRegion(provider, region) +} + +func (s aggregationCatalogScope) resolveMembers(agg accounts.Aggregation, index map[string][]map[string]any) []aggregationCatalogMember { resolved := make([]aggregationCatalogMember, 0, len(agg.Members)) for _, member := range agg.Members { - key := aggregationCatalogKey(member.Provider, modelAllowKey(member.Model)) - if key == "" { + provider := accounts.NormalizeProviderFamily(member.Provider) + model := modelAllowKey(provider, member.Model) + if model == "" || (!s.aggregationOnly && !s.identity.AllowsProvider(provider)) { continue } - for _, candidate := range index[key] { - if member.Region != "" && !accountServesRegion(member.Region, EntryModelRegions(candidate)) { - continue + if s.byProvider == nil { + for _, candidate := range index[provider+"\x00"+model] { + if member.Region != "" { + if !s.allows(provider, member.Region) || !accountServesRegion(member.Region, catalogEntryRegions(candidate, provider)) { + continue + } + } else if !s.aggregationOnly && !identityAllowsAnyModelRegion(s.identity, candidate) { + continue + } + id, _ := candidate["id"].(string) + resolved = append(resolved, aggregationCatalogMember{id: id, entry: candidate}) } - id, _ := candidate["id"].(string) - if strings.TrimSpace(id) == "" { + continue + } + // Resolve the member, its alias target and the row through the same + // account. A provider-wide catalog row cannot authorize a different + // region or account, and a display alias cannot prove model support. + targets := make(map[string][]string) + for _, account := range s.byProvider[provider] { + region := accounts.NormalizeRegion(account.Region) + if (member.AccountID != "" && member.AccountID != account.AccountID) || + (member.Region != "" && accounts.NormalizeRegion(member.Region) != region) || + !accountServesModel(account, model) || + (account.CanRouteModel != nil && !account.CanRouteModel(member.Model)) { continue } - // A region-wide member can fail over to the same model in several - // regions. Keep every candidate so the advertised capability - // intersection covers all of them. IDs may repeat across those - // rows; the hidden set below deduplicates them. - resolved = append(resolved, aggregationCatalogMember{id: id, entry: candidate}) + target := model + if alias := account.Aliases[model]; alias != "" { + target = accounts.CanonicalModelID(alias) + } + targets[target] = append(targets[target], region) + } + keys := make([]string, 0, len(targets)) + for target := range targets { + keys = append(keys, target) + } + sort.Strings(keys) + for _, target := range keys { + for _, candidate := range index[provider+"\x00"+target] { + if alias, _ := candidate["alias_of"].(string); alias != "" { + continue + } + for _, region := range targets[target] { + if !accountServesRegion(region, catalogEntryRegions(candidate, provider)) { + continue + } + id, _ := candidate["id"].(string) + if target != model { + id = model // hide the configured alias, not its underlying row + } + resolved = append(resolved, aggregationCatalogMember{id: id, entry: candidate}) + break + } + } } } return resolved diff --git a/internal/control/aggregation_catalog_test.go b/internal/control/aggregation_catalog_test.go index 7c0093484..cd61e5437 100644 --- a/internal/control/aggregation_catalog_test.go +++ b/internal/control/aggregation_catalog_test.go @@ -2,9 +2,11 @@ package control import ( "context" + "errors" "testing" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" ) type aggregationCatalogLister []accounts.Aggregation @@ -13,6 +15,91 @@ func (l aggregationCatalogLister) List(context.Context) ([]accounts.Aggregation, return l, nil } +type aggregationCatalogSnapshotStub struct { + loads int + err error +} + +func (*aggregationCatalogSnapshotStub) List(context.Context) ([]accounts.Aggregation, error) { + panic("the live catalog must use its routing snapshot") +} + +func (s *aggregationCatalogSnapshotStub) Catalog(context.Context) (map[string]accounts.Aggregation, error) { + s.loads++ + return map[string]accounts.Aggregation{ + "active": {ID: "active", Enabled: true, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "target"}}}, + "shadowed": {ID: "shadowed", Enabled: true, Members: []accounts.AggregationMember{{Provider: "workbuddy", Model: "target"}}}, + "disabled": {ID: "disabled"}, + }, s.err +} + +func TestAggregationKeyModelEntriesUsesOneSnapshotForShadowing(t *testing.T) { + source := &aggregationCatalogSnapshotStub{} + models := []map[string]any{{"id": "target", "provider": "qoder"}} + pool := []AccountModelAllow{{Provider: "qoder", Aliases: map[string]string{"shadowed": "target", "disabled": "target"}}} + identity := auth.Identity{ModelAggregation: true, AllowedProviders: []string{"qoder"}} + got := AggregationKeyModelEntries(t.Context(), source, models, identity, pool) + if source.loads != 1 || len(got) != 2 || got[0]["id"] != "active" || got[1]["id"] != "disabled" { + t.Fatalf("loads=%d, list=%#v: want active group and disabled group’s unshadowed alias", source.loads, got) + } + source.err = errors.New("snapshot unavailable") + if got := AggregationKeyModelEntries(t.Context(), source, models, identity, pool); len(got) != 0 { + t.Fatalf("advertised aliases without their logical namespace: %#v", got) + } +} + +func TestMergeAggregationModelsUsesCurrentNestedMembers(t *testing.T) { + old := accounts.AggregationMember{Provider: "qoder", Model: "old-model"} + list := aggregationCatalogLister{ + {ID: "parent", Enabled: true, Document: `{"steps":[{"kind":"group","aggregation_id":"child"}]}`, Members: []accounts.AggregationMember{old}}, + {ID: "child", Enabled: true, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "new-model"}}}, + } + models := []map[string]any{ + {"id": "old-model", "provider": "qoder", "catalog_context_length": 32768}, + {"id": "new-model", "provider": "qoder", "catalog_context_length": 128000}, + {"id": "parent", "provider": "qoder"}, + } + got := MergeAggregationModels(t.Context(), list, models) + if parent := aggregationTestEntry(got, "parent"); parent == nil || parent["catalog_context_length"] != 128000 { + t.Fatalf("parent did not use live child capability: %#v", got) + } + if aggregationTestEntry(got, "old-model") == nil || len(got) != 3 { + t.Fatalf("retired leaf hidden or duplicate logical ID advertised: %#v", got) + } + list[1].Enabled = false + got = MergeAggregationModels(t.Context(), list, models[:2]) + if aggregationTestEntry(got, "parent") != nil || len(got) != 2 { + t.Fatalf("disabled child still advertised by its parent: %#v", got) + } +} + +func TestMergeAggregationModelsDoesNotBorrowAnotherNamespace(t *testing.T) { + list := aggregationCatalogLister{{ID: "logical", Enabled: true, Members: []accounts.AggregationMember{{Provider: "command", Model: "alpha/shared"}}}} + models := []map[string]any{ + {"id": "beta/shared", "provider": "command", "catalog_context_length": 32768}, + {"id": "command/alpha/shared", "provider": "command", "catalog_context_length": 128000}, + } + if got := MergeAggregationModels(t.Context(), list, models[:1]); len(got) != 1 || aggregationTestEntry(got, "logical") != nil { + t.Fatalf("advertised alpha using beta model: %#v", got) + } + got := MergeAggregationModels(t.Context(), list, models) + if entry := aggregationTestEntry(got, "logical"); entry == nil || entry["catalog_context_length"] != 128000 || aggregationTestEntry(got, "beta/shared") == nil { + t.Fatalf("did not match exact namespace: %#v", got) + } +} + +func TestMergeAggregationModelsKeepsUnrelatedModelsWhenGroupsAreMissingTargets(t *testing.T) { + models := []map[string]any{{"id": "usable-model", "provider": "qoder"}} + list := aggregationCatalogLister{ + {ID: "logical-a", Enabled: true, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "missing-a"}}}, + {ID: "logical-b", Enabled: true, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "missing-b"}}}, + } + got := MergeAggregationModels(t.Context(), list, models) + if len(got) != 1 || got[0]["id"] != "usable-model" { + t.Fatalf("unrelated catalog model lost: %#v", got) + } +} + func TestMergeAggregationModelsOmitsAggregationWithNoVisibleMembers(t *testing.T) { models := []map[string]any{{"id": "allowed-model", "provider": "qoder"}} list := aggregationCatalogLister{{ diff --git a/internal/control/aggregation_test.go b/internal/control/aggregation_test.go index 8f304601c..6c17fde95 100644 --- a/internal/control/aggregation_test.go +++ b/internal/control/aggregation_test.go @@ -2,10 +2,16 @@ package control import ( "context" + "errors" "fmt" + "net/http" "testing" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" ) func TestAggregationResolveFiltersByProviderAndOrders(t *testing.T) { @@ -57,6 +63,114 @@ func TestAggregationResolveRejectsDisabledAndUnknown(t *testing.T) { } } +func TestAggregationResolveRetainsEnabledModelAfterFilteringAllMembers(t *testing.T) { + store := &aggTestStore{agg: accounts.Aggregation{ + ID: "shared", Enabled: true, + Members: []accounts.AggregationMember{{Provider: "qoder", Model: "upstream"}}, + }} + svc := NewAggregations(store) + got, err := svc.Resolve(context.Background(), "shared", map[string]bool{"workbuddy": true}) + if err != nil || got.ID != "shared" || !got.Enabled || len(got.Members) != 0 { + t.Fatalf("resolved aggregation=%+v err=%v, want known enabled model with no members", got, err) + } + got, err = svc.Resolve(context.Background(), "shared", nil) + if err != nil || len(got.Members) != 1 { + t.Fatalf("filtered lookup mutated the snapshot: %+v err=%v", got, err) + } +} + +func TestAggregationPrepareDoesNotDispatchSameNameOrdinaryModelOnFailure(t *testing.T) { + const model = "shared" + for _, tc := range []struct { + name string + agg accounts.Aggregation + requestModel string + listErr error + wantCode string + wantStatus int + }{ + {name: "unknown allows ordinary model"}, + {name: "disabled allows ordinary model", agg: accounts.Aggregation{ID: model}}, + { + name: "unauthorized members", + agg: accounts.Aggregation{ID: model, Enabled: true, Members: []accounts.AggregationMember{ + {Provider: "qoder", Model: "upstream"}, + }}, + wantCode: "model_not_available", wantStatus: http.StatusBadRequest, + }, + { + name: "stored aggregation ID is matched canonically", requestModel: " ShArEd ", + agg: accounts.Aggregation{ID: model, Enabled: true}, + wantCode: "model_not_available", wantStatus: http.StatusBadRequest, + }, + { + name: "invalid pipeline", + agg: accounts.Aggregation{ID: model, Enabled: true, Document: `{"version":1,`}, + wantCode: "aggregation_unavailable", wantStatus: http.StatusServiceUnavailable, + }, + { + name: "pipeline without reachable members", + agg: accounts.Aggregation{ + ID: model, Enabled: true, + Document: `{"version":1,"steps":[{"id":"member","kind":"member","provider":"qoder","model":"upstream"}]}`, + }, + wantCode: "aggregation_unavailable", wantStatus: http.StatusServiceUnavailable, + }, + { + name: "backend cannot resolve name", + listErr: errors.New("aggregation snapshot failed"), + wantCode: "aggregation_unavailable", wantStatus: http.StatusServiceUnavailable, + }, + } { + t.Run(tc.name, func(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "ordinary", Provider: "workbuddy", Runtime: "in_process", Models: []string{model}}) + chat := &aggregationOrdinaryChat{} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + requestModel := tc.requestModel + if requestModel == "" { + requestModel = model + } + prepared, err := ex.Prepare(executor.PrepareInput{ + Request: translate.ChatRequest{Model: requestModel}, + Identity: auth.Identity{AllowedProviders: []string{"workbuddy"}}, + CrossProviderPool: true, + Aggregations: NewAggregations(&aggTestStore{agg: tc.agg, listErr: tc.listErr}), + }) + if err == nil { + _, err = ex.ChatNonStreamPrepared(prepared.Context, prepared.Request, prepared.Route) + } + if tc.wantCode == "" { + if err != nil || chat.calls != 1 { + t.Fatalf("ordinary route calls=%d err=%v, want one successful dispatch", chat.calls, err) + } + return + } + var prepareError *executor.PrepareError + if !errors.As(err, &prepareError) || prepareError.Code != tc.wantCode || prepareError.Status != tc.wantStatus || chat.calls != 0 { + t.Fatalf("ordinary route calls=%d err=%#v; want no dispatch and %s / %d", chat.calls, err, tc.wantCode, tc.wantStatus) + } + }) + } +} + +type aggregationOrdinaryChat struct { + calls int + model string +} + +func (f *aggregationOrdinaryChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + f.calls++ + f.model = req.Model + return providers.ChatOutcome{Content: "ordinary"}, nil +} + +func (f *aggregationOrdinaryChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, errors.New("unexpected streaming dispatch") +} + func TestAggregationResolveUsesCacheAndInvalidatesOnWrite(t *testing.T) { store := &aggTestStore{agg: accounts.Aggregation{ ID: "my-model", Enabled: true, Strategy: accounts.AggregationRoundRobin, @@ -84,6 +198,135 @@ func TestAggregationResolveUsesCacheAndInvalidatesOnWrite(t *testing.T) { } } +func TestAggregationResolveWithCatalogKeepsOneVersion(t *testing.T) { + ctx := context.Background() + const doc = `{"steps":[{"id":"nested","kind":"group","aggregation_id":"team/child"}]}` + old := accounts.Aggregation{ID: "team/root", Enabled: true, Document: doc, Members: []accounts.AggregationMember{{Provider: "qoder", Model: "old"}}} + child := accounts.Aggregation{ID: "team/child", Enabled: true, Members: old.Members} + store := &aggTestStore{agg: child, extra: []accounts.Aggregation{old, {ID: "disabled"}}} + svc := NewAggregations(store) + root, catalog, err := svc.ResolveWithCatalog(ctx, " TEAM/ROOT ", nil) + if err != nil || root.ID != old.ID || len(root.Members) != 1 || catalog[child.ID].ID != child.ID || store.listCalls != 1 { + t.Fatalf("root=%+v catalog=%+v err=%v List calls=%d", root, catalog, err, store.listCalls) + } + if filtered, dir, err := svc.ResolveWithCatalog(ctx, old.ID, map[string]bool{"workbuddy": true}); err != nil || len(filtered.Members) != 0 || dir[child.ID].ID != child.ID || store.listCalls != 1 { + t.Fatalf("known root after filtering=%+v catalog=%+v err=%v List calls=%d", filtered, dir, err, store.listCalls) + } + for _, id := range []string{"disabled", "unknown"} { + if _, dir, err := svc.ResolveWithCatalog(ctx, id, nil); !errors.Is(err, ErrAggregationNotFound) || dir != nil { + t.Errorf("ResolveWithCatalog(%q) directory=%+v err=%v, want not found", id, dir, err) + } + } + if flat, dir, err := svc.ResolveWithCatalog(ctx, child.ID, nil); err != nil || flat.ID != child.ID || dir != nil { + t.Fatalf("flat root=%+v catalog=%+v err=%v", flat, dir, err) + } + // Disable the child after lookup and before compiling. The in-flight + // request keeps its original root/catalog; new requests see the update. + disable := false + if _, err := svc.Update(ctx, child.ID, accounts.UpdateAggregation{Enabled: &disable}); err != nil { + t.Fatal(err) + } + newRoot, newCatalog, err := svc.ResolveWithCatalog(ctx, old.ID, nil) + if err != nil || newCatalog[child.ID].Enabled || store.listCalls != 2 { + t.Fatalf("new catalog=%+v err=%v List calls=%d", newCatalog, err, store.listCalls) + } + if _, _, _, err := accounts.CompilePipeline(newRoot, newCatalog, "", nil, nil); err == nil { + t.Fatal("new request compiled a disabled child") + } + got, _, _, err := accounts.CompilePipeline(root, catalog, "", nil, nil) + if err != nil || len(got.Members) != 1 || got.Members[0].Model != "old" { + t.Fatalf("in-flight request lost its snapshot: %+v, %v", got, err) + } +} + +func TestAggregationCreateRejectsConflictsWithoutLockingOutOldData(t *testing.T) { + ctx := context.Background() + const oldDoc = `{"steps":[{"kind":"branch","paths":[{"fallback":true,"steps":[{"kind":"member","provider":"qoder","model":"a"}]}],"fallback":[{"kind":"member","provider":"qoder","model":"b"}]}]}` + store := &aggTestStore{agg: accounts.Aggregation{ID: "qoder-cn/legacy", Enabled: true, Document: oldDoc}} + svc := NewAggregations(store) + for _, input := range []accounts.CreateAggregation{ + {ID: "qoder-cn/forbidden", Members: []accounts.AggregationMember{{Provider: "qoder", Model: "a"}}}, + {ID: "new-model", Document: oldDoc}, + } { + _, err := svc.Create(ctx, input) + var op *OperationError + if !errors.As(err, &op) || op.Code != "invalid_request" || store.inserts != 0 { + t.Fatalf("Create(%q) err=%v Inserts=%d", input.ID, err, store.inserts) + } + } + name := "Manage legacy record" + if got, err := svc.Update(ctx, store.agg.ID, accounts.UpdateAggregation{Name: &name}); err != nil || got.Name != name || got.Document != oldDoc { + t.Fatalf("old record not manageable: %+v, %v", got, err) + } + doc := `{"steps":[{"kind":"member","provider":"qoder","model":"qoder-cn/a"}]}` + got, err := svc.Update(ctx, store.agg.ID, accounts.UpdateAggregation{Document: &doc}) + if err != nil || len(got.Members) != 1 || got.Members[0].Region != "cn" || got.Members[0].Model != "a" { + t.Fatalf("corrected document not saved: %+v, %v", got, err) + } +} + +func TestAggregationNestedAliasDispatchesOnlyWithinMemberRegionAndKeyGrant(t *testing.T) { + ctx := context.Background() + const childID = "team/child" + const rootID = "team/root" + store := &aggTestStore{} + svc := NewAggregations(store) + child, err := svc.Create(ctx, accounts.CreateAggregation{ + ID: childID, Enabled: true, + Document: `{"steps":[{"kind":"member","provider":"workbuddy","model":"workbuddy-cn/fast"}]}`, + }) + if err != nil { + t.Fatal(err) + } + store.agg = child + root, err := svc.Create(ctx, accounts.CreateAggregation{ + ID: rootID, Enabled: true, Strategy: accounts.AggregationPriority, + Document: `{"steps":[{"id":"nested","kind":"group","aggregation_id":" TEAM/CHILD "}]}`, + }) + if err != nil { + t.Fatal(err) + } + store.extra = []accounts.Aggregation{root} + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ + ID: "first-global", Provider: "workbuddy", Region: "global", Runtime: "in_process", + Models: []string{"upstream-global"}, ModelAliases: map[string]string{"fast": "upstream-global"}, + }) + pool.Upsert(executor.Item{ + ID: "second-cn", Provider: "workbuddy", Region: "cn", Runtime: "in_process", + Models: []string{"upstream-cn"}, ModelAliases: map[string]string{"fast": "upstream-cn"}, + }) + chat := &aggregationOrdinaryChat{} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = providers.NewRegistry() + ex.Providers.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + for _, tc := range []struct { + grant string + allowed bool + }{{"workbuddy", true}, {"workbuddy:cn", true}, {"workbuddy:global", false}} { + t.Run(tc.grant, func(t *testing.T) { + chat.calls, chat.model = 0, "" + prepared, err := ex.Prepare(executor.PrepareInput{ + Context: ctx, Request: translate.ChatRequest{Model: rootID}, + Identity: auth.Identity{AllowedProviders: []string{tc.grant}}, CrossProviderPool: true, Aggregations: svc, + }) + if err != nil { + t.Fatal(err) + } + got, err := ex.ChatNonStreamPrepared(prepared.Context, prepared.Request, prepared.Route) + if !tc.allowed { + if err == nil || chat.calls != 0 { + t.Fatalf("conflicting grant dispatched: calls=%d, err=%v", chat.calls, err) + } + return + } + if err != nil || chat.calls != 1 || got.AccountID != "second-cn" || chat.model != "upstream-cn" { + t.Fatalf("nested alias: account=%q, upstream=%q, calls=%d, err=%v", got.AccountID, chat.model, chat.calls, err) + } + }) + } +} + func TestAggregationCreateRejectsProviderDisabledModel(t *testing.T) { store := &aggTestStore{} validator := aggregationMemberRejector{model: "disabled-model"} @@ -133,6 +376,8 @@ func (r aggregationMemberRejector) ValidateAggregationMembers(_ context.Context, // aggTestStore implements only the narrow AggregationStore surface. type aggTestStore struct { agg accounts.Aggregation + extra []accounts.Aggregation + listErr error listCalls int inserts int saves int @@ -155,6 +400,6 @@ func (s *aggTestStore) SaveAggregation(_ context.Context, agg accounts.Aggregati } func (s *aggTestStore) ListAggregations(_ context.Context) ([]accounts.Aggregation, error) { s.listCalls++ - return []accounts.Aggregation{s.agg}, nil + return append([]accounts.Aggregation{s.agg}, s.extra...), s.listErr } func (s *aggTestStore) DeleteAggregation(_ context.Context, _ string) error { return nil } diff --git a/internal/control/catalog_policy.go b/internal/control/catalog_policy.go index f8bc89965..16063b447 100644 --- a/internal/control/catalog_policy.go +++ b/internal/control/catalog_policy.go @@ -288,6 +288,7 @@ func ProviderModelEntry(model providers.ModelInfo, provider string) map[string]a // contributes every model of its provider and region. Enabled IDs are the // canonical form stored by NormalizeAccountRouting. type AccountModelAllow struct { + AccountID string Provider string Region string ModelsRestricted bool @@ -296,6 +297,8 @@ type AccountModelAllow struct { // model this account rewrites it to. The public list keeps an alias only // when some granted account both defines it and may serve its target. Aliases map[string]string + // CanRouteModel optionally checks the account’s live model snapshot. + CanRouteModel func(string) bool } // ModelServedByAccounts reports whether at least one account the caller can @@ -330,9 +333,9 @@ func ModelServedByAccounts(entry map[string]any, identity auth.Identity, pool [] if !aggregationOnly && !identity.AllowsProvider(provider) { return false } - regions := EntryModelRegions(entry) + regions := catalogEntryRegions(entry, provider) id, _ := entry["id"].(string) - modelKey := modelAllowKey(id) + modelKey := modelAllowKey(provider, id) if modelKey == "" { return true } @@ -365,12 +368,12 @@ func ExpandModelAliases(models []map[string]any, pool []AccountModelAllow) []map existing := make(map[string]bool, len(models)) for _, model := range models { id, _ := model["id"].(string) - key := modelAllowKey(id) + provider := modelEntryProvider(model) + key := modelAllowKey(provider, id) if key == "" { continue } existing[key] = true - provider := modelEntryProvider(model) if provider != "" { byTarget[provider+"@"+key] = model } @@ -401,7 +404,7 @@ func ExpandModelAliases(models []map[string]any, pool []AccountModelAllow) []map if base == nil { base = byTarget["@"+targetKey] } - if base == nil || !accountServesRegion(account.Region, EntryModelRegions(base)) { + if base == nil || !accountServesRegion(account.Region, catalogEntryRegions(base, modelEntryProvider(base))) { continue } dedupeKey := provider + "@" + aliasKey @@ -439,7 +442,7 @@ func AggregateModelEntries(models []map[string]any, identity auth.Identity, pool realIDs := make(map[string]bool, len(models)) for _, model := range models { id, _ := model["id"].(string) - key := modelAllowKey(id) + key := modelAllowKey(modelEntryProvider(model), id) if key == "" { continue } @@ -458,10 +461,11 @@ func AggregateModelEntries(models []map[string]any, identity auth.Identity, pool for alias, target := range account.Aliases { aliasKey := accounts.CanonicalModelID(alias) targetKey := accounts.CanonicalModelID(target) - if aliasKey == "" || aliasKey == "auto" || targetKey == "" || targetKey == "auto" || aliasKey == targetKey { + if aliasKey == "" || aliasKey == "auto" || strings.Contains(aliasKey, "/") || targetKey == "" || targetKey == "auto" || aliasKey == targetKey { continue } - if realIDs[aliasKey] || seen[aliasKey] || !accountServesModel(account, targetKey) { + if realIDs[aliasKey] || seen[aliasKey] || !accountServesModel(account, aliasKey) || + (account.CanRouteModel != nil && !account.CanRouteModel(aliasKey)) { continue } base := aliasBaseEntry(byTarget[targetKey], provider, account.Region) @@ -492,12 +496,7 @@ func AggregateModelEntries(models []map[string]any, identity auth.Identity, pool // account lives in another region. func aliasBaseEntry(candidates []map[string]any, provider, region string) map[string]any { for _, candidate := range candidates { - if modelEntryProvider(candidate) == provider && accountServesRegion(region, EntryModelRegions(candidate)) { - return candidate - } - } - for _, candidate := range candidates { - if accountServesRegion(region, EntryModelRegions(candidate)) { + if modelEntryProvider(candidate) == provider && accountServesRegion(region, catalogEntryRegions(candidate, provider)) { return candidate } } @@ -556,19 +555,27 @@ func accountServesModel(account AccountModelAllow, modelKey string) bool { return false } -// modelAllowKey folds a catalog id the same way routing folds a request, and -// strips a provider prefix ("qoder/glm-5.2", "workbuddy-cn/glm-5.2") so a -// prefixed public list matches the bare ids stored on the account. "auto" is a -// real catalog entry and must obey a restricted account's enabled list; only an -// empty/unparseable id bypasses the allowlist. -func modelAllowKey(id string) string { - id = strings.TrimSpace(id) - if slash := strings.LastIndex(id, "/"); slash >= 0 { - id = id[slash+1:] +// modelAllowKey removes only the owning provider's route selector. The +// remaining ID can contain slashes (for example, Command's org/model IDs). +func modelAllowKey(provider, id string) string { + prefix, _, bare := accounts.SplitProviderModelPrefix(id) + if prefix != "" && prefix == accounts.NormalizeProviderFamily(provider) { + id = bare + } + if strings.TrimSpace(id) == "" { + return "" } return accounts.CanonicalModelID(id) } +func catalogEntryRegions(entry map[string]any, provider string) []string { + id, _ := entry["id"].(string) + if prefix, region, _ := accounts.SplitProviderModelPrefix(id); prefix != "" && prefix == provider && region != "" { + return []string{region} + } + return EntryModelRegions(entry) +} + // FilterModelsForIdentity applies grants after loading the shared catalog. func FilterModelsForIdentity(identity auth.Identity, models []map[string]any) []map[string]any { if len(identity.AllowedProviders) == 0 { @@ -600,9 +607,9 @@ func FilterModelsForIdentity(identity auth.Identity, models []map[string]any) [] // cross-provider pool is on; with it off, RejectsBareModel refuses them, so // model lists must match what the gateway accepts or every client that picks a // model from the list (console access page, /v1/models consumers) gets a 400. -// Entries already carrying a prefix, and the pooled qoder view (empty provider, -// owned_by=qoder), pass through unchanged. Region-qualified entries use the -// dash form so a specific region stays pinned ("workbuddy-cn/glm-5.3"). +// Entries already carrying their provider's route prefix pass through. A +// provider-native namespace is part of the model ID, not a route prefix. +// Region-qualified entries use the dash form ("workbuddy-cn/glm-5.3"). func PrefixModelEntries(models []map[string]any) []map[string]any { if len(models) == 0 { return models @@ -615,7 +622,12 @@ func PrefixModelEntries(models []map[string]any) []map[string]any { if provider == "" { provider, _ = model["owned_by"].(string) } - if id == "" || provider == "" || strings.Contains(id, "/") { + if id == "" || strings.TrimSpace(provider) == "" { + out = append(out, model) + continue + } + provider = accounts.NormalizeProviderFamily(provider) + if current, _, _ := accounts.SplitProviderModelPrefix(id); current == provider { out = append(out, model) continue } @@ -647,14 +659,11 @@ func CloneModelEntry(model map[string]any) map[string]any { } func identityAllowsAnyModelRegion(identity auth.Identity, model map[string]any) bool { - regions := EntryModelRegions(model) + provider := modelEntryProvider(model) + regions := catalogEntryRegions(model, provider) if len(regions) == 0 { return true } - provider, _ := model["provider"].(string) - if provider == "" { - provider, _ = model["owned_by"].(string) - } for _, region := range regions { if identity.AllowsProviderRegion(provider, region) { return true diff --git a/internal/control/provider_settings.go b/internal/control/provider_settings.go index f69ad2021..69ac739df 100644 --- a/internal/control/provider_settings.go +++ b/internal/control/provider_settings.go @@ -273,12 +273,12 @@ func providerPolicyAllowsModel(policy accounts.ProviderPolicy, model string) boo if len(policy.EnabledModels) == 0 { return true } - key := modelAllowKey(model) + key := modelAllowKey(policy.Provider, model) if target := policy.ModelAliases[key]; target != "" { - key = modelAllowKey(target) + key = accounts.CanonicalModelID(target) } for _, enabled := range policy.EnabledModels { - if modelAllowKey(enabled) == key { + if accounts.CanonicalModelID(enabled) == key { return true } } diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 4af2932d1..6a946ba45 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -12,6 +12,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -24,15 +25,18 @@ func (h *Handler) HandleAnthropicMessages(w http.ResponseWriter, r *http.Request body := decodeRequestBody(w, r, maxChatRequestBytes, maxChatRequestBytes) defer body.Close() if body.err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request_error", body.err.Error()) writeAnthropicRequestBodyError(w, body.err) return } rawBody, readErr := readConversationBody(body, maxChatRequestBytes) if readErr != nil { if isRequestBodyTooLarge(readErr) { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "request_too_large", readErr.Error()) writeAnthropicRequestBodyError(w, readErr) return } + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request_error", readErr.Error()) writeAnthropicError(w, http.StatusBadRequest, "invalid_request_error", readErr.Error()) return } @@ -42,6 +46,7 @@ func (h *Handler) HandleAnthropicMessages(w http.ResponseWriter, r *http.Request var rectifyErr error rectified, rectify, rectifyErr = translate.RectifyAnthropicRequest(rawBody) if rectifyErr != nil { + h.recordEntryRejection(r, source.Model, accounts.KindInvalidRequest, "invalid_request_error", rectifyErr.Error()) writeAnthropicError(w, http.StatusBadRequest, "invalid_request_error", rectifyErr.Error()) return } @@ -50,6 +55,7 @@ func (h *Handler) HandleAnthropicMessages(w http.ResponseWriter, r *http.Request } } if err := json.Unmarshal(rectified, &source); err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request_error", err.Error()) writeAnthropicError(w, http.StatusBadRequest, "invalid_request_error", err.Error()) return } @@ -58,44 +64,69 @@ func (h *Handler) HandleAnthropicMessages(w http.ResponseWriter, r *http.Request } request, err := translate.TranslateAnthropicMessages(source) if err != nil { + h.recordEntryRejection(r, source.Model, accounts.KindInvalidRequest, "invalid_request_error", err.Error()) writeAnthropicError(w, http.StatusBadRequest, "invalid_request_error", err.Error()) return } - execution, err := h.PrepareCompatibilityExecution(r, request) + reserveKey, releaseKey := h.keySlotHooks(r) + defer releaseKey() + execution, err := h.prepareCompatibilityExecution(r, request, reserveKey) if err != nil { + h.recordPrepareRejection(r, source.Model, err) writeAnthropicCompatibilityError(w, err) return } - releaseKey, ok := h.reserveKeySlot(r) - if !ok { - writeAnthropicKeyConcurrencyLimited(w) - return - } - defer releaseKey() w.Header().Set("X-Request-Id", execution.RequestID) if execution.Request.Stream { h.handleAnthropicMessagesStream(w, r, execution) return } - result, err := h.Executor.ChatNonStream(execution.Context, execution.Request, execution.Prefer, execution.ProviderFilter) + result, err := h.Executor.ChatNonStreamPrepared(execution.Context, execution.Request, execution.Route) + defer h.refreshQuotaAfterUse(result.PoolAccountID, result.CooldownModel, result.AggregateFEFO) if err != nil { h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, nil, err, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) writeAnthropicCompatibilityError(w, err) return } - h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusOK, 0, &StreamRelayStats{ + turn, canonicalErr := canonicalNonStreamTurn(execution.Route.Tooling, result) + if canonicalErr != nil { + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, nil, canonicalErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, canonicalErr) + return + } + stats := &StreamRelayStats{ PromptTokens: ptrInt(result.PromptTokens), CompletionTokens: ptrInt(result.CompletionTokens), CacheReadTokens: result.CacheReadTokens, CacheWriteTokens: result.CacheWriteTokens, CachedTokens: result.CachedTokens, UsageSource: result.UsageSource, Credits: result.Credits, ConsumedCredits: result.ConsumedCredits, Model: result.Model, - }, nil, result.AttemptCount, result.ReasoningLevel) - writeJSON(w, http.StatusOK, anthropicMessageResponse(execution.RequestID, firstNonEmpty(result.Model, execution.PublicModel), result.Content, result.Reasoning, decodeOpenAIToolCalls(result.ToolCalls), result.FinishReason, result.PromptTokens, result.CompletionTokens, result.CacheReadTokens, result.CacheWriteTokens)) + UpstreamTerminal: "done", RequestState: "sent", + } + response, renderErr := anthropicCanonicalMessageResponse(execution.RequestID, firstNonEmpty(result.Model, execution.PublicModel), turn, result.PromptTokens, result.CompletionTokens, result.CacheReadTokens, result.CacheWriteTokens) + if renderErr != nil { + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, stats, renderErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, renderErr) + return + } + if writeErr := writeJSONResult(w, http.StatusOK, response); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusCanceled, 0, stats, writeErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + return + } + stats.DownstreamTerminal, stats.FlushState = "done", "ok" + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusOK, 0, stats, nil, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) } func (h *Handler) handleAnthropicMessagesStream(w http.ResponseWriter, r *http.Request, execution Execution) { - upstream, err := h.Executor.ChatStreamProxy(execution.Context, execution.Request, execution.Prefer, execution.ProviderFilter) + upstream, err := h.Executor.ChatStreamProxyPrepared(execution.Context, execution.Request, nil, execution.Route) + defer h.refreshQuotaAfterUse(upstream.PoolAccountID, upstream.CooldownModel, upstream.AggregateFEFO) if err != nil { h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusError, upstream.TTFBMs, nil, err, upstream.AttemptCount, upstream.ReasoningLevel) + h.finalizeExecution(execution) writeAnthropicCompatibilityError(w, err) return } @@ -103,12 +134,17 @@ func (h *Handler) handleAnthropicMessagesStream(w http.ResponseWriter, r *http.R h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusStreaming, upstream.TTFBMs, nil, nil, upstream.AttemptCount, upstream.ReasoningLevel) setCompatibilityStreamHeaders(w, upstream.AccountID, firstNonEmpty(upstream.Provider, execution.ProviderFilter)) w.WriteHeader(http.StatusOK) - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() + if flushErr := flushResponse(w); flushErr != nil { + stats := StreamRelayStats{DownstreamTerminal: "error", FlushState: "error"} + h.Executor.FinishStream(execution.Context, upstream, executor.ClientDisconnectError(flushErr)) + h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusCanceled, upstream.TTFBMs, &stats, flushErr, upstream.AttemptCount, upstream.ReasoningLevel) + h.finalizeExecution(execution) + return } writer := compatibilityStreamWriter(w) - stats, relayErr := RelayAnthropicStream(writer, upstream.Response.Body, execution.RequestID, firstNonEmpty(execution.PublicModel, execution.Request.Model)) - status := streamLogStatus(relayErr, stats.SawDone, r.Context().Err() != nil) + stats, relayErr := RelayAnthropicStream(writer, upstream.Response.Body, execution.RequestID, firstNonEmpty(execution.PublicModel, execution.Request.Model), execution.Route.Tooling) + stats.RequestState = upstream.RequestState + status := streamLogStatus(relayErr, stats, r.Context().Err() != nil) h.recordStreamDiagnostic(execution.RequestID, upstream.Response, execution.Started, stats, relayErr, r.Context().Err()) ttfb := streamTTFB(execution.Started, upstream.TTFBMs, stats) logErr := relayErr @@ -119,20 +155,22 @@ func (h *Handler) handleAnthropicMessagesStream(w http.ResponseWriter, r *http.R logErr = nil } h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, status, ttfb, &stats, logErr, upstream.AttemptCount, upstream.ReasoningLevel) - if relayErr == nil { - h.Executor.CommitSession(execution.Context, execution.Request, upstream.Routing, firstNonEmpty(upstream.PoolAccountID, upstream.AccountID)) - return - } - if !IsStreamClientDisconnect(relayErr) { + h.finishRelayedStream(execution.Context, upstream, relayErr) + if relayErr != nil && !IsStreamClientDisconnect(relayErr) && stats.DownstreamTerminal != "error" { _ = writeAnthropicStreamError(writer, relayErr) } - h.observeCompatibilityStreamFailure(r, execution, upstream, relayErr) } func writeAnthropicCompatibilityError(w http.ResponseWriter, err error) { + if errors.Is(err, errKeyConcurrencyLimited) { + writeAnthropicKeyConcurrencyLimited(w) + return + } var requestErr *chatHTTPError if errors.As(err, &requestErr) { - writeAnthropicError(w, requestErr.Status, "invalid_request_error", requestErr.Message) + writeAnthropicError(w, requestErr.Status, anthropicErrorTypeForStatus(requestErr.Status), executor.PublicErrorMessage(executor.Classified{ + Kind: accounts.KindInvalidRequest, Status: requestErr.Status, Message: requestErr.Message, + })) return } classified := ClassifyAPIError(err) @@ -146,7 +184,27 @@ func writeAnthropicCompatibilityError(w http.ResponseWriter, err error) { } w.Header().Set("Retry-After", fmt.Sprintf("%d", seconds)) } - writeAnthropicError(w, classified.Status, anthropicErrorType(classified.Kind), classified.Message) + writeAnthropicError(w, classified.Status, anthropicErrorType(classified.Kind), executor.PublicErrorMessage(classified)) +} + +func anthropicErrorTypeForStatus(status int) string { + switch status { + case http.StatusBadRequest, http.StatusUnprocessableEntity: + return "invalid_request_error" + case http.StatusUnauthorized: + return "authentication_error" + case http.StatusForbidden: + return "permission_error" + case http.StatusNotFound: + return "not_found_error" + case http.StatusTooManyRequests: + return "rate_limit_error" + default: + if status >= 500 { + return "api_error" + } + return "invalid_request_error" + } } func writeAnthropicError(w http.ResponseWriter, status int, errorType, message string) { @@ -188,6 +246,38 @@ func shouldRectifyAnthropicRequest(raw []byte) bool { } } +func anthropicCanonicalMessageResponse(requestID, model string, turn toolcall.TurnResult, promptTokens, completionTokens int, cacheReadTokens, cacheWriteTokens *int) (map[string]any, error) { + canonicalBlocks, err := toolcall.RenderMessagesBlocks(turn) + if err != nil { + return nil, err + } + blocks := make([]any, 0, 2+len(canonicalBlocks)) + if turn.Reasoning != "" { + blocks = append(blocks, map[string]any{"type": "thinking", "thinking": turn.Reasoning}) + } + for _, block := range canonicalBlocks { + switch block.Type { + case "text": + blocks = append(blocks, map[string]any{"type": "text", "text": block.Text}) + case "tool_use": + input := block.Input + if len(input) == 0 { + input = json.RawMessage(`{}`) + } + blocks = append(blocks, map[string]any{"type": "tool_use", "id": block.ID, "name": block.Name, "input": input}) + } + } + if len(blocks) == 0 { + blocks = append(blocks, map[string]any{"type": "text", "text": ""}) + } + finishReason := toolcall.RenderChat(turn).FinishReason + return map[string]any{ + "id": "msg_" + requestID, "type": "message", "role": "assistant", "model": model, + "content": blocks, "stop_reason": anthropicStopReason(finishReason, canonicalProxyToolCalls(turn)), "stop_sequence": nil, + "usage": anthropicUsage(promptTokens, completionTokens, cacheReadTokens, cacheWriteTokens), + }, nil +} + func anthropicMessageResponse(requestID, model, content, reasoning string, toolCalls []proxyToolCall, finishReason string, promptTokens, completionTokens int, cacheReadTokens, cacheWriteTokens *int) map[string]any { blocks := make([]any, 0, 2+len(toolCalls)) if reasoning != "" { @@ -197,10 +287,11 @@ func anthropicMessageResponse(requestID, model, content, reasoning string, toolC blocks = append(blocks, map[string]any{"type": "text", "text": content}) } for _, call := range toolCalls { - arguments, _ := translate.NormalizeToolCallArguments(call.Arguments) - input := json.RawMessage(arguments) - if !json.Valid(input) { + var input json.RawMessage + if call.Arguments == "" { input = json.RawMessage(`{}`) + } else { + input = json.RawMessage(call.Arguments) } blocks = append(blocks, map[string]any{"type": "tool_use", "id": call.ID, "name": call.Name, "input": input}) } diff --git a/internal/gateway/compat.go b/internal/gateway/compat.go index c0a75d7fc..c947e898f 100644 --- a/internal/gateway/compat.go +++ b/internal/gateway/compat.go @@ -41,66 +41,27 @@ func proxyToolCallItem(requestID string, callIndex int, call proxyToolCall) map[ return item } -func decodeOpenAIToolCalls(raw json.RawMessage) []proxyToolCall { - if len(raw) == 0 || string(raw) == "null" { - return nil - } - var source []struct { - ID string `json:"id"` - Function struct { - Name string `json:"name"` - Arguments string `json:"arguments"` - } `json:"function"` - } - if json.Unmarshal(raw, &source) != nil { - return nil - } - calls := make([]proxyToolCall, 0, len(source)) - for _, call := range source { - if call.Function.Name == "" { - continue - } - arguments := strings.TrimSpace(call.Function.Arguments) - if arguments == "" { - arguments = "{}" - } - if _, _, custom := translate.DecodeCustomToolName(call.Function.Name); !custom && !json.Valid([]byte(arguments)) { - normalized, _ := translate.NormalizeToolCallArguments(arguments) - arguments = normalized - } - calls = append(calls, proxyToolCall{ID: call.ID, Name: call.Function.Name, Arguments: arguments}) - } - return calls -} - -// normalizeProxyToolCallArguments makes every function call carry valid JSON -// arguments. It never fails the turn: a call the model mangled or left -// unfinished keeps only the fields it completed, so the client can run the tool -// and hand the validation error back to the model instead of the client -// aborting the whole round with "arguments are invalid JSON". -func normalizeProxyToolCallArguments(calls []proxyToolCall) bool { - changed := false - for index := range calls { - call := &calls[index] - if _, _, custom := translate.DecodeCustomToolName(call.Name); custom { - continue - } - normalized, normalizedChanged := translate.NormalizeToolCallArguments(call.Arguments) - call.Arguments = normalized - if normalizedChanged { - changed = true - } - } - return changed +func (h *Handler) PrepareCompatibilityExecution(r *http.Request, request translate.ChatRequest) (Execution, error) { + return h.prepareCompatibilityExecution(r, request, nil) } -func (h *Handler) PrepareCompatibilityExecution(r *http.Request, request translate.ChatRequest) (Execution, error) { +func (h *Handler) prepareCompatibilityExecution(r *http.Request, request translate.ChatRequest, beforeSideEffects func() error) (Execution, error) { if len(request.Messages) == 0 { return Execution{}, &chatHTTPError{Status: http.StatusBadRequest, Code: "invalid_request", Message: "input messages required"} } - return h.PrepareChatExecution(r, request) + return h.prepareExecution(r, request, nil, beforeSideEffects) } func (h *Handler) finishCompatibility(execution Execution, accountID, provider, routing, status string, ttfb int, stats *StreamRelayStats, err error, attempts int, resolvedReasoning string) { h.finishRequestLog(execution.RequestID, execution.Started, execution.Request, execution.PublicModel, accountID, firstNonEmpty(provider, execution.ProviderFilter), routing, status, ttfb, stats, err, attempts, resolvedReasoning) } + +// finalizeExecution releases the recorder's per-request buffer after the +// non-stream attempt row has been queued. Streaming paths call Finalize from +// finishRelayedStream, after FinishStream has queued the final attempt. +func (h *Handler) finalizeExecution(execution Execution) { + if h == nil || h.Recorder == nil || execution.RequestID == "" { + return + } + h.Recorder.Finalize(execution.RequestID) +} diff --git a/internal/gateway/compat_stream.go b/internal/gateway/compat_stream.go index 8fd5a2710..da6630f59 100644 --- a/internal/gateway/compat_stream.go +++ b/internal/gateway/compat_stream.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "log" "net/http" "sort" "strings" @@ -15,12 +14,23 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) -func (h *Handler) observeCompatibilityStreamFailure(r *http.Request, execution Execution, upstream executor.StreamResult, relayErr error) { - if r.Context().Err() == nil && !errors.Is(relayErr, context.Canceled) && !errors.Is(relayErr, context.DeadlineExceeded) && !IsStreamClientDisconnect(relayErr) { - h.Executor.ObserveStreamFailure(firstNonEmpty(upstream.PoolAccountID, upstream.AccountID), relayErr, execution.Request.Model) +func (h *Handler) finishRelayedStream(ctx context.Context, upstream executor.StreamResult, relayErr error) { + // A downstream write failure cancels the attempt; it says nothing about + // the selected account. The executor owns the target for upstream outcomes. + if IsStreamClientDisconnect(relayErr) { + h.Executor.FinishStream(ctx, upstream, executor.ClientDisconnectError(relayErr)) + } else { + h.Executor.FinishStream(ctx, upstream, relayErr) + } + // FinishStream writes the main log before the final attempt. Only after + // both exist can the recorder drop the id; otherwise a late attempt loses + // its parent and an id stays buffered until TTL. + if id := executor.RequestIDFromContext(ctx); id != "" && h.Recorder != nil { + h.Recorder.Finalize(id) } } @@ -39,8 +49,8 @@ func setCompatibilityStreamHeaders(w http.ResponseWriter, accountID, provider st } func compatibilityStreamWriter(w http.ResponseWriter) io.Writer { - if flusher, ok := w.(http.Flusher); ok { - return StreamFlushWriter{W: w, F: flusher} + if flushWriter, ok := newStreamFlushWriter(w); ok { + return flushWriter } return w } @@ -55,24 +65,42 @@ func streamRequestStatus(err error) string { return accounts.RequestStatusError } -// streamLogStatus records a completed upstream stream as success even when the -// caller closes the connection after the terminal frame. A disconnect before -// that frame stays canceled; anything else stays an error. -func streamLogStatus(err error, completed bool, clientGone bool) string { +// streamLogStatus records a stream as success only when no error stopped it. +// An upstream terminal frame is not delivery: a downstream write failure before +// that terminal frame reached the client is a canceled request, not success. +func streamLogStatus(err error, stats StreamRelayStats, clientGone bool) string { status := streamRequestStatus(err) if err == nil { return status } - disconnected := clientGone || IsStreamClientDisconnect(err) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) + disconnected := clientGone || streamClientGone(err) if !disconnected { return accounts.RequestStatusError } - if completed { + if stats.DownstreamDone { return accounts.RequestStatusOK } return accounts.RequestStatusCanceled } +// streamClientGone distinguishes a real downstream/client cancellation from a +// classified upstream timeout whose message happens to wrap context.Canceled. +// An ExecutionError classified as unavailable is upstream evidence; a raw +// context error with no conflict is still treated as the client leaving. +func streamClientGone(err error) bool { + if err == nil { + return false + } + if IsStreamClientDisconnect(err) { + return true + } + var executionErr *executor.ExecutionError + if errors.As(err, &executionErr) && executionErr != nil && executionErr.Classified.Kind != accounts.KindCanceled { + return false + } + return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) +} + func streamTTFB(started time.Time, fallback int, stats StreamRelayStats) int { if stats.FirstTokenAt == nil { return fallback @@ -90,34 +118,45 @@ func writeSSEEvent(writer io.Writer, event string, payload any) error { return err } if event != "" { - if _, err := fmt.Fprintf(writer, "event: %s\n", event); err != nil { - return &StreamRelayWriteError{err: err} + if err := writeSSEString(writer, "event: "+event+"\n"); err != nil { + return err } } - if _, err := fmt.Fprintf(writer, "data: %s\n\n", encoded); err != nil { + if err := writeSSEString(writer, "data: "+string(encoded)+"\n\n"); err != nil { + return err + } + return nil +} + +func writeSSEString(writer io.Writer, value string) error { + n, err := writer.Write([]byte(value)) + if err != nil { return &StreamRelayWriteError{err: err} } + if n < len(value) { + return &StreamRelayWriteError{err: io.ErrShortWrite} + } return nil } func writeAnthropicStreamError(writer io.Writer, err error) error { classified := ClassifyAPIError(err) - return writeSSEEvent(writer, "error", map[string]any{"type": "error", "error": map[string]string{"type": anthropicErrorType(classified.Kind), "message": classified.Message}}) + return writeSSEEvent(writer, "error", map[string]any{"type": "error", "error": map[string]string{"type": anthropicErrorType(classified.Kind), "message": executor.PublicErrorMessage(classified)}}) } func writeResponsesStreamError(writer io.Writer, err error) error { classified := ClassifyAPIError(err) - return writeSSEEvent(writer, "error", map[string]any{"type": "error", "error": map[string]any{"type": classified.Type, "code": classified.Code, "message": classified.Message}}) + return writeSSEEvent(writer, "error", map[string]any{"type": "error", "error": map[string]any{"type": openaiErrorType(classified), "code": classified.Code, "message": executor.PublicErrorMessage(classified)}}) } type streamedChatOutput struct { content strings.Builder reasoning strings.Builder - toolCalls map[int]*proxyToolCall finishReason string - // resolved maps a chunk's tool_call position to the call index it belongs - // to, so converters can reuse the same grouping the accumulator chose. - resolved []int + + canonical *toolcall.Reducer + canonicalResult toolcall.TurnResult + canonicalErr error } func (o *streamedChatOutput) add(payload json.RawMessage) { @@ -141,8 +180,6 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { if json.Unmarshal(payload, &chunk) != nil { return } - o.resolved = o.resolved[:0] - lastIndex := -1 for _, choice := range chunk.Choices { if choice.FinishReason != "" { o.finishReason = choice.FinishReason @@ -153,78 +190,36 @@ func (o *streamedChatOutput) add(payload json.RawMessage) { if choice.Delta.ReasoningContent != "" { o.reasoning.WriteString(choice.Delta.ReasoningContent) } - for callPosition, delta := range choice.Delta.ToolCalls { - if o.toolCalls == nil { - o.toolCalls = map[int]*proxyToolCall{} - } - index := o.resolveToolCallIndex(delta.Index, delta.ID, delta.Function.Name, callPosition, lastIndex) - lastIndex = index - call := o.toolCalls[index] - if call == nil { - call = &proxyToolCall{} - o.toolCalls[index] = call - } - if delta.ID != "" { - call.ID = delta.ID - } - if delta.Function.Name != "" { - call.Name = delta.Function.Name - } - call.Arguments = mergeToolArguments(call.Arguments, argumentFragment(delta.Function.Arguments)) - o.resolved = append(o.resolved, index) + if o.canonical == nil { + continue + } + delta := toolcall.ChatDelta{Content: choice.Delta.Content, Reasoning: choice.Delta.ReasoningContent, FinishReason: choice.FinishReason} + for position := range choice.Delta.ToolCalls { + toolDelta := choice.Delta.ToolCalls[position] + delta.ToolCalls = append(delta.ToolCalls, toolcall.ChatToolDelta{ + Index: toolDelta.Index, + ID: toolDelta.ID, + Name: toolDelta.Function.Name, + Arguments: argumentFragment(toolDelta.Function.Arguments), + }) + } + if _, err := o.canonical.Absorb(delta); err != nil { + o.canonicalErr = err } } } -// resolveToolCallIndex keeps fragments with one call together. Upstreams that -// omit `index` either keep streaming the same call (no id/name, fold into -// the previous one) or start a new call (id or name present, next slot). -func (o *streamedChatOutput) resolveToolCallIndex(declared *int, id, name string, position, lastIndex int) int { - startsCall := id != "" || name != "" - switch { - case declared != nil && *declared > 0: - return *declared - case declared != nil && !startsCall: - return *declared - case declared != nil && startsCall: - if o.callIsDifferent(*declared, id, name) { - return maxToolCallIndex(o.toolCalls) + 1 - } - return *declared - case startsCall: - if position == 0 && !o.callIsDifferent(0, id, name) { - return 0 - } - return maxToolCallIndex(o.toolCalls) + 1 - case lastIndex >= 0: - return lastIndex - default: - return position - } -} - -// callIsDifferent reports whether this delta starts a new call on an index -// that already holds one. Two calls of the same tool are common, so the -// call id is what separates them; a name-only comparison would merge them. -func (o *streamedChatOutput) callIsDifferent(index int, id, name string) bool { - existing := o.toolCalls[index] - if existing == nil || (existing.Name == "" && existing.ID == "") { - return false - } - if id != "" && existing.ID != "" { - return existing.ID != id +func (o *streamedChatOutput) finalize(terminal string) error { + if o == nil || o.canonical == nil { + return nil } - return name != "" && existing.Name != "" && existing.Name != name -} - -func maxToolCallIndex(calls map[int]*proxyToolCall) int { - maximum := -1 - for index := range calls { - if index > maximum { - maximum = index - } + result, err := o.canonical.Finish(terminal) + o.canonicalResult = result + if err != nil { + o.canonicalErr = err + return err } - return maximum + return nil } // argumentFragment normalizes the arguments field of a stream delta. Some @@ -247,49 +242,41 @@ func argumentFragment(raw json.RawMessage) string { return "" } -// mergeToolArguments appends a delta fragment, but tolerates upstreams that -// resend the whole argument buffer (or its tail) on every chunk — concatenating -// those blindly is what produces `{"a":1}{"a":1}` and an invalid tool call. -func mergeToolArguments(base, fragment string) string { - if fragment == "" { - return base - } - if base == "" { - return fragment +func (o *streamedChatOutput) canonicalFinishReason() string { + if o == nil { + return "" } - if len(fragment) > len(base) && strings.HasPrefix(fragment, base) { - return fragment + if o.canonicalResult.Status == toolcall.TurnToolCalls { + return "tool_calls" } - if len(fragment) >= 8 && strings.HasSuffix(base, fragment) { - return base + if o.canonicalResult.FinishReason != "" { + return o.canonicalResult.FinishReason } - return base + fragment + return "stop" } func (o *streamedChatOutput) calls() []proxyToolCall { - indexes := make([]int, 0, len(o.toolCalls)) - for index := range o.toolCalls { - indexes = append(indexes, index) + if o == nil { + return nil } - sort.Ints(indexes) - calls := make([]proxyToolCall, 0, len(indexes)) - for _, index := range indexes { - call := o.toolCalls[index] - if call == nil || call.Name == "" { - continue - } - calls = append(calls, *call) + calls := make([]proxyToolCall, 0, len(o.canonicalResult.Calls)) + for _, call := range o.canonicalResult.Calls { + calls = append(calls, proxyToolCall{ID: call.InternalID, Name: call.Name, Arguments: string(call.Arguments)}) } return calls } -func consumeOpenAIStream(body io.Reader, handle func(json.RawMessage, *streamedChatOutput) error) (StreamRelayStats, streamedChatOutput, error) { +func consumeOpenAIStream(body io.Reader, handle func(json.RawMessage, *streamedChatOutput) error, requests ...toolcall.Request) (StreamRelayStats, streamedChatOutput, error) { var stats StreamRelayStats var output streamedChatOutput + var declared toolcall.Request + if len(requests) > 0 { + declared = requests[0] + } + output.canonical = toolcall.NewReducer(declared) scanner := bufio.NewScanner(body) scanner.Buffer(make([]byte, 0, 64*1024), maxSSELineSize) var frame []string - sawDone := false flush := func() error { if len(frame) == 0 { return nil @@ -300,7 +287,7 @@ func consumeOpenAIStream(body io.Reader, handle func(json.RawMessage, *streamedC return classified } if strings.TrimSpace(data) == "[DONE]" { - sawDone = true + stats.SawDone = true return nil } payload := json.RawMessage(strings.TrimSpace(data)) @@ -323,7 +310,7 @@ func consumeOpenAIStream(body io.Reader, handle func(json.RawMessage, *streamedC for scanner.Scan() { line := strings.TrimSuffix(scanner.Text(), "\r") if line == "" { - if err := flush(); err != nil { + if err := flush(); err != nil || stats.SawDone { return stats, output, err } continue @@ -333,17 +320,15 @@ func consumeOpenAIStream(body io.Reader, handle func(json.RawMessage, *streamedC if err := scanner.Err(); err != nil { return stats, output, executor.StreamReadError(err) } - if err := flush(); err != nil { + if err := flush(); err != nil || stats.SawDone { return stats, output, err } - if !sawDone { - return stats, output, executor.StreamIncompleteError() - } - stats.SawDone = true - return stats, output, nil + return stats, output, executor.StreamIncompleteError() } -func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model string) (StreamRelayStats, error) { +func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model string, requests ...toolcall.Request) (StreamRelayStats, error) { + body, stopFirstFrame := guardFirstFrame(body) + defer stopFirstFrame() messageID := "msg_" + requestID if err := writeSSEEvent(writer, "message_start", map[string]any{"type": "message_start", "message": map[string]any{ "id": messageID, "type": "message", "role": "assistant", "model": model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil, @@ -377,7 +362,7 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str textStarted = false return nil } - stats, output, err := consumeOpenAIStream(body, func(payload json.RawMessage, current *streamedChatOutput) error { + stats, output, err := consumeOpenAIStream(body, func(payload json.RawMessage, _ *streamedChatOutput) error { var chunk struct { Choices []struct { Delta struct { @@ -427,54 +412,41 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str return err } } - for callPosition, delta := range choice.Delta.ToolCalls { - if err := closeThinking(); err != nil { - return err - } - index, ok := resolvedCallIndex(current, callPosition) - if !ok { - continue - } - blockIndex, exists := toolBlocks[index] - if !exists && delta.Function.Name != "" { - if textStarted { - if err := closeText(); err != nil { - return err - } - } - blockIndex = nextBlock - nextBlock++ - toolBlocks[index] = blockIndex - callID := delta.ID - if callID == "" { - callID = fmt.Sprintf("toolu_%s_%d", requestID, index) - } - if err := writeSSEEvent(writer, "content_block_start", map[string]any{"type": "content_block_start", "index": blockIndex, "content_block": map[string]any{"type": "tool_use", "id": callID, "name": delta.Function.Name, "input": map[string]any{}}}); err != nil { - return err - } - exists = true - } - if !exists { - continue - } - } } return nil - }) + }, requests...) if err != nil { return stats, err } + if err := output.finalize("done"); err != nil { + if writeErr := writeAnthropicStreamError(writer, err); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return stats, writeErr + } + stats.DownstreamTerminal, stats.FlushState = "error", "ok" + return stats, err + } if err := closeThinking(); err != nil { return stats, err } if err := closeText(); err != nil { return stats, err } - // Arguments are held until the block closes so they can be normalized - // first: a damaged buffer would otherwise reach the client as several - // input_json_delta fragments that never parse. - if err := writeToolArguments(writer, &output, toolBlocks, requestID, model); err != nil { - return stats, err + toolBlocks = map[int]int{} + for callIndex, call := range output.canonicalResult.Calls { + blockIndex := nextBlock + nextBlock++ + toolBlocks[callIndex] = blockIndex + callID := call.InternalID + if callID == "" { + callID = fmt.Sprintf("toolu_%s_%d", requestID, callIndex) + } + if err := writeSSEEvent(writer, "content_block_start", map[string]any{"type": "content_block_start", "index": blockIndex, "content_block": map[string]any{"type": "tool_use", "id": callID, "name": call.Name, "input": map[string]any{}}}); err != nil { + return stats, err + } + if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": string(call.Arguments)}}); err != nil { + return stats, err + } } for _, blockIndex := range sortedBlockIndexes(toolBlocks) { if err := writeSSEEvent(writer, "content_block_stop", map[string]any{"type": "content_block_stop", "index": blockIndex}); err != nil { @@ -485,13 +457,17 @@ func RelayAnthropicStream(writer io.Writer, body io.Reader, requestID, model str // message_start goes out before any usage is known, so the final counts, // input included, ride on message_delta. deltaUsage := anthropicUsage(derefInt(stats.PromptTokens), derefInt(stats.CompletionTokens), stats.CacheReadTokens, stats.CacheWriteTokens) - if err := writeSSEEvent(writer, "message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": anthropicStopReason(output.finishReason, calls), "stop_sequence": nil}, "usage": deltaUsage}); err != nil { + if err := writeSSEEvent(writer, "message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": anthropicStopReason(output.canonicalFinishReason(), calls), "stop_sequence": nil}, "usage": deltaUsage}); err != nil { return stats, err } if err := writeSSEEvent(writer, "message_stop", map[string]string{"type": "message_stop"}); err != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" return stats, err } stats.SawDone = true + stats.UpstreamTerminal = "done" + stats.DownstreamDone = true + stats.DownstreamTerminal, stats.FlushState = "done", "ok" return stats, nil } @@ -510,7 +486,9 @@ func (w *responsesEventWriter) write(event string, payload any) error { return writeSSEEvent(w.writer, event, payload) } -func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model string, names map[string]translate.ResponseToolName) (StreamRelayStats, error) { +func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model string, names map[string]translate.ResponseToolName, requests ...toolcall.Request) (StreamRelayStats, error) { + body, stopFirstFrame := guardFirstFrame(body) + defer stopFirstFrame() eventWriter := responsesEventWriter{writer: writer, toolNames: names} responseID := "resp_" + requestID created := time.Now().Unix() @@ -524,7 +502,6 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str reasoningText := strings.Builder{} toolAnnounced := map[int]bool{} toolCallIDs := map[int]string{} - toolCallNames := map[int]string{} toolOutputIndexes := map[int]int{} nextOutputIndex := 0 reasoningOutputIndex := -1 @@ -545,7 +522,7 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str reasoningStarted = false return nil } - stats, output, err := consumeOpenAIStream(body, func(payload json.RawMessage, current *streamedChatOutput) error { + stats, output, err := consumeOpenAIStream(body, func(payload json.RawMessage, _ *streamedChatOutput) error { var chunk struct { Choices []struct { Delta struct { @@ -602,57 +579,26 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str return err } } - for callPosition, delta := range choice.Delta.ToolCalls { - index, ok := resolvedCallIndex(current, callPosition) - if !ok { - continue - } - if err := closeReasoning(); err != nil { - return err - } - if delta.ID != "" { - toolCallIDs[index] = delta.ID - } - if delta.Function.Name != "" { - toolCallNames[index] = delta.Function.Name - } - if toolCallIDs[index] == "" { - toolCallIDs[index] = fmt.Sprintf("call_%s_%d", requestID, index) - } - if delta.Function.Name != "" && !toolAnnounced[index] { - toolOutputIndexes[index] = nextOutputIndex - nextOutputIndex++ - item := map[string]any{"id": fmt.Sprintf("fc_%s_%d", requestID, index), "type": "function_call", "status": "in_progress", "call_id": toolCallIDs[index], "name": toolCallNames[index], "arguments": ""} - if namespace, name, custom := translate.DecodeCustomToolName(toolCallNames[index]); custom { - item = map[string]any{"id": fmt.Sprintf("ctc_%s_%d", requestID, index), "type": "custom_tool_call", "status": "in_progress", "call_id": toolCallIDs[index], "name": name, "input": ""} - if namespace != "" { - item["namespace"] = namespace - } - } - if err := eventWriter.write("response.output_item.added", map[string]any{"type": "response.output_item.added", "output_index": toolOutputIndexes[index], "item": item}); err != nil { - return err - } - toolAnnounced[index] = true - } - // Arguments are not streamed as deltas: a damaged buffer would - // reach the client as fragments that never parse. The normalized - // full string is delivered once in response.function_call_arguments.done. - } } return nil - }) + }, requests...) if err != nil { return stats, err } - stats.FinishReason = output.finishReason + if err := output.finalize("done"); err != nil { + if writeErr := writeResponsesStreamError(writer, err); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return stats, writeErr + } + stats.DownstreamTerminal, stats.FlushState = "error", "ok" + return stats, err + } + stats.FinishReason = output.canonicalFinishReason() if err := closeReasoning(); err != nil { return stats, err } content := output.content.String() calls := output.calls() - if normalizeProxyToolCallArguments(calls) { - log.Printf("tool call arguments normalized request_id=%q model=%q finish_reason=%q calls=%d", requestID, model, output.finishReason, len(calls)) - } if textStarted { if err := eventWriter.write("response.output_text.done", map[string]any{"type": "response.output_text.done", "item_id": "msg_" + requestID, "output_index": textOutputIndex, "content_index": 0, "text": content}); err != nil { return stats, err @@ -726,65 +672,23 @@ func RelayResponsesStream(writer io.Writer, body io.Reader, requestID, model str return stats, err } } - terminal := responsesTerminalForFinishReason(output.finishReason) + terminal := responsesTerminalForFinishReason(output.canonicalFinishReason()) response := responsesResponse( requestID, model, content, output.reasoning.String(), calls, - derefInt(stats.PromptTokens), derefInt(stats.CompletionTokens), output.finishReason, + derefInt(stats.PromptTokens), derefInt(stats.CompletionTokens), output.canonicalFinishReason(), stats.CacheReadTokens, stats.CacheWriteTokens, stats.CachedTokens, stats.ReasoningTokens, ) if err := eventWriter.write(terminal.event, map[string]any{"type": terminal.event, "response": response}); err != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" return stats, err } + stats.SawDone = true + stats.UpstreamTerminal = "done" + stats.DownstreamDone = true + stats.DownstreamTerminal, stats.FlushState = "done", "ok" return stats, nil } -// writeToolArguments emits one normalized input_json_delta per tool block. The -// Anthropic wire format has no way to retract a delta, so the arguments are -// buffered to block-close time; that keeps a damaged buffer from reaching the -// client as fragments that never parse. -func writeToolArguments(writer io.Writer, output *streamedChatOutput, toolBlocks map[int]int, requestID, model string) error { - if output == nil { - return nil - } - indexes := make([]int, 0, len(toolBlocks)) - for index := range toolBlocks { - indexes = append(indexes, index) - } - sort.Ints(indexes) - for _, index := range indexes { - blockIndex := toolBlocks[index] - call := output.toolCalls[index] - if call == nil || strings.TrimSpace(call.Arguments) == "" { - continue - } - arguments, changed := translate.NormalizeToolCallArguments(call.Arguments) - if changed { - log.Printf("tool call arguments normalized request_id=%q model=%q tool=%q truncated=%v", requestID, model, call.Name, !json.Valid([]byte(strings.TrimSpace(call.Arguments)))) - } - if err := writeSSEEvent(writer, "content_block_delta", map[string]any{"type": "content_block_delta", "index": blockIndex, "delta": map[string]string{"type": "input_json_delta", "partial_json": arguments}}); err != nil { - return err - } - } - return nil -} - -func resolvedCallIndex(output *streamedChatOutput, position int) (int, bool) { - if output == nil || position >= len(output.resolved) { - return 0, false - } - return output.resolved[position], true -} - -func accumulatedToolArguments(output *streamedChatOutput, index int) string { - if output == nil { - return "" - } - if call := output.toolCalls[index]; call != nil { - return call.Arguments - } - return "" -} - func sortedBlockIndexes(blocks map[int]int) []int { indexes := make([]int, 0, len(blocks)) for _, blockIndex := range blocks { diff --git a/internal/gateway/entry_body_test.go b/internal/gateway/entry_body_test.go new file mode 100644 index 000000000..fac9c2068 --- /dev/null +++ b/internal/gateway/entry_body_test.go @@ -0,0 +1,68 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "testing" +) + +func TestReadConversationBodyRequiresOneJSONValue(t *testing.T) { + cases := []struct { + name string + body string + limit int64 + wantErr error + }{ + {name: "single object", body: `{"model":"m","messages":[]}`}, + {name: "trailing whitespace", body: `{"model":"m","messages":[]}` + "\n\t "}, + {name: "trailing object", body: `{"model":"m"}{"model":"other"}`, wantErr: ErrMultipleJSONValues}, + {name: "trailing object split", body: `{"model":"m"}` + "\n" + `{"extra":true}`, wantErr: ErrMultipleJSONValues}, + {name: "truncated", body: `{"model":`, wantErr: io.ErrUnexpectedEOF}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + limit := tc.limit + if limit == 0 { + limit = int64(len(tc.body) + 1) + } + got, err := readConversationBody(bytes.NewReader([]byte(tc.body)), limit) + if tc.wantErr != nil { + if !errors.Is(err, tc.wantErr) { + t.Fatalf("err = %v, want %v", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("err = %v", err) + } + var decoded map[string]any + if err := json.Unmarshal(got, &decoded); err != nil { + t.Fatalf("returned body is not the first object: %v", err) + } + }) + } +} + +func TestReadConversationBodyRejectsOverLimit(t *testing.T) { + body := `{"model":"m","messages":[{"role":"user","content":"` + string(bytes.Repeat([]byte("a"), 64)) + `"}]}` + _, err := readConversationBody(bytes.NewReader([]byte(body)), 32) + var maxErr *http.MaxBytesError + if !errors.As(err, &maxErr) { + t.Fatalf("err = %v (%T), want MaxBytesError", err, err) + } +} + +func TestAnthropicPrepareErrorTypes(t *testing.T) { + if got := anthropicErrorTypeForStatus(http.StatusForbidden); got != "permission_error" { + t.Fatalf("403 type = %s", got) + } + if got := anthropicErrorTypeForStatus(http.StatusServiceUnavailable); got != "api_error" { + t.Fatalf("503 type = %s", got) + } + if got := anthropicErrorTypeForStatus(http.StatusTooManyRequests); got != "rate_limit_error" { + t.Fatalf("429 type = %s", got) + } +} diff --git a/internal/gateway/entry_rejection.go b/internal/gateway/entry_rejection.go new file mode 100644 index 000000000..f259e733a --- /dev/null +++ b/internal/gateway/entry_rejection.go @@ -0,0 +1,69 @@ +package gateway + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +// recordEntryRejection writes one terminal log row for a request rejected +// before Prepare could start it: malformed body, key concurrency, or a route +// resolution error. The entry request id is allocated before auth, so a client +// holding it can always find the reason for the rejection. +func (h *Handler) recordEntryRejection(r *http.Request, model string, kind, code, message string) { + if h == nil || h.Recorder == nil || r == nil { + return + } + id := executor.EntryRequestIDFromContext(r.Context()) + if id == "" { + return + } + if h.Recorder.WasDeclared(id) { + return + } + now := time.Now().UTC() + entry := accounts.RequestLog{ + ID: id, + CreatedAt: now, + FinishedAt: &now, + Status: accounts.RequestStatusError, + RequestedModel: strings.TrimSpace(model), + ErrorKind: kind, + ErrorCode: code, + ErrorMessage: message, + RequestState: executor.RequestStateNotSent, + } + h.Recorder.Start(entry) + h.Recorder.Finish(entry) + h.Recorder.Finalize(id) +} + +// recordPrepareRejection classifies a pre-execution Prepare failure and writes +// the same terminal row as an entry rejection. Prepare failures that already +// started a log are skipped via WasDeclared. +func (h *Handler) recordPrepareRejection(r *http.Request, model string, err error) { + if err == nil { + return + } + if errors.Is(err, errKeyConcurrencyLimited) { + h.recordEntryRejection(r, model, accounts.KindRateLimit, "rate_limit", err.Error()) + return + } + var prepareErr *chatHTTPError + if errors.As(err, &prepareErr) && prepareErr != nil { + kind := accounts.KindInvalidRequest + if prepareErr.Status == http.StatusTooManyRequests { + kind = accounts.KindRateLimit + } else if prepareErr.Status >= 500 { + kind = accounts.KindUnavailable + } + h.recordEntryRejection(r, model, kind, prepareErr.Code, prepareErr.Message) + return + } + classified := ClassifyAPIError(err) + h.recordEntryRejection(r, model, classified.Kind, classified.Code, classified.Message) +} diff --git a/internal/gateway/fefo_quota_test.go b/internal/gateway/fefo_quota_test.go index cf8f726ae..053ce69a5 100644 --- a/internal/gateway/fefo_quota_test.go +++ b/internal/gateway/fefo_quota_test.go @@ -1,31 +1,99 @@ package gateway import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" "testing" "time" - "github.com/caigee-cmd/cli2api/internal/accounts" - "github.com/caigee-cmd/cli2api/internal/translate" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" ) +type firstDeltaRecorder struct { + *httptest.ResponseRecorder + delta chan struct{} + once sync.Once +} + +func (w *firstDeltaRecorder) Flush() { + w.ResponseRecorder.Flush() + if strings.Contains(w.Body.String(), "response.output_text.delta") { + w.once.Do(func() { close(w.delta) }) + } +} + func TestQuotaInvalidationRunsAfterTerminalResponseNotStreamHeaders(t *testing.T) { - var calls []string - h := &Handler{AfterAccountUse: func(id, model string) { calls = append(calls, id+":"+model) }} - finish := func(status, id, publicModel string) { - h.finishRequestLog("", time.Now(), translate.ChatRequest{Model: "paid"}, publicModel, id, "workbuddy", "", status, 0, nil, nil, 1, "") + const poolID, model = "qoder-pool", "paid" + allowFinish := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(allowFinish) }) + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"first"}}]}`+"\n\n") + w.(http.Flusher).Flush() + <-allowFinish + _, _ = io.WriteString(w, `data: {"choices":[{"finish_reason":"stop"}]}`+"\n\n"+"data: [DONE]\n\n") + })) + defer worker.Close() + defer unblock() + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: poolID, URL: worker.URL, Provider: "qoder", Region: "global", Runtime: "child_process", Models: []string{model}, MaxInFlight: 1}) + ex := executor.NewChatExecutor(pool, "") + ex.HTTPClient = worker.Client() + quotaRefresh := make(chan string, 2) + h := &Handler{Executor: ex, Pool: pool, KeyLimits: &KeyInFlight{}, AfterAccountUse: func(id, routedModel string, aggregateFEFO bool) { + item, _ := pool.ByID(id) + if item.InFlight != 0 { + t.Errorf("quota invalidation happened before releasing the account slot: %+v", item) + } + quotaRefresh <- id + ":" + routedModel + }} + id := auth.Identity{Kind: auth.KindKey, KeyID: "limited", MaxInFlight: 1} + const path, input = "/v1/responses", `{"model":"qoder/paid","stream":true,"input":"hello"}` + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(input)) + w := &firstDeltaRecorder{ResponseRecorder: httptest.NewRecorder(), delta: make(chan struct{})} + done := make(chan struct{}) + go func() { + defer close(done) + h.HandleResponses(w, req.WithContext(auth.WithIdentity(req.Context(), id))) + }() + select { + case <-w.delta: + case <-done: + t.Fatalf("stream stopped before the first delta: %d %s", w.Code, w.Body.String()) + case <-time.After(5 * time.Second): + t.Fatal("first delta not relayed") + } + if extra := callGateway(h.HandleResponses, path, input, id); extra.Code != http.StatusTooManyRequests { + t.Fatalf("second request while stream was open: %d %s", extra.Code, extra.Body.String()) + } + select { + case call := <-quotaRefresh: + t.Fatalf("quota invalidation before stream finished: %s", call) + default: } - finish(accounts.RequestStatusStarted, "synthetic", "paid") - finish(accounts.RequestStatusStreaming, "synthetic", "paid") - finish(accounts.RequestStatusOK, "", "paid") - if len(calls) != 0 { - t.Fatalf("invalidated before account use finished: %v", calls) + unblock() + select { + case <-done: + if !strings.Contains(w.Body.String(), "response.completed") { + t.Fatalf("stream did not finish: %s", w.Body.String()) + } + case <-time.After(5 * time.Second): + t.Fatal("stream did not close") } - for _, status := range []string{accounts.RequestStatusOK, accounts.RequestStatusIncomplete, accounts.RequestStatusError, accounts.RequestStatusCanceled} { - finish(status, "synthetic", "paid") + select { + case call := <-quotaRefresh: + if call != poolID+":"+model { + t.Fatalf("quota invalidation used %s", call) + } + default: + t.Fatal("missing terminal quota invalidation") } - finish(accounts.RequestStatusOK, "synthetic", "workbuddy-cn/paid") - h.finishRequestLog("", time.Now(), translate.ChatRequest{Model: "alias"}, "workbuddy/alias", "synthetic", "workbuddy", "", accounts.RequestStatusOK, 0, nil, nil, 1, "") - if len(calls) != 6 || calls[0] != "synthetic:paid" || calls[4] != "synthetic:paid" || calls[5] != "synthetic:alias" { - t.Fatalf("terminal response invalidations = %v", calls) + if !h.KeyLimits.acquire(id) { + t.Fatal("Key slot did not release after stream completed") } + h.KeyLimits.release(id) } diff --git a/internal/gateway/first_frame.go b/internal/gateway/first_frame.go new file mode 100644 index 000000000..9decd9bbe --- /dev/null +++ b/internal/gateway/first_frame.go @@ -0,0 +1,127 @@ +package gateway + +import ( + "io" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/caigee-cmd/cli2api/internal/executor" +) + +const ( + defaultFirstFrameTimeout = 2 * time.Minute + firstFrameWatchBuffer = 1 << 20 +) + +// resolveFirstFrameTimeout reads CLI2API_STREAM_FIRST_FRAME_TIMEOUT_MS. This +// window starts only after the upstream response head arrived; it is separate +// from connect and first-byte deadlines because a proxy can return 200 and +// then black-hole the SSE body indefinitely. +func resolveFirstFrameTimeout() time.Duration { + raw := strings.TrimSpace(os.Getenv("CLI2API_STREAM_FIRST_FRAME_TIMEOUT_MS")) + if raw == "" { + return defaultFirstFrameTimeout + } + ms, err := strconv.Atoi(raw) + if err != nil || ms <= 0 { + return defaultFirstFrameTimeout + } + return time.Duration(ms) * time.Millisecond +} + +// firstFrameGuard wraps an upstream body and closes it if no frame carrying a +// non-empty data field arrives within the window. Heartbeat comments and blank +// frames do not stop the timer: only a protocol payload counts as progress. +type firstFrameGuard struct { + body io.Reader + closer io.Closer + timeout time.Duration + timer *time.Timer + timedOut atomic.Bool + seen atomic.Bool + stopOnce sync.Once + tail []byte +} + +func guardFirstFrame(body io.Reader) (io.Reader, func()) { + if body == nil { + return body, func() {} + } + guard := &firstFrameGuard{body: body, timeout: resolveFirstFrameTimeout()} + if closer, ok := body.(io.Closer); ok && guard.timeout > 0 { + guard.closer = closer + guard.timer = time.AfterFunc(guard.timeout, func() { + guard.timedOut.Store(true) + _ = closer.Close() + }) + } + return guard, guard.Stop +} + +func (g *firstFrameGuard) Stop() { + g.stopOnce.Do(func() { + if g.timer != nil { + g.timer.Stop() + } + }) +} + +func (g *firstFrameGuard) Read(p []byte) (int, error) { + n, err := g.body.Read(p) + if n > 0 && !g.seen.Load() { + g.inspect(p[:n]) + } + if err != nil && g.timedOut.Load() { + return n, executor.ErrStreamFirstFrameTimeout + } + return n, err +} + +func (g *firstFrameGuard) inspect(chunk []byte) { + g.tail = append(g.tail, chunk...) + for { + index := frameBoundary(g.tail) + if index < 0 { + if len(g.tail) > firstFrameWatchBuffer { + g.tail = g.tail[len(g.tail)-firstFrameWatchBuffer/4:] + } + return + } + frame := g.tail[:index] + g.tail = g.tail[index:] + if sseFrameHasData(frame) { + g.seen.Store(true) + g.Stop() + return + } + } +} + +func frameBoundary(b []byte) int { + for i := 0; i+1 < len(b); i++ { + if b[i] == '\n' && b[i+1] == '\n' { + return i + 2 + } + if i+3 < len(b) && b[i] == '\r' && b[i+1] == '\n' && b[i+2] == '\r' && b[i+3] == '\n' { + return i + 4 + } + } + return -1 +} + +func sseFrameHasData(frame []byte) bool { + for _, raw := range strings.Split(string(frame), "\n") { + line := strings.TrimSpace(strings.TrimSuffix(raw, "\r")) + if !strings.HasPrefix(line, "data:") { + continue + } + if strings.TrimSpace(strings.TrimPrefix(line, "data:")) != "" { + return true + } + } + return false +} diff --git a/internal/gateway/first_frame_test.go b/internal/gateway/first_frame_test.go new file mode 100644 index 000000000..a879a22e6 --- /dev/null +++ b/internal/gateway/first_frame_test.go @@ -0,0 +1,85 @@ +package gateway + +import ( + "errors" + "io" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/executor" +) + +type stagedReadCloser struct { + mu sync.Mutex + stages [][]byte + closed chan struct{} + once sync.Once +} + +func (b *stagedReadCloser) Read(p []byte) (int, error) { + b.mu.Lock() + if len(b.stages) > 0 { + chunk := b.stages[0] + b.stages = b.stages[1:] + b.mu.Unlock() + copy(p, chunk) + return len(chunk), nil + } + b.mu.Unlock() + <-b.closed + return 0, io.ErrClosedPipe +} + +func (b *stagedReadCloser) Close() error { + b.once.Do(func() { close(b.closed) }) + return nil +} + +func TestFirstFrameGuardTimesOutOnHeartbeatsOnly(t *testing.T) { + t.Setenv("CLI2API_STREAM_FIRST_FRAME_TIMEOUT_MS", "30") + body := &stagedReadCloser{ + stages: [][]byte{[]byte(": keepalive\n\n")}, + closed: make(chan struct{}), + } + guarded, stop := guardFirstFrame(body) + defer stop() + if _, err := guarded.Read(make([]byte, 64)); err != nil { + t.Fatalf("comment read: %v", err) + } + done := make(chan error, 1) + go func() { + _, err := guarded.Read(make([]byte, 64)) + done <- err + }() + select { + case err := <-done: + if !errors.Is(err, executor.ErrStreamFirstFrameTimeout) { + t.Fatalf("err = %v, want first-frame timeout", err) + } + case <-time.After(2 * time.Second): + t.Fatal("guard did not close a heartbeat-only body") + } +} + +func TestFirstFrameGuardStopsOnValidDataFrame(t *testing.T) { + t.Setenv("CLI2API_STREAM_FIRST_FRAME_TIMEOUT_MS", "30") + body := &stagedReadCloser{ + stages: [][]byte{[]byte("data: {\"choices\":[]}\n\n"), []byte("data: [DONE]\n\n")}, + closed: make(chan struct{}), + } + guarded, stop := guardFirstFrame(body) + defer stop() + if _, err := guarded.Read(make([]byte, 128)); err != nil { + t.Fatalf("data read: %v", err) + } + time.Sleep(60 * time.Millisecond) + select { + case <-body.closed: + t.Fatal("valid data frame did not stop the first-frame timer") + default: + } + if _, err := guarded.Read(make([]byte, 128)); err != nil { + t.Fatalf("second read after timer window: %v", err) + } +} diff --git a/internal/gateway/handler.go b/internal/gateway/handler.go index 12f1bad7b..51e7d186e 100644 --- a/internal/gateway/handler.go +++ b/internal/gateway/handler.go @@ -34,9 +34,9 @@ type Handler struct { // AggregationKeyModels builds the provider-neutral list for a key with // model aggregation on: configured logical models plus account aliases. AggregationKeyModels func(context.Context, *http.Request, []map[string]any) []map[string]any - // AfterAccountUse is an optional non-blocking quota invalidation hook. It - // runs after the response/stream finishes, never on receipt of SSE headers. - AfterAccountUse func(accountID, publicModel string) + // AfterAccountUse receives the actual pool account and routed model after + // the response/stream finishes, never on receipt of SSE headers. + AfterAccountUse func(accountID, concreteModel string, aggregateFEFO bool) // KeyLimits caps concurrent chat requests per named API key. Nil means // unlimited, which tests and the console chat path rely on. KeyLimits *KeyInFlight @@ -63,3 +63,9 @@ func (h *Handler) requestedAccount(r *http.Request) string { func (h *Handler) crossProviderPoolOn() bool { return h != nil && h.CrossProviderPool != nil && h.CrossProviderPool.Load() } + +func (h *Handler) refreshQuotaAfterUse(poolAccountID, model string, aggregateFEFO bool) { + if h.AfterAccountUse != nil && poolAccountID != "" { + h.AfterAccountUse(poolAccountID, model, aggregateFEFO) + } +} diff --git a/internal/gateway/http.go b/internal/gateway/http.go index 3521b0fd9..41dd370a3 100644 --- a/internal/gateway/http.go +++ b/internal/gateway/http.go @@ -4,24 +4,89 @@ import ( "encoding/json" "net/http" "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" ) func writeJSON(w http.ResponseWriter, status int, v any) { + _ = writeJSONResult(w, status, v) +} + +// writeJSONResult is writeJSON with the write/encode error surfaced. A handler +// that records delivery must use this instead of assuming a 200 write succeeded. +func writeJSONResult(w http.ResponseWriter, status int, v any) error { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(v) + return json.NewEncoder(w).Encode(v) } +// writeErr builds a plain OpenAI-style error envelope. The error type is +// derived from the status alone; callers holding a Classified should use the +// classified-aware path so Kind/Type drive the OpenAI error type. func writeErr(w http.ResponseWriter, status int, code, msg string) { + writeTypedErr(w, status, openaiErrorTypeForStatus(status), code, msg) +} + +func writeTypedErr(w http.ResponseWriter, status int, errType, code, msg string) { writeJSON(w, status, map[string]any{ "error": map[string]any{ "message": msg, - "type": "api_error", + "type": errType, "code": code, }, }) } +// openaiErrorType maps a classified failure onto the OpenAI error.type +// vocabulary. A recognized upstream type wins; otherwise Kind, then Status, +// supply the fallback. Clients branch on error.type (not only on code), so a +// quota or auth rejection must not surface as a generic api_error. +func openaiErrorType(classified executor.Classified) string { + switch strings.TrimSpace(classified.Type) { + case "invalid_request_error", "authentication_error", "permission_error", + "rate_limit_error", "insufficient_quota", "model_not_found", "api_error": + return classified.Type + } + switch classified.Kind { + case accounts.KindInvalidRequest, accounts.KindModelNotAvailable: + if classified.Status == http.StatusNotFound { + return "model_not_found" + } + return "invalid_request_error" + case accounts.KindAuth: + if classified.Status == http.StatusForbidden { + return "permission_error" + } + return "authentication_error" + case accounts.KindQuota: + return "insufficient_quota" + case accounts.KindRateLimit: + return "rate_limit_error" + } + return openaiErrorTypeForStatus(classified.Status) +} + +func openaiErrorTypeForStatus(status int) string { + switch { + case status == http.StatusUnauthorized: + return "authentication_error" + case status == http.StatusForbidden: + return "permission_error" + case status == http.StatusNotFound: + return "model_not_found" + case status == http.StatusTooManyRequests: + return "rate_limit_error" + case status == http.StatusBadRequest || status == http.StatusUnprocessableEntity || + status == http.StatusRequestEntityTooLarge: + return "invalid_request_error" + case status >= 500: + return "api_error" + default: + return "api_error" + } +} + func firstNonEmpty(vals ...string) string { for _, v := range vals { if s := strings.TrimSpace(v); s != "" { diff --git a/internal/gateway/http_error_type_test.go b/internal/gateway/http_error_type_test.go new file mode 100644 index 000000000..3cebb8fc9 --- /dev/null +++ b/internal/gateway/http_error_type_test.go @@ -0,0 +1,147 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +func TestOpenAIErrorTypeMapping(t *testing.T) { + cases := []struct { + name string + kind string + status int + typ string + wantType string + }{ + {"quota maps to insufficient_quota", accounts.KindQuota, http.StatusTooManyRequests, "", "insufficient_quota"}, + {"auth 401 maps to authentication_error", accounts.KindAuth, http.StatusUnauthorized, "", "authentication_error"}, + {"auth 403 maps to permission_error", accounts.KindAuth, http.StatusForbidden, "", "permission_error"}, + {"rate limit maps to rate_limit_error", accounts.KindRateLimit, http.StatusTooManyRequests, "", "rate_limit_error"}, + {"invalid request maps to invalid_request_error", accounts.KindInvalidRequest, http.StatusBadRequest, "", "invalid_request_error"}, + {"model not available 404 maps to model_not_found", accounts.KindModelNotAvailable, http.StatusNotFound, "", "model_not_found"}, + {"unavailable 502 maps to api_error", accounts.KindUnavailable, http.StatusBadGateway, "", "api_error"}, + {"recognized upstream type wins over kind", accounts.KindQuota, http.StatusTooManyRequests, "rate_limit_error", "rate_limit_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{Kind: tc.kind, Status: tc.status, Type: tc.typ} + if got := openaiErrorType(classified); got != tc.wantType { + t.Fatalf("openaiErrorType(%+v) = %q, want %q", classified, got, tc.wantType) + } + }) + } +} + +func TestOpenAIErrorTypeForStatus(t *testing.T) { + cases := map[int]string{ + http.StatusUnauthorized: "authentication_error", + http.StatusForbidden: "permission_error", + http.StatusNotFound: "model_not_found", + http.StatusTooManyRequests: "rate_limit_error", + http.StatusBadRequest: "invalid_request_error", + http.StatusUnprocessableEntity: "invalid_request_error", + http.StatusRequestEntityTooLarge: "invalid_request_error", + http.StatusBadGateway: "api_error", + http.StatusInternalServerError: "api_error", + } + for status, want := range cases { + if got := openaiErrorTypeForStatus(status); got != want { + t.Fatalf("openaiErrorTypeForStatus(%d) = %q, want %q", status, got, want) + } + } +} + +func TestWriteClassifiedErrEnvelopeCarriesTypeAndRetryAfter(t *testing.T) { + classified := executor.Classified{ + Kind: accounts.KindQuota, + Status: http.StatusTooManyRequests, + Code: "insufficient_quota", + Message: "upstream diagnostic that must not reach the client", + RetryAfter: 45 * time.Second, + } + err := executor.NewExecutionError(classified, nil) + + w := httptest.NewRecorder() + WriteClassifiedErr(w, err) + + if w.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want %d", w.Code, http.StatusTooManyRequests) + } + if got := w.Header().Get("Retry-After"); got != "45" { + t.Fatalf("Retry-After = %q, want 45", got) + } + + var body struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode error envelope: %v", err) + } + if body.Error.Type != "insufficient_quota" { + t.Fatalf("error.type = %q, want insufficient_quota", body.Error.Type) + } + if body.Error.Code != "insufficient_quota" { + t.Fatalf("error.code = %q, want insufficient_quota", body.Error.Code) + } +} + +func TestStructuredStreamErrorCarriesMappedType(t *testing.T) { + cases := []struct { + name string + kind string + status int + wantType string + }{ + {name: "quota", kind: accounts.KindQuota, status: http.StatusTooManyRequests, wantType: "insufficient_quota"}, + {name: "rate limit", kind: accounts.KindRateLimit, status: http.StatusTooManyRequests, wantType: "rate_limit_error"}, + {name: "auth", kind: accounts.KindAuth, status: http.StatusUnauthorized, wantType: "authentication_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{ + Kind: tc.kind, + Status: tc.status, + Code: "test_code", + } + err := executor.NewExecutionError(classified, nil) + var buf bytes.Buffer + if werr := writeStructuredStreamError(&buf, err); werr != nil { + t.Fatalf("writeStructuredStreamError: %v", werr) + } + var dataLine string + for _, line := range strings.Split(buf.String(), "\n") { + if strings.HasPrefix(line, "data:") { + dataLine = strings.TrimSpace(strings.TrimPrefix(line, "data:")) + } + } + var envelope struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Kind string `json:"kind"` + } `json:"error"` + } + if jerr := json.Unmarshal([]byte(dataLine), &envelope); jerr != nil { + t.Fatalf("decode stream error payload: %v", jerr) + } + if envelope.Error.Type != tc.wantType { + t.Fatalf("error.type = %q, want %q", envelope.Error.Type, tc.wantType) + } + if envelope.Error.Kind != tc.kind { + t.Fatalf("error.kind = %q, want %q", envelope.Error.Kind, tc.kind) + } + }) + } +} diff --git a/internal/gateway/keylimit.go b/internal/gateway/keylimit.go index f6d06f73c..0adfe8ed6 100644 --- a/internal/gateway/keylimit.go +++ b/internal/gateway/keylimit.go @@ -1,6 +1,7 @@ package gateway import ( + "errors" "net/http" "sync" @@ -49,27 +50,37 @@ func (k *KeyInFlight) release(identity auth.Identity) { k.count[identity.KeyID]-- } -// reserveKeySlot takes one concurrency slot for a named key. A false result -// is a 429 the caller should write and return from. The returned function -// releases the slot and is safe to call when nothing was reserved. -func (h *Handler) reserveKeySlot(r *http.Request) (func(), bool) { +var errKeyConcurrencyLimited = errors.New("API key concurrency limit reached") + +// keySlotHooks gives Prepare a gate after pure validation and before side +// effects. The handler defers release before calling Prepare, keeping the +// slot through dispatch and response writing (including a stream body). +func (h *Handler) keySlotHooks(r *http.Request) (reserve func() error, release func()) { identity := h.requestIdentity(r) - if h == nil || h.KeyLimits == nil || !h.KeyLimits.acquire(identity) { - if h == nil || h.KeyLimits == nil { - return func() {}, true + limits := h.KeyLimits + held := false + return func() error { + if limits != nil && !held { + if !limits.acquire(identity) { + return errKeyConcurrencyLimited + } + held = true + } + return nil + }, func() { + if held { + limits.release(identity) + held = false + } } - return func() {}, false - } - var once sync.Once - return func() { once.Do(func() { h.KeyLimits.release(identity) }) }, true } func writeKeyConcurrencyLimited(w http.ResponseWriter) { w.Header().Set("Retry-After", "1") - writeErr(w, http.StatusTooManyRequests, "rate_limit", "API key concurrency limit reached") + writeErr(w, http.StatusTooManyRequests, "rate_limit", errKeyConcurrencyLimited.Error()) } func writeAnthropicKeyConcurrencyLimited(w http.ResponseWriter) { w.Header().Set("Retry-After", "1") - writeAnthropicError(w, http.StatusTooManyRequests, "rate_limit_error", "API key concurrency limit reached") + writeAnthropicError(w, http.StatusTooManyRequests, "rate_limit_error", errKeyConcurrencyLimited.Error()) } diff --git a/internal/gateway/keylimit_test.go b/internal/gateway/keylimit_test.go index 9121da02c..5b5f6a8c5 100644 --- a/internal/gateway/keylimit_test.go +++ b/internal/gateway/keylimit_test.go @@ -2,15 +2,21 @@ package gateway import ( "bytes" + "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" + "strings" "sync" + "sync/atomic" "testing" "time" + "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/auth" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/translate" ) func TestKeyConcurrencyLimitRejectsTheExtraRequest(t *testing.T) { @@ -50,6 +56,136 @@ func TestKeyConcurrencyLimitRejectsTheExtraRequest(t *testing.T) { } } +type testAggregationResolver func(context.Context, string, map[string]bool) (accounts.Aggregation, error) + +func (f testAggregationResolver) Resolve(ctx context.Context, id string, allowed map[string]bool) (accounts.Aggregation, error) { + return f(ctx, id, allowed) +} + +type testCatalogPreparer func() + +func (f testCatalogPreparer) EnsureModelCatalogs(context.Context, bool) { f() } + +type testRequestStarter func(accounts.RequestLog) + +func (f testRequestStarter) Start(entry accounts.RequestLog) { f(entry) } + +func callGateway(handler http.HandlerFunc, path, body string, identity auth.Identity) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + w := httptest.NewRecorder() + handler(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) + return w +} + +func TestKeyConcurrencyRejectsBeforeAggregationClassifier(t *testing.T) { + const pipeline = `{ "version":1, "steps":[ + {"id":"route","kind":"branch","classifier":{"provider":"qoder","model":"classify"},"paths":[ + {"id":"answer","label":"Answer","intent":"answer","steps":[{"id":"m","kind":"member","provider":"qoder","model":"answer"}]} + ]} + ]}` + var resolveCalls, classifyCalls, answerCalls, catalogCalls, requestStarts atomic.Int32 + classifierStarted := make(chan struct{}) + allowClassifier := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(allowClassifier) }) + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req translate.ChatRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Errorf("decode worker request: %v", err) + w.WriteHeader(http.StatusBadRequest) + return + } + switch req.Model { + case "classify": + if classifyCalls.Add(1) == 1 { + close(classifierStarted) + <-allowClassifier + } + case "answer": + answerCalls.Add(1) + default: + t.Errorf("unexpected worker model %q", req.Model) + w.WriteHeader(http.StatusBadRequest) + return + } + _, _ = fmt.Fprint(w, `{"model":"answer","choices":[{"message":{"content":"answer"},"finish_reason":"stop"}]}`) + })) + defer worker.Close() + defer unblock() + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "qoder", URL: worker.URL, Provider: "qoder", Region: "global", Runtime: "child_process", Models: []string{"classify", "answer"}, MaxInFlight: 8}) + ex := executor.NewChatExecutor(pool, "") + ex.HTTPClient = worker.Client() + crossProvider := &atomic.Bool{} + crossProvider.Store(true) + h := &Handler{Executor: ex, Pool: pool, KeyLimits: &KeyInFlight{}, CrossProviderPool: crossProvider, + Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + resolveCalls.Add(1) + return accounts.Aggregation{ID: id, Name: "Pipeline", Enabled: true, Document: pipeline}, nil + }), + Catalogs: testCatalogPreparer(func() { catalogCalls.Add(1) }), + Logs: testRequestStarter(func(entry accounts.RequestLog) { + if entry.Status != accounts.RequestStatusStarted || entry.APIKeyID != "limited" { + t.Errorf("unexpected log start: %+v", entry) + } + requestStarts.Add(1) + }), + } + id := auth.Identity{Kind: auth.KindKey, KeyID: "limited", MaxInFlight: 1, AllowedProviders: []string{"qoder"}} + const chatBody = `{"model":%q,"messages":[{"role":"user","content":"hello"}]}` + firstDone := make(chan *httptest.ResponseRecorder, 1) + go func() { + firstDone <- callGateway(h.HandleChatCompletions, "/v1/chat/completions", fmt.Sprintf(chatBody, "pipeline"), id) + }() + select { + case <-classifierStarted: + case <-time.After(5 * time.Second): + t.Fatal("first request did not start the aggregation classifier") + } + + catalogBefore, startsBefore := catalogCalls.Load(), requestStarts.Load() + for _, tc := range []struct { + path, body, limitError, forbiddenError string + handler http.HandlerFunc + }{ + {"/v1/chat/completions", chatBody, `"code":"rate_limit"`, `"code":"provider_not_allowed"`, h.HandleChatCompletions}, + {"/v1/messages", `{"model":%q,"messages":[{"role":"user","content":"hello"}],"max_tokens":16}`, `"type":"rate_limit_error"`, `"type":"permission_error"`, h.HandleAnthropicMessages}, + {"/v1/responses", `{"model":%q,"input":"hello"}`, `"code":"rate_limit"`, `"code":"provider_not_allowed"`, h.HandleResponses}, + } { + t.Run(tc.path, func(t *testing.T) { + got := callGateway(tc.handler, tc.path, fmt.Sprintf(tc.body, "pipeline"), id) + if got.Code != http.StatusTooManyRequests || got.Header().Get("Retry-After") != "1" || got.Header().Get("X-Request-Id") != "" || !strings.Contains(got.Body.String(), tc.limitError) { + t.Fatalf("limited response: %d %v %s", got.Code, got.Header(), got.Body.String()) + } + malformed := callGateway(tc.handler, tc.path, `{`, id) + if malformed.Code != http.StatusBadRequest || malformed.Header().Get("Retry-After") != "" { + t.Fatalf("malformed response: %d %v %s", malformed.Code, malformed.Header(), malformed.Body.String()) + } + forbidden := callGateway(tc.handler, tc.path, fmt.Sprintf(tc.body, "codex/answer"), id) + if forbidden.Code != http.StatusForbidden || forbidden.Header().Get("Retry-After") != "" || !strings.Contains(forbidden.Body.String(), tc.forbiddenError) { + t.Fatalf("forbidden response: %d %v %s", forbidden.Code, forbidden.Header(), forbidden.Body.String()) + } + }) + } + if resolveCalls.Load() != 1 || classifyCalls.Load() != 1 || answerCalls.Load() != 0 || catalogCalls.Load() != catalogBefore || requestStarts.Load() != startsBefore { + t.Fatalf("rejected requests ran Prepare effects: resolve=%d classify=%d dispatch=%d catalog=%d starts=%d", resolveCalls.Load(), classifyCalls.Load(), answerCalls.Load(), catalogCalls.Load(), requestStarts.Load()) + } + unblock() + select { + case first := <-firstDone: + if first.Code != http.StatusOK { + t.Fatalf("first request: %d %s", first.Code, first.Body.String()) + } + case <-time.After(5 * time.Second): + t.Fatal("first request did not finish") + } + if after := callGateway(h.HandleChatCompletions, "/v1/chat/completions", fmt.Sprintf(chatBody, "qoder/answer"), id); after.Code != http.StatusOK { + t.Fatalf("request after release: %d %s", after.Code, after.Body.String()) + } + if classifyCalls.Load() != 1 || answerCalls.Load() != 2 || requestStarts.Load() != 2 { + t.Fatalf("accepted counts: classify=%d dispatch=%d starts=%d", classifyCalls.Load(), answerCalls.Load(), requestStarts.Load()) + } +} + func TestKeyConcurrencyUnlimitedDoesNotCount(t *testing.T) { limits := &KeyInFlight{} identity := auth.Identity{Kind: auth.KindKey, KeyID: "key", MaxInFlight: 0} diff --git a/internal/gateway/native_delivery_test.go b/internal/gateway/native_delivery_test.go new file mode 100644 index 000000000..0923d3471 --- /dev/null +++ b/internal/gateway/native_delivery_test.go @@ -0,0 +1,545 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +func nativeDeliveryRequest(t *testing.T, tools string, choice string, parallel *bool) toolcall.Request { + t.Helper() + var choiceRaw json.RawMessage + if choice != "" { + choiceRaw = json.RawMessage(choice) + } + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, json.RawMessage(tools), choiceRaw, parallel, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + +func nativeDeliveryStream(frames ...string) string { + return strings.Join(frames, "\n") +} + +func assertNativeDeliveryFailure(t *testing.T, upstream string, request toolcall.Request, forbidden ...string) { + t.Helper() + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil { + t.Fatal("native tool delivery should have been rejected") + } + if stats.DownstreamTerminal != "error" || stats.FinishReason != "error" { + t.Fatalf("stats = %+v", stats) + } + got := out.String() + if strings.Contains(got, "response.completed") { + t.Fatalf("rejected turn wrote response.completed: %s", got) + } + for _, value := range forbidden { + if strings.Contains(got, value) { + t.Fatalf("rejected turn leaked %q: %s", value, got) + } + } + if strings.Count(got, "event: error") != 1 { + t.Fatalf("expected exactly one structured error, got %d: %s", strings.Count(got, "event: error"), got) + } +} + +func TestNativeDeliveryRejectsVisibleCallOmittedByTerminal(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"describe","parameters":{"type":"object"}},{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, + `{"type":"function","name":"lookup"}`, nil) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_describe","type":"function_call","call_id":"call_describe","name":"describe","arguments":"{}"}}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_lookup","type":"function_call","call_id":"call_lookup","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_lookup","type":"function_call","call_id":"call_lookup","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item.done", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsParallelCallsBeyondTerminal(t *testing.T) { + parallel := false + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, + "", ¶llel) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item.done", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsEarlierInvalidCompleteFrameRepairedByTerminal(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, + "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\""}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item.done", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsToolInsideControlFrame(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":"}]}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.created", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsSSEEventTypeConflict(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsMalformedArgumentFrame(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{\"q\":\"ok\"}"}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{\"q":`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "function_call", `"q"`, "response.completed") +} + +func TestNativeDeliveryRejectsToolEmbeddedInNestedControlOutput(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"msg_1","type":"message"},"response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item.added", "function_call", "response.completed") +} + +func TestNativeDeliveryAcceptsCustomCompletionWithNonEmptyInput(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"custom","name":"exec"}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + ``, + `event: response.custom_tool_call_input.done`, + `data: {"type":"response.custom_tool_call_input.done","item_id":"ct_1","input":"pwd"}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":"pwd"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "response.custom_tool_call_input.done") || !strings.Contains(out.String(), `"input":"pwd"`) { + t.Fatalf("legal non-empty custom completion was not delivered: %s", out.String()) + } +} + +func TestNativeDeliveryAcceptsDataOnlySSE(t *testing.T) { + upstream := strings.Join([]string{ + `data: {"type":"response.output_text.delta","delta":"hello"}`, + ``, + `data: {"type":"response.completed","response":{"status":"completed","output":[]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil) + if err != nil { + t.Fatal(err) + } + if stats.FinishReason != "stop" || stats.DownstreamTerminal != "done" { + t.Fatalf("data-only terminal stats = %+v", stats) + } + if !strings.Contains(out.String(), "hello") || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("data-only SSE was not delivered: %s", out.String()) + } +} + +func TestNativeDeliveryRejectsCompletedEventWithTruncatedBody(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.output_item.done", "function_call", "response.completed") +} + +// clientSSEFrame is an independent parser used by tests. It only accepts a +// frame when a blank line terminates it, so a missing trailing blank line is +// not silently treated as a complete client event. +type clientSSEFrame struct { + Event string + Data string +} + +func parseClientSSE(raw string) []clientSSEFrame { + var frames []clientSSEFrame + var lines []string + flush := func() { + if len(lines) == 0 { + return + } + var frame clientSSEFrame + var data []string + for _, line := range lines { + line = strings.TrimSuffix(line, "\r") + switch { + case strings.HasPrefix(line, "event:"): + frame.Event = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + case strings.HasPrefix(line, "data:"): + data = append(data, strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ")) + } + } + frame.Data = strings.Join(data, "\n") + if frame.Event != "" || frame.Data != "" { + frames = append(frames, frame) + } + lines = nil + } + for _, line := range strings.Split(raw, "\n") { + if strings.TrimSpace(line) == "" { + flush() + continue + } + lines = append(lines, line) + } + return frames +} + +func TestNativeFailureWritesOneCompleteSSEEvent(t *testing.T) { + for _, tc := range []struct { + name string + body string + }{ + {"failed_with_tool_output", "event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"id\":\"r1\",\"status\":\"failed\",\"output\":[{\"type\":\"function_call\",\"call_id\":\"c1\",\"name\":\"secret_tool\",\"arguments\":\"{}\"}],\"error\":{\"message\":\"secret upstream\"}}}\n\n"}, + {"error", "event: error\ndata: {\"type\":\"error\",\"error\":{\"message\":\"secret upstream\"}}\n\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(tc.body), nil) + if err == nil { + t.Fatal("upstream failure must return an error") + } + if stats.DownstreamTerminal != "error" || stats.FinishReason != "error" { + t.Fatalf("stats = %+v", stats) + } + frames := parseClientSSE(out.String()) + if len(frames) != 1 { + t.Fatalf("client received %d complete frames, want 1: %q", len(frames), out.String()) + } + if frames[0].Event != "error" { + t.Fatalf("event = %q, want a minimal error terminal", frames[0].Event) + } + var payload map[string]any + if err := json.Unmarshal([]byte(frames[0].Data), &payload); err != nil { + t.Fatalf("client error payload is not JSON: %v (%q)", err, frames[0].Data) + } + for _, forbidden := range []string{"secret upstream", "function_call", "secret_tool", "call_id", "response"} { + if strings.Contains(frames[0].Data, forbidden) { + t.Fatalf("failure terminal leaked %q: %s", forbidden, frames[0].Data) + } + } + }) + } +} + +type shortFirstWrite struct { + buf bytes.Buffer + once bool +} + +func (w *shortFirstWrite) Write(p []byte) (int, error) { + if !w.once && len(p) > 1 { + w.once = true + n := len(p) - 1 + _, _ = w.buf.Write(p[:n]) + return n, nil + } + return w.buf.Write(p) +} + +func TestNativeShortWriteStopsWithoutDone(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + var out shortFirstWrite + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil || !errors.Is(err, io.ErrShortWrite) { + t.Fatalf("short write must abort the relay, got %v", err) + } + if stats.DownstreamTerminal == "done" || stats.SawDone { + t.Fatalf("short write was recorded as success: %+v", stats) + } + if strings.Contains(out.buf.String(), "response.completed") { + t.Fatalf("relay continued after a short write: %s", out.buf.String()) + } +} + +func TestNativeDeliveryAllowsNonClientToolWhitelist(t *testing.T) { + upstream := nativeDeliveryStream( + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"mcp_1","type":"mcp_call","name":"outside","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"mcp_1","type":"mcp_call","name":"outside","arguments":"{}"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "mcp_call") || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("non-client whitelist item was dropped: %s", out.String()) + } +} + +func TestNativeDeliveryUsesInjectedLimits(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`, + ``, + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_2","type":"function_call","call_id":"call_2","name":"lookup","arguments":""}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + limits := toolcall.DefaultNativeLimits() + limits.MaxCalls = 1 + var out bytes.Buffer + stats, err := relayNativeResponsesStream(&out, strings.NewReader(upstream), nil, limits, request) + if err == nil { + t.Fatal("injected MaxCalls must reach NativeTurn") + } + if stats.DownstreamTerminal != "error" { + t.Fatalf("stats = %+v", stats) + } + if strings.Contains(out.String(), "function_call") { + t.Fatalf("over-limit call leaked: %s", out.String()) + } +} + +func TestNativeDeliveryRejectsControlEnvelopeToolOmittedByTerminal(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "response.created", "function_call", "response.completed") +} + +func TestNativeDeliveryAcceptsControlEnvelopeCompletedByTerminal(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.created`, + `data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}]}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "response.created") || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("legal control envelope was not delivered: %s", out.String()) + } +} + +func TestNativeDeliveryAcceptsTerminalOnlyCall(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), `"function_call"`) || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("terminal-only call was not delivered: %s", out.String()) + } +} + +func TestNativeDeliveryAcceptsAddedCallCompletedByTerminal(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, + "", nil) + upstream := nativeDeliveryStream( + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":""}}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{\"q\":\"ok\"}"}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"ok\"}"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + got := out.String() + if !strings.Contains(got, "response.output_item.added") || !strings.Contains(got, "function_call_arguments.delta") { + t.Fatalf("valid added call was not delivered: %s", got) + } + if !strings.Contains(got, "response.completed") { + t.Fatalf("valid terminal was not delivered: %s", got) + } +} + +func TestNativeDeliveryRejectsDoneThatRewritesDelta(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","call_id":"call_1","delta":"{\"q\":\"old\"}"}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","item_id":"fc_1","call_id":"call_1","arguments":"{\"q\":\"new\"}"}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"new\"}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "old", "new", "function_call", "response.completed") +} + +func TestNativeDeliveryRejectsOversizedAddedArguments(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + limits := toolcall.DefaultNativeLimits() + limits.MaxArgumentBytes = 3 + upstream := nativeDeliveryStream( + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{\"q\":\"large\"}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + var out bytes.Buffer + stats, err := relayNativeResponsesStream(&out, strings.NewReader(upstream), nil, limits, request) + if err == nil || stats.DownstreamTerminal != "error" || strings.Contains(out.String(), "large") { + t.Fatalf("oversized item arguments were delivered: err=%v stats=%+v", err, stats) + } +} + +func TestNativeDeliveryRejectsCompletedEventWithIncompleteBody(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + assertNativeDeliveryFailure(t, upstream, request, "function_call", "response.completed") +} + +func TestNativeDeliveryAcceptsLateCallIDBinding(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := nativeDeliveryStream( + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","call_id":"call_1","name":"lookup","delta":"{}"}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}]}}`, + ``, + ) + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatalf("legal late call_id binding was rejected: %v\n%s", err, out.String()) + } +} + +func TestNativeDeliveryRejectsBufferedToolFramesAtEOF(t *testing.T) { + request := nativeDeliveryRequest(t, + `[{"type":"function","name":"lookup","parameters":{"type":"object"}}]`, "", nil) + upstream := "event: response.output_item.done\n" + + "data: {\"type\":\"response.output_item.done\",\"item\":{\"id\":\"fc_1\",\"type\":\"function_call\",\"call_id\":\"call_1\",\"name\":\"lookup\",\"arguments\":\"{}\"}}" + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil || stats.DownstreamTerminal == "done" || strings.Contains(out.String(), "function_call") { + t.Fatalf("buffered tool frames were released at EOF: err=%v stats=%+v out=%s", err, stats, out.String()) + } +} diff --git a/internal/gateway/native_responses.go b/internal/gateway/native_responses.go index af12ff547..8fb21912e 100644 --- a/internal/gateway/native_responses.go +++ b/internal/gateway/native_responses.go @@ -3,50 +3,235 @@ package gateway import ( "bufio" "encoding/json" + "errors" + "fmt" "io" + "net/http" "strings" "time" + "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) // RelayNativeResponsesStream relays an upstream OpenAI Responses SSE body // while observing the frames needed for accounting: first-token timing, -// terminal status, and token usage. It writes no events of its own — the -// upstream already emits a well-formed stream including response.created / -// response.completed. +// terminal status, and token usage. It writes no events of its own except one: +// when a buffered tool frame or the terminal response violates the request +// contract, the success terminal is replaced with a structured error. // // Frames are relayed verbatim except for one rewrite: when names is non-empty, // flattened namespace tool names (the form providers receive) are restored to // the caller's namespace + name on function_call items, exactly as the // compatibility relay does. Frames that carry no such tool call stay // byte-for-byte. -func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[string]translate.ResponseToolName) (StreamRelayStats, error) { +type nativeDeliveryPlan struct { + calls []toolcall.NativeCall + frames []string +} + +// nativeToolValidationError keeps a native contract violation out of the +// account-health path. The stream has already been accepted, so it is a failed +// turn, not an unavailable account; the executor must record it as a client / +// upstream tool-contract error. The error is still terminal for the relay. +func nativeToolValidationError(err error) error { + if err == nil { + return nil + } + var execution *executor.ExecutionError + if errors.As(err, &execution) { + return err + } + return executor.NewExecutionError(executor.Classified{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadGateway, + Code: "invalid_upstream_tool_call", + Type: "api_error", + Message: "native tool delivery failed validation", + }, err) +} + +func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[string]translate.ResponseToolName, requests ...toolcall.Request) (StreamRelayStats, error) { + return relayNativeResponsesStream(writer, body, names, toolcall.DefaultNativeLimits(), requests...) +} + +func relayNativeResponsesStream(writer io.Writer, body io.Reader, names map[string]translate.ResponseToolName, limits toolcall.NativeLimits, requests ...toolcall.Request) (StreamRelayStats, error) { + body, stopFirstFrame := guardFirstFrame(body) + defer stopFirstFrame() var stats StreamRelayStats + var canonical toolcall.Request + if len(requests) > 0 { + canonical = requests[0] + } scanner := bufio.NewScanner(body) scanner.Buffer(make([]byte, 0, 64*1024), maxSSELineSize) var frame []string - var sawTerminal bool + // Native Responses normally relays frames as they arrive. A tool item is + // different: its argument events carry the client-visible tool payload, and + // earlier completed frames must remain valid even when the terminal snapshot + // repairs them. Buffer from the first tool event through the terminal so a + // rejected turn never delivers tool arguments it cannot retract. Text + // frames after the tool starts are held with it to preserve stream order. + var pending []string + pendingBytes := 0 + pendingClientTool := false + buffering := false + validator := toolcall.NewNativeTurn(canonical, limits) + + writeChunk := func(output string) error { + n, err := writer.Write([]byte(output)) + if err != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return &StreamRelayWriteError{err: err} + } + if n < len(output) { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return &StreamRelayWriteError{err: io.ErrShortWrite} + } + return nil + } + // nativeDeliveryPlan is constructed only after NativeTurn.Finish accepted + // the whole round. The relay writes tool-bearing frames through this plan, + // never through the staging slice directly. + writeDelivery := func(delivery *toolcall.NativeDelivery, frames []string) error { + plan := &nativeDeliveryPlan{calls: delivery.Calls, frames: frames} + pending = nil + pendingBytes = 0 + pendingClientTool = false + buffering = false + for _, output := range plan.frames { + if err := writeChunk(output); err != nil { + return err + } + } + return nil + } + failPending := func(err error) error { + pending = nil + pendingBytes = 0 + pendingClientTool = false + buffering = false + stats.UpstreamTerminal = "error" + stats.FinishReason = "error" + stats.DownstreamTerminal, stats.FlushState = "error", "ok" + err = nativeToolValidationError(err) + if writeErr := writeResponsesStreamError(writer, err); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return writeErr + } + return err + } flush := func() error { if len(frame) == 0 { return nil } eventName, data := parseSSEFrame(frame) - if _, err := io.WriteString(writer, restoreNativeFrameToolNames(frame, data, names)); err != nil { - frame = nil - return &StreamRelayWriteError{err: err} + classifiedErr := classifyStreamSSEError(eventName, data) + event, eventOK := translate.ParseResponsesEvent(data) + if !eventOK { + trimmed := strings.TrimSpace(data) + if trimmed != "" && trimmed != "[DONE]" { + frame = nil + return failPending(fmt.Errorf("native Responses stream carried an invalid event frame")) + } } - frame = nil - if classified := classifyStreamSSEError(eventName, data); classified != nil { - return classified + if eventOK { + observeName := eventName + if observeName == "message" { + // parseSSEFrame supplies "message" when the frame had no event: + // field. Native Responses payloads carry their own type, and a + // data-only terminal must not be rejected as an event-name + // conflict. + observeName = "" + } + if validateErr := validator.Observe(observeName, []byte(data)); validateErr != nil { + frame = nil + return failPending(validateErr) + } } - payload := strings.TrimSpace(data) - if payload == "" || payload == "[DONE]" { - return nil + terminalSuccess := eventOK && event.Terminal && event.FinishReason != "error" + var delivery *toolcall.NativeDelivery + if terminalSuccess { + var validateErr error + delivery, validateErr = validator.Finish(event.Response, event.FinishReason) + if validateErr != nil { + frame = nil + return failPending(validateErr) + } + if pendingClientTool && (delivery == nil || len(delivery.Calls) == 0) { + frame = nil + return failPending(fmt.Errorf("native tool suffix has no validated client call")) + } } - event, ok := translate.ParseResponsesEvent(payload) - if !ok { + output := restoreNativeFrameToolNames(frame, data, names) + failure := classifiedErr + if failure == nil && eventOK && event.Terminal && event.FinishReason == "error" { + failure = executor.ClassifyUpstreamBody(0, data) + } + if failure != nil { + // Native Responses frames are otherwise relayed verbatim, but an + // upstream failure frame is an error exit: its message must never + // carry an upstream body or credential to the client. + output = sanitizeNativeFailureFrame(executor.ClassifyError(failure)) + } + if failure != nil { + pending = nil + pendingBytes = 0 + pendingClientTool = false + buffering = false + frame = nil + if err := writeChunk(output); err != nil { + return err + } + // This error frame is already on the wire. Mark it terminal so the + // handler does not synthesize another failure frame. + stats.FinishReason = "error" + stats.UpstreamTerminal = "error" + stats.DownstreamTerminal, stats.FlushState = "error", "ok" + return failure + } + if eventOK && event.Terminal && event.FinishReason == "error" { + // A failed terminal is an exit frame, not a successful turn. Drop + // buffered tool events before relaying the failure. + pending = nil + pendingBytes = 0 + pendingClientTool = false + buffering = false + frame = nil + if err := writeChunk(output); err != nil { + return err + } + stats.DownstreamTerminal, stats.FlushState = "error", "ok" + } else if terminalSuccess { + if err := writeDelivery(delivery, pending); err != nil { + frame = nil + return err + } + frame = nil + if err := writeChunk(output); err != nil { + return err + } + } else if buffering || (eventOK && nativeToolEvent(event, data)) { + if len(pending)+1 > limits.MaxFrames || pendingBytes+len(output) > limits.MaxBufferedBytes { + frame = nil + return failPending(fmt.Errorf("native tool suffix exceeded its buffer limit")) + } + buffering = true + pending = append(pending, output) + pendingBytes += len(output) + if eventOK && nativeClientToolEvent(event, data) { + pendingClientTool = true + } + frame = nil + } else { + frame = nil + if err := writeChunk(output); err != nil { + return err + } + } + if !eventOK { return nil } if stats.FirstTokenAt == nil && event.FirstToken { @@ -56,7 +241,6 @@ func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[stri if !event.Terminal { return nil } - sawTerminal = true stats.FinishReason = event.FinishReason stats.PromptTokens = event.InputTokens stats.CompletionTokens = event.OutputTokens @@ -66,14 +250,21 @@ func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[stri stats.ReasoningTokens = event.ReasoningTokens stats.UsageSource = "upstream" if event.FinishReason == "error" { - return executor.ClassifyUpstreamBody(0, payload) + stats.UpstreamTerminal = "error" + return executor.ClassifyUpstreamBody(0, data) } + stats.SawDone = true + stats.UpstreamTerminal = "done" + stats.DownstreamDone = true + stats.DownstreamTerminal, stats.FlushState = "done", "ok" return nil } for scanner.Scan() { line := strings.TrimSuffix(scanner.Text(), "\r") if line == "" { - if err := flush(); err != nil { + // The first successfully relayed terminal event settles the + // request; an error reading beyond it cannot change that result. + if err := flush(); err != nil || stats.SawDone { return stats, err } continue @@ -81,16 +272,76 @@ func RelayNativeResponsesStream(writer io.Writer, body io.Reader, names map[stri frame = append(frame, line) } if err := scanner.Err(); err != nil { + stats.UpstreamTerminal = "eof" return stats, executor.StreamReadError(err) } - if err := flush(); err != nil { + // A trailing frame without its terminating blank line is only rejected when + // it is not a complete terminal event. Tool suffixes that never received a + // terminal must not be flushed as success; a trailing terminal frame is + // still handed to flush(), which validates the buffered tools before any + // bytes are written. + if len(frame) > 0 { + _, data := parseSSEFrame(frame) + event, ok := translate.ParseResponsesEvent(data) + if !ok || !event.Terminal { + pending = nil + pendingBytes = 0 + pendingClientTool = false + buffering = false + frame = nil + stats.UpstreamTerminal = "eof" + return stats, executor.StreamIncompleteError() + } + } + if err := flush(); err != nil || stats.SawDone { return stats, err } - if !sawTerminal { - return stats, executor.StreamIncompleteError() + stats.UpstreamTerminal = "eof" + return stats, executor.StreamIncompleteError() +} + +// sanitizeNativeFailureFrame replaces an upstream failure message before the +// frame reaches the client. Native Responses is otherwise a verbatim relay, so +// this is the one place where an upstream error body must be rewritten rather +// than passed through. The event shape is preserved where possible; malformed +// or unexpected payloads fall back to a protocol-shaped error event. +func sanitizeNativeFailureFrame(classified executor.Classified) string { + message := executor.PublicErrorMessage(classified) + code := publicNativeErrorCode(classified.Code) + errorType := strings.TrimSpace(classified.Type) + if errorType == "" { + errorType = "api_error" + } + // A failed terminal must never carry the upstream response object: it can + // contain unvalidated function_call items, tool arguments, or credentials. + // Rebuild a minimal failure envelope instead of editing the original in + // place, so response.output and any unknown fields are dropped wholesale. + encoded, _ := json.Marshal(map[string]any{ + "type": "error", + "error": map[string]any{ + "type": errorType, + "code": code, + "message": message, + }, + }) + return "event: error" + "\n" + "data: " + string(encoded) + "\n\n" +} + +func publicNativeErrorCode(code string) string { + code = strings.TrimSpace(code) + if code == "" { + return "upstream_error" + } + for _, r := range code { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == '.' { + continue + } + return "upstream_error" + } + if len(code) > 64 { + return "upstream_error" } - stats.SawDone = true - return stats, nil + return code } // restoreNativeFrameToolNames returns the frame to write. Without a mapping, or @@ -134,3 +385,73 @@ func frameMentionsToolName(data string, names map[string]translate.ResponseToolN } return false } + +// nativeToolEvent reports whether an upstream Responses event carries a tool +// item or tool arguments. These frames must not reach the client until the +// terminal response has passed canonical validation. +func nativeClientToolEvent(event translate.ResponsesEvent, data string) bool { + switch event.Type { + case "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done": + return true + } + var envelope struct { + Item struct { + Type string `json:"type"` + } `json:"item"` + Response struct { + Output []struct { + Type string `json:"type"` + } `json:"output"` + } `json:"response"` + } + if json.Unmarshal([]byte(strings.TrimSpace(data)), &envelope) != nil { + return false + } + if envelope.Item.Type == "function_call" || envelope.Item.Type == "custom_tool_call" { + return true + } + for _, item := range envelope.Response.Output { + if item.Type == "function_call" || item.Type == "custom_tool_call" { + return true + } + } + return false +} + +func nativeToolEvent(event translate.ResponsesEvent, data string) bool { + switch event.Type { + case "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done": + return true + } + if strings.Contains(event.Type, "mcp_call") { + return true + } + var envelope struct { + Item struct { + Type string `json:"type"` + } `json:"item"` + Response struct { + Output []struct { + Type string `json:"type"` + } `json:"output"` + } `json:"response"` + } + if json.Unmarshal([]byte(strings.TrimSpace(data)), &envelope) != nil { + return false + } + if strings.HasSuffix(envelope.Item.Type, "_call") { + return true + } + for _, item := range envelope.Response.Output { + if strings.HasSuffix(item.Type, "_call") || item.Type == "function_call" || item.Type == "custom_tool_call" { + return true + } + } + return false +} diff --git a/internal/gateway/native_responses_test.go b/internal/gateway/native_responses_test.go index dba86a183..fbb87dad2 100644 --- a/internal/gateway/native_responses_test.go +++ b/internal/gateway/native_responses_test.go @@ -2,12 +2,253 @@ package gateway import ( "bytes" + "encoding/json" "strings" "testing" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) +func TestRelayNativeResponsesStreamReplacesInvalidToolTerminal(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil { + t.Fatal("invalid native tool terminal must fail") + } + if stats.FinishReason != "error" || stats.DownstreamTerminal != "error" { + t.Fatalf("stats = %+v", stats) + } + got := out.String() + if strings.Contains(got, "response.completed") { + t.Fatalf("success terminal was written for invalid tool output: %s", got) + } + if strings.Contains(got, "response.output_item.done") || strings.Contains(got, "function_call_arguments") { + t.Fatalf("tool events leaked before terminal validation: %s", got) + } + if !strings.Contains(got, "event: error") { + t.Fatalf("structured terminal error missing: %s", got) + } +} + +func TestRelayNativeResponsesStreamBuffersToolEventsUntilValidTerminal(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"read_file","arguments":""}}`, + ``, + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"{\"path\":\"README.md\"}"}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","call_id":"call_1","arguments":"{\"path\":\"README.md\"}"}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err != nil { + t.Fatal(err) + } + if stats.FinishReason != "stop" { + t.Fatalf("stats = %+v", stats) + } + got := out.String() + added := strings.Index(got, "response.output_item.added") + delta := strings.Index(got, "response.function_call_arguments.delta") + done := strings.Index(got, "response.function_call_arguments.done") + terminal := strings.Index(got, "response.completed") + if added < 0 || delta < 0 || done < 0 || terminal < 0 || !(added < delta && delta < done && done < terminal) { + t.Fatalf("tool event order lost: %s", got) + } +} + +func TestRelayNativeResponsesStreamDropsToolEventsOnIncompleteTurn(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.function_call_arguments.delta`, + `data: {"type":"response.function_call_arguments.delta","call_id":"call_1","delta":"{\"path\":"}`, + ``, + `event: response.incomplete`, + `data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil { + t.Fatal("incomplete tool turn must fail") + } + if stats.DownstreamTerminal != "error" { + t.Fatalf("stats = %+v", stats) + } + if strings.Contains(out.String(), "function_call_arguments") { + t.Fatalf("truncated tool event leaked: %s", out.String()) + } +} + +func TestRelayNativeResponsesStreamRejectsInvalidEarlierFrameWithValidTerminal(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil { + t.Fatal("an invalid buffered frame with a valid terminal must fail") + } + if stats.DownstreamTerminal != "error" { + t.Fatalf("stats = %+v", stats) + } + if strings.Contains(out.String(), "response.output_item.done") || strings.Contains(out.String(), "response.completed") { + t.Fatalf("frame leaked despite invalid earlier tool frame: %s", out.String()) + } + if !strings.Contains(out.String(), "event: error") { + t.Fatalf("structured terminal error missing: %s", out.String()) + } +} + +func TestRelayNativeResponsesStreamRejectsCompleteArgumentsFromIncompleteTurn(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}}`, + ``, + `event: response.incomplete`, + `data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + stats, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request) + if err == nil { + t.Fatal("incomplete turn with a complete-looking tool call must fail") + } + if stats.DownstreamTerminal != "error" { + t.Fatalf("stats = %+v", stats) + } + if strings.Contains(out.String(), "response.output_item.done") || strings.Contains(out.String(), "response.incomplete") { + t.Fatalf("buffered tool frame leaked from incomplete turn: %s", out.String()) + } + if !strings.Contains(out.String(), "event: error") { + t.Fatalf("structured terminal error missing: %s", out.String()) + } +} + +func TestRelayNativeResponsesStreamRejectsInvalidArgumentsDoneRepairedByLaterFrame(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":""}}`, + ``, + `event: response.function_call_arguments.done`, + `data: {"type":"response.function_call_arguments.done","item_id":"fc_1","call_id":"call_1","arguments":"{}"}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err == nil { + t.Fatal("later frame repaired an invalid completed arguments frame") + } + if strings.Contains(out.String(), "response.function_call_arguments.done") || strings.Contains(out.String(), "response.output_item.done") { + t.Fatalf("invalid completed frame leaked: %s", out.String()) + } +} + +func TestRelayNativeResponsesStreamAllowsAddedFrameCompletedByTerminal(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":""}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "response.output_item.added") || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("valid added+terminal call was dropped: %s", out.String()) + } +} + +func TestRelayNativeResponsesStreamAcceptsCustomToolCall(t *testing.T) { + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, json.RawMessage(`[{"type":"custom","name":"exec"}]`), json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + upstream := strings.Join([]string{ + `event: response.output_item.added`, + `data: {"type":"response.output_item.added","item":{"id":"ct_1","type":"custom_tool_call","call_id":"call_1","name":"exec","input":""}}`, + ``, + `event: response.custom_tool_call_input.delta`, + `data: {"type":"response.custom_tool_call_input.delta","item_id":"ct_1","delta":"pwd"}`, + ``, + `event: response.custom_tool_call_input.done`, + `data: {"type":"response.custom_tool_call_input.done","item_id":"ct_1","input":"pwd"}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"custom_tool_call","id":"ct_1","call_id":"call_1","name":"exec","input":"pwd"}]}}`, + ``, + }, "\n") + var out bytes.Buffer + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), nil, request); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "response.custom_tool_call_input.done") || !strings.Contains(out.String(), "response.completed") { + t.Fatalf("valid custom tool call was dropped: %s", out.String()) + } +} + func TestRelayNativeResponsesStreamPassthrough(t *testing.T) { upstream := strings.Join([]string{ `event: response.created`, @@ -55,7 +296,7 @@ func TestRelayNativeResponsesStreamIncomplete(t *testing.T) { func TestRelayNativeResponsesStreamFailedIsTerminalError(t *testing.T) { upstream := strings.Join([]string{ `event: response.failed`, - `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"slow down"}}}`, + `data: {"type":"response.failed","response":{"status":"failed","error":{"code":"rate_limit_exceeded","message":"slow down SENSITIVE_MARKER Authorization: Bearer abcdefghijklmnop"}}}`, ``, }, "\n") var out bytes.Buffer @@ -66,8 +307,15 @@ func TestRelayNativeResponsesStreamFailedIsTerminalError(t *testing.T) { if stats.FinishReason != "error" { t.Fatalf("finish %q", stats.FinishReason) } - if !strings.Contains(out.String(), "response.failed") { - t.Fatalf("failure event was not relayed: %s", out.String()) + got := out.String() + if !strings.Contains(got, "event: error") { + t.Fatalf("minimal error terminal was not relayed: %s", got) + } + if strings.Contains(got, "SENSITIVE_MARKER") || strings.Contains(got, "Bearer") || strings.Contains(got, "response.failed") || strings.Contains(got, "\"response\"") { + t.Fatalf("native failure frame leaked upstream body: %s", got) + } + if !strings.Contains(got, "upstream ") { + t.Fatalf("native failure frame lost its public message: %s", got) } } @@ -86,6 +334,15 @@ func TestRelayNativeResponsesStreamIncompleteStatus(t *testing.T) { } } +func nativeGlobToolRequest(t *testing.T) toolcall.Request { + t.Helper() + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, json.RawMessage(`[{"type":"function","name":"mcp__fastctx__glob","parameters":{"type":"object"}}]`), nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + func TestRelayNativeResponsesStreamRestoresNamespacedToolNames(t *testing.T) { upstream := strings.Join([]string{ `event: response.output_item.added`, @@ -95,12 +352,12 @@ func TestRelayNativeResponsesStreamRestoresNamespacedToolNames(t *testing.T) { `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","name":"mcp__fastctx__glob","call_id":"call_1","arguments":"{\"pattern\":\"mcp__fastctx__glob\"}"}}`, ``, `event: response.completed`, - `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","name":"mcp__fastctx__glob","call_id":"call_1","arguments":"{}"}]}}`, + `data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"fc_1","type":"function_call","name":"mcp__fastctx__glob","call_id":"call_1","arguments":"{\"pattern\":\"mcp__fastctx__glob\"}"}]}}`, ``, }, "\n") names := map[string]translate.ResponseToolName{"mcp__fastctx__glob": {Namespace: "mcp__fastctx", Name: "glob"}} var out bytes.Buffer - if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), names); err != nil { + if _, err := RelayNativeResponsesStream(&out, strings.NewReader(upstream), names, nativeGlobToolRequest(t)); err != nil { t.Fatal(err) } got := out.String() @@ -120,9 +377,9 @@ func TestRelayNativeResponsesStreamRestoresNamespacedToolNames(t *testing.T) { } func TestRelayNativeResponsesStreamWithoutNamesIsVerbatim(t *testing.T) { - frame := `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","name":"mcp__fastctx__glob"}]}}` + frame := `data: {"type":"response.completed","response":{"status":"completed","output":[{"type":"function_call","name":"mcp__fastctx__glob","call_id":"call_1","arguments":"{}"}]}}` var out bytes.Buffer - if _, err := RelayNativeResponsesStream(&out, strings.NewReader("event: response.completed\n"+frame+"\n\n"), nil); err != nil { + if _, err := RelayNativeResponsesStream(&out, strings.NewReader("event: response.completed\n"+frame+"\n\n"), nil, nativeGlobToolRequest(t)); err != nil { t.Fatal(err) } if out.String() != "event: response.completed\n"+frame+"\n\n" { diff --git a/internal/gateway/openai.go b/internal/gateway/openai.go index dc95bc777..70a71ad90 100644 --- a/internal/gateway/openai.go +++ b/internal/gateway/openai.go @@ -12,6 +12,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -30,19 +31,23 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) body := decodeRequestBody(w, r, maxChatRequestBytes, maxChatRequestBytes) defer body.Close() if body.err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request", body.err.Error()) writeRequestBodyError(w, body.err) return } rawBody, readErr := readConversationBody(body, maxChatRequestBytes) if readErr != nil { if isRequestBodyTooLarge(readErr) { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "request_too_large", readErr.Error()) writeRequestBodyError(w, readErr) return } + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request", readErr.Error()) writeErr(w, http.StatusBadRequest, "invalid_request", readErr.Error()) return } if err := json.Unmarshal(rawBody, &req); err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request", err.Error()) writeErr(w, http.StatusBadRequest, "invalid_request", err.Error()) return } @@ -50,27 +55,25 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) r = r.WithContext(WithConversationID(r.Context(), id)) } if len(req.Messages) == 0 { + h.recordEntryRejection(r, req.Model, accounts.KindInvalidRequest, "invalid_request", "messages required") writeErr(w, http.StatusBadRequest, "invalid_request", "messages required") return } if err := translate.ValidateChatRequest(&req); err != nil { + h.recordEntryRejection(r, req.Model, accounts.KindInvalidRequest, "invalid_request", err.Error()) writeErr(w, http.StatusBadRequest, "invalid_request", err.Error()) return } - execution, err := h.PrepareChatExecution(r, req) + reserveKey, releaseKey := h.keySlotHooks(r) + defer releaseKey() + execution, err := h.prepareExecution(r, req, nil, reserveKey) if err != nil { + h.recordPrepareRejection(r, req.Model, err) writeChatHTTPError(w, err) return } - releaseKey, ok := h.reserveKeySlot(r) - if !ok { - writeKeyConcurrencyLimited(w) - return - } - defer releaseKey() req = execution.Request publicModel := execution.PublicModel - prefer := execution.Prefer providerFilter := execution.ProviderFilter requestID := execution.RequestID started := execution.Started @@ -88,20 +91,14 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) } } - // The heartbeat may commit SSE headers while ChatStreamProxy is still - // waiting for the upstream head. Account/provider are known as soon as - // the executor picks a route, so the timer reads them from this hint - // and includes them in the first flush. - routeHint := &executor.StreamRouteHint{} - ctx = executor.WithStreamRouteHint(ctx, routeHint) - + // The heartbeat can commit before an upstream stream is accepted. + // The selected account and provider can still change on failover, so + // only the handler may add identity headers from the accepted result. setStreamHeaders := func() { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.Header().Set("X-Accel-Buffering", "no") - accountID, provider := routeHint.Get() - applyStreamIdentityHeaders(accountID, firstNonEmpty(provider, providerFilter)) } // Start heartbeating before blocking on the upstream head. Silence @@ -111,7 +108,8 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) heartbeat := newStreamHeartbeat(w) heartbeat.Arm(setStreamHeaders) - upstream, err := h.Executor.ChatStreamProxy(ctx, req, prefer, providerFilter) + upstream, err := h.Executor.ChatStreamProxyPrepared(ctx, req, nil, execution.Route) + defer h.refreshQuotaAfterUse(upstream.PoolAccountID, upstream.CooldownModel, upstream.AggregateFEFO) if err != nil { if heartbeat.Abandon() { // The headers are already on the wire, so the only channel left @@ -123,12 +121,18 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) err = context.Canceled } h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, status, upstream.TTFBMs, nil, err, upstream.AttemptCount, upstream.ReasoningLevel) + if requestID != "" && h.Recorder != nil { + h.Recorder.Finalize(requestID) + } if status != accounts.RequestStatusCanceled { writeStructuredStreamError(w, err) } return } h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, accounts.RequestStatusError, upstream.TTFBMs, nil, err, upstream.AttemptCount, upstream.ReasoningLevel) + if requestID != "" && h.Recorder != nil { + h.Recorder.Finalize(requestID) + } WriteClassifiedErr(w, err) return } @@ -137,10 +141,13 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) if heartbeat.clientGone() != nil || r.Context().Err() != nil { // The client left during the heartbeat wait. Do not record this // as a normal stream open; the headers may already be on the - // wire, but no upstream tokens were relayed. CommitSession stays - // uncalled: it binds only a stream that finished without a client - // error, and this one ended because the client left. + // wire, but no upstream tokens were relayed. There is no stream + // outcome to apply to account health; only cancel the attempt. + h.Executor.FinishStream(ctx, upstream, context.Canceled) h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, accounts.RequestStatusCanceled, upstream.TTFBMs, nil, context.Canceled, upstream.AttemptCount, upstream.ReasoningLevel) + if requestID != "" && h.Recorder != nil { + h.Recorder.Finalize(requestID) + } return } h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, accounts.RequestStatusStreaming, upstream.TTFBMs, nil, nil, upstream.AttemptCount, upstream.ReasoningLevel) @@ -148,12 +155,20 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) setStreamHeaders() applyStreamIdentityHeaders(upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter)) w.WriteHeader(http.StatusOK) - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() + if flushErr := flushResponse(w); flushErr != nil { + // Headers were committed but even the empty stream preamble could + // not be flushed: the client is gone, not the upstream. + h.Executor.FinishStream(ctx, upstream, executor.ClientDisconnectError(flushErr)) + h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, accounts.RequestStatusCanceled, upstream.TTFBMs, &StreamRelayStats{DownstreamTerminal: "error", FlushState: "error"}, flushErr, upstream.AttemptCount, upstream.ReasoningLevel) + if requestID != "" && h.Recorder != nil { + h.Recorder.Finalize(requestID) + } + return } } - stats, relayErr := RelayOpenAIStream(w, upstream.Response.Body) - status := streamLogStatus(relayErr, stats.SawDone, r.Context().Err() != nil) + stats, relayErr := RelayOpenAIStream(w, upstream.Response.Body, execution.Route.Tooling) + stats.RequestState = upstream.RequestState + status := streamLogStatus(relayErr, stats, r.Context().Err() != nil) h.recordStreamDiagnostic(requestID, upstream.Response, started, stats, relayErr, r.Context().Err()) ttfb := upstream.TTFBMs if stats.FirstTokenAt != nil { @@ -170,26 +185,15 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) logErr = nil } h.finishRequestLog(requestID, started, req, publicModel, upstream.AccountID, firstNonEmpty(upstream.Provider, providerFilter), upstream.Routing, status, ttfb, &stats, logErr, upstream.AttemptCount, upstream.ReasoningLevel) - if relayErr == nil { - h.Executor.CommitSession(ctx, req, upstream.Routing, firstNonEmpty(upstream.PoolAccountID, upstream.AccountID)) - } + h.finishRelayedStream(ctx, upstream, relayErr) if relayErr != nil { - // The upstream answered 200 and failed inside the stream, so the - // executor's attempt loop never saw it. Feed the classified state - // back into the pool so the next request can route around a - // quota-exhausted account. Use req.Model (prefix-stripped by - // resolveProviderFilter) so the cooldown key matches the key - // PickRoute uses; publicModel may still carry "qoder/" and would - // write a cooldown that routing never hits. - if r.Context().Err() == nil && !errors.Is(relayErr, context.Canceled) && !errors.Is(relayErr, context.DeadlineExceeded) && !IsStreamClientDisconnect(relayErr) { - h.Executor.ObserveStreamFailure(firstNonEmpty(upstream.PoolAccountID, upstream.AccountID), relayErr, req.Model) - } panic(http.ErrAbortHandler) } return } - res, err := h.Executor.ChatNonStream(ctx, req, prefer, providerFilter) + res, err := h.Executor.ChatNonStreamPrepared(ctx, req, execution.Route) + defer h.refreshQuotaAfterUse(res.PoolAccountID, res.CooldownModel, res.AggregateFEFO) if err != nil { h.finishRequestLog(requestID, started, req, publicModel, res.AccountID, firstNonEmpty(res.Provider, providerFilter), res.Routing, accounts.RequestStatusError, 0, nil, err, res.AttemptCount, res.ReasoningLevel) WriteClassifiedErr(w, err) @@ -198,33 +202,34 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) if publicModel != "" { res.Model = publicModel } - h.finishRequestLog(requestID, started, req, publicModel, res.AccountID, firstNonEmpty(res.Provider, providerFilter), res.Routing, accounts.RequestStatusOK, 0, &StreamRelayStats{ + turn, canonicalErr := canonicalNonStreamTurn(execution.Route.Tooling, res) + if canonicalErr != nil { + h.finishRequestLog(requestID, started, req, publicModel, res.AccountID, firstNonEmpty(res.Provider, providerFilter), res.Routing, accounts.RequestStatusError, 0, nil, canonicalErr, res.AttemptCount, res.ReasoningLevel) + writeToolCallResultError(w, canonicalErr) + return + } + stats := &StreamRelayStats{ PromptTokens: ptrInt(res.PromptTokens), CompletionTokens: ptrInt(res.CompletionTokens), CacheReadTokens: res.CacheReadTokens, CacheWriteTokens: res.CacheWriteTokens, CachedTokens: res.CachedTokens, UsageSource: res.UsageSource, Credits: res.Credits, ConsumedCredits: res.ConsumedCredits, Model: res.Model, - }, nil, res.AttemptCount, res.ReasoningLevel) + UpstreamTerminal: "done", RequestState: "sent", + } + rendered := toolcall.RenderChat(turn) message := map[string]any{ "role": "assistant", - "content": res.Content, + "content": rendered.Text, } - if res.Reasoning != "" { - message["reasoning_content"] = res.Reasoning + if rendered.Reasoning != "" { + message["reasoning_content"] = rendered.Reasoning } - if len(res.ToolCalls) > 0 && string(res.ToolCalls) != "null" { - message["tool_calls"] = json.RawMessage(res.ToolCalls) - if res.Content == "" { + if len(rendered.Calls) > 0 { + message["tool_calls"] = canonicalChatToolCalls(rendered.Calls) + if rendered.Text == "" { message["content"] = nil } } - finishReason := res.FinishReason - if finishReason == "" { - if len(res.ToolCalls) > 0 && string(res.ToolCalls) != "null" { - finishReason = "tool_calls" - } else { - finishReason = "stop" - } - } + finishReason := rendered.FinishReason if res.AccountID != "" { w.Header().Set("X-Qoder-Account", res.AccountID) w.Header().Set("X-CLI2API-Account", res.AccountID) @@ -232,7 +237,7 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) if provider := firstNonEmpty(res.Provider, providerFilter); provider != "" { w.Header().Set("X-CLI2API-Provider", provider) } - writeJSON(w, http.StatusOK, map[string]any{ + if writeErr := writeJSONResult(w, http.StatusOK, map[string]any{ "id": "chatcmpl-" + requestID, "object": "chat.completion", "created": time.Now().Unix(), @@ -243,13 +248,16 @@ func (h *Handler) HandleChatCompletions(w http.ResponseWriter, r *http.Request) "finish_reason": finishReason, }}, "usage": BuildChatUsage(res), - }) + }); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + h.finishRequestLog(requestID, started, req, publicModel, res.AccountID, firstNonEmpty(res.Provider, providerFilter), res.Routing, accounts.RequestStatusCanceled, 0, stats, writeErr, res.AttemptCount, res.ReasoningLevel) + return + } + stats.DownstreamTerminal, stats.FlushState = "done", "ok" + h.finishRequestLog(requestID, started, req, publicModel, res.AccountID, firstNonEmpty(res.Provider, providerFilter), res.Routing, accounts.RequestStatusOK, 0, stats, nil, res.AttemptCount, res.ReasoningLevel) } func (h *Handler) finishRequestLog(requestID string, started time.Time, req translate.ChatRequest, publicModel, accountID, provider, routing, status string, ttfb int, stats *StreamRelayStats, err error, attemptCount int, resolvedReasoning string) { - if accountID != "" && h.AfterAccountUse != nil && status != accounts.RequestStatusStarted && status != accounts.RequestStatusStreaming { - h.AfterAccountUse(accountID, firstNonEmpty(req.Model, publicModel)) - } if h.Recorder == nil || requestID == "" { return } @@ -278,6 +286,10 @@ func (h *Handler) finishRequestLog(requestID string, started time.Time, req tran entry.TTFBMs = entry.LatencyMs } if stats != nil { + entry.UpstreamTerminal = stats.UpstreamTerminal + entry.DownstreamTerminal = stats.DownstreamTerminal + entry.FlushState = stats.FlushState + entry.RequestState = stats.RequestState entry.PromptTokens = stats.PromptTokens entry.CompletionTokens = stats.CompletionTokens entry.CacheReadTokens = stats.CacheReadTokens @@ -292,13 +304,25 @@ func (h *Handler) finishRequestLog(requestID string, started time.Time, req tran entry.MappedModel = stats.Model } } + deriveRelayQuality(started, stats) if err != nil { classified := ClassifyAPIError(err) entry.ErrorKind = classified.Kind entry.ErrorCode = classified.Code entry.ErrorMessage = classified.Message + if entry.RequestState == "" { + entry.RequestState = classified.RequestState + } + } else if entry.RequestState == "" && status == accounts.RequestStatusOK { + // A buffered response proves the upstream request was sent; it does not + // prove the downstream JSON write succeeded. Delivery remains a separate + // fact and is not inferred from status. + entry.RequestState = executor.RequestStateSent } h.Recorder.Finish(entry) + if !req.Stream && requestID != "" { + h.Recorder.Finalize(requestID) + } logCacheDiagnostics(entry, routing) if stats != nil && entry.Credits != nil { h.Recorder.UsageDetail(accounts.RequestUsageDetail{ diff --git a/internal/gateway/openai_stream.go b/internal/gateway/openai_stream.go index 8071cc2ff..3003a2ed3 100644 --- a/internal/gateway/openai_stream.go +++ b/internal/gateway/openai_stream.go @@ -5,30 +5,54 @@ import ( "encoding/json" "errors" "io" - "log" "net/http" "strings" "time" "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" ) const maxSSELineSize = 16 * 1024 * 1024 type StreamFlushWriter struct { - W http.ResponseWriter - F http.Flusher + W http.ResponseWriter + RC *http.ResponseController +} + +func newStreamFlushWriter(w http.ResponseWriter) (StreamFlushWriter, bool) { + if _, ok := w.(http.Flusher); ok { + return StreamFlushWriter{W: w, RC: http.NewResponseController(w)}, true + } + // Since Go 1.20 ResponseController also recognizes a FlushError method even + // when the writer does not expose the legacy error-less Flusher interface. + if _, ok := w.(interface{ FlushError() error }); ok { + return StreamFlushWriter{W: w, RC: http.NewResponseController(w)}, true + } + return StreamFlushWriter{}, false } func (w StreamFlushWriter) Write(data []byte) (int, error) { n, err := w.W.Write(data) - if n > 0 { - w.F.Flush() + if err != nil { + return n, err + } + if n > 0 && w.RC != nil { + if flushErr := w.RC.Flush(); flushErr != nil { + return n, &StreamRelayWriteError{err: flushErr} + } } return n, err } +func flushResponse(w http.ResponseWriter) error { + if w == nil { + return nil + } + return http.NewResponseController(w).Flush() +} + type StreamRelayStats struct { PromptTokens *int CompletionTokens *int @@ -46,6 +70,31 @@ type StreamRelayStats struct { BytesRead int64 LastEvent string SawDone bool + // UpstreamTerminal is done, error, eof, or none. It records what the + // upstream sent, not whether the client received it. + UpstreamTerminal string + // DownstreamDone is true only after the terminal frame for this protocol + // was written and flushed successfully. + DownstreamDone bool + // DownstreamTerminal is done/error/none: what the relay wrote as the final + // frame for this protocol. DownstreamDone carries the successful-write bit. + DownstreamTerminal string + // FlushState is ok/error for the final downstream flush. A write that + // returned success but could not flush did not deliver the frame. + FlushState string + // RequestState mirrors the executor's send fact for the accepted attempt. + RequestState string + // RelayEndAt is when the relay loop finished; it anchors the decode-window + // throughput and TPOT calculations. + RelayEndAt time.Time + // OutputTPS is the full-request output rate (completion tokens / E2E). + OutputTPS float64 + // DecodeTPS is the decode-only output rate over the generation window. + DecodeTPS float64 + // TPOT is the decode-window time per output token, seconds/token. + TPOT float64 + // Completeness is the delivery verdict derived from terminal facts. + Completeness string } type countingReader struct { @@ -77,20 +126,25 @@ func (e *StreamRelayWriteError) Unwrap() error { return e.err } -func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelayStats, returnErr error) { +func RelayOpenAIStream(w http.ResponseWriter, body io.Reader, requests ...toolcall.Request) (stats StreamRelayStats, returnErr error) { + body, stopFirstFrame := guardFirstFrame(body) + defer stopFirstFrame() countedBody := &countingReader{reader: body} defer func() { stats.BytesRead = countedBody.bytes }() var writer io.Writer = w - if flusher, ok := w.(http.Flusher); ok { - writer = StreamFlushWriter{W: w, F: flusher} + if flushWriter, ok := newStreamFlushWriter(w); ok { + writer = flushWriter } scanner := bufio.NewScanner(countedBody) scanner.Buffer(make([]byte, 0, 64*1024), maxSSELineSize) - sawDone := false var frame []string - var streamErr error - normalizer := newOpenAIToolNormalizer() + normalizer := newOpenAIToolNormalizer(requests...) + defer func() { + if normalizer.canonical != nil && normalizer.canonicalErr == nil { + stats.FinishReason = normalizer.canonicalFinishReason() + } + }() argsFlushed := false flushToolArguments := func() error { @@ -99,19 +153,20 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay } argsFlushed = true frames := normalizer.flushFrames() + if normalizer.canonicalErr != nil { + _ = writeStructuredStreamError(writer, normalizer.canonicalErr) + return normalizer.canonicalErr + } if len(frames) == 0 { return nil } - if normalizer.changed { - log.Printf("tool call arguments normalized stream=chat_completion calls=%d finish_reason=%q", len(frames), normalizer.finish) - } for _, payload := range frames { encoded, err := json.Marshal(payload) if err != nil { continue } - if _, err := io.WriteString(writer, "data: "+string(encoded)+"\n\n"); err != nil { - return &StreamRelayWriteError{err: err} + if err := writeSSEString(writer, "data: "+string(encoded)+"\n\n"); err != nil { + return err } } return nil @@ -125,19 +180,19 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay stats.SSEEventCount++ stats.LastEvent = eventName if classifiedErr := classifyStreamSSEError(eventName, data); classifiedErr != nil { - if streamErr == nil { - streamErr = classifiedErr - } if err := writeStructuredStreamError(writer, classifiedErr); err != nil { return err } - frame = nil - return nil + stats.UpstreamTerminal = "error" + // A structured error is terminal, even if the upstream does not + // close the socket or follows it with a synthetic [DONE]. + return classifiedErr } // Each data line is handled on its own: upstreams differ on whether they // put one JSON payload per line, and a frame may bundle content, usage and // [DONE] together. Tool-call fragments are absorbed and withheld here so // a damaged buffer never reaches the client as fragments. + frameDone := false lines := make([]string, 0, len(frame)) for _, rawLine := range frame { line := strings.TrimSuffix(rawLine, "\r") @@ -153,10 +208,9 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay if err := flushToolArguments(); err != nil { return err } - sawDone = true - stats.SawDone = true + frameDone = true lines = append(lines, line) - continue + break } if payload != "" { var decoded map[string]any @@ -175,6 +229,9 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay if err := flushToolArguments(); err != nil { return err } + if normalizer.canonical != nil { + stats.FinishReason = normalizer.canonicalFinishReason() + } } } } @@ -195,8 +252,15 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay stats = usage } } - if _, err := io.WriteString(writer, strings.Join(lines, "\n")+"\n\n"); err != nil { - return &StreamRelayWriteError{err: err} + if err := writeSSEString(writer, strings.Join(lines, "\n")+"\n\n"); err != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return err + } + stats.SawDone = frameDone + if frameDone { + stats.UpstreamTerminal = "done" + stats.DownstreamDone = true + stats.DownstreamTerminal, stats.FlushState = "done", "ok" } frame = nil return nil @@ -208,44 +272,55 @@ func RelayOpenAIStream(w http.ResponseWriter, body io.Reader) (stats StreamRelay if err := flushFrame(); err != nil { return stats, err } + if stats.SawDone { + return stats, nil + } continue } frame = append(frame, line) } if err := scanner.Err(); err != nil { - if streamErr != nil { - return stats, streamErr - } + stats.UpstreamTerminal = "eof" streamErr := executor.StreamReadError(err) if writeErr := writeStructuredStreamError(writer, streamErr); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" return stats, writeErr } + stats.DownstreamTerminal, stats.FlushState = "error", "ok" return stats, streamErr } if err := flushFrame(); err != nil { return stats, err } - if streamErr != nil { - return stats, streamErr - } - if !sawDone { + if !stats.SawDone { if stats.FinishReason != "" && (stats.FirstTokenAt != nil || stats.SSEEventCount > 0) { - sawDone = true stats.SawDone = true + stats.UpstreamTerminal = "done" if err := flushToolArguments(); err != nil { return stats, err } - if _, err := io.WriteString(writer, "data: [DONE]\n\n"); err != nil { - return stats, &StreamRelayWriteError{err: err} + if err := writeSSEString(writer, "data: [DONE]\n\n"); err != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + return stats, err } + stats.DownstreamDone = true + stats.DownstreamTerminal, stats.FlushState = "done", "ok" return stats, nil } + stats.UpstreamTerminal = "eof" streamErr := executor.StreamIncompleteError() if writeErr := writeStructuredStreamError(writer, streamErr); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" return stats, writeErr } + stats.DownstreamTerminal, stats.FlushState = "error", "ok" return stats, streamErr } + if stats.SawDone && !stats.DownstreamDone { + // The upstream terminal frame was seen but its write failed; the + // caller must not record success. + return stats, &StreamRelayWriteError{err: errors.New("terminal frame was not delivered")} + } return stats, nil } @@ -259,8 +334,11 @@ func writeStructuredStreamError(writer io.Writer, err error) error { status = http.StatusBadGateway } code := firstNonEmpty(classified.Code, "upstream_error") - typ := firstNonEmpty(classified.Type, "api_error") - message := firstNonEmpty(classified.Message, code) + typ := openaiErrorType(classified) + message := executor.PublicErrorMessage(classified) + if message == "" { + message = code + } errorPayload := map[string]any{ "message": message, "type": typ, @@ -283,8 +361,8 @@ func writeStructuredStreamError(writer io.Writer, err error) error { if marshalErr != nil { return marshalErr } - if _, writeErr := io.WriteString(writer, "data: "+string(payload)+"\n\n"); writeErr != nil { - return &StreamRelayWriteError{err: writeErr} + if writeErr := writeSSEString(writer, "data: "+string(payload)+"\n\n"); writeErr != nil { + return writeErr } return nil } @@ -313,121 +391,7 @@ func parseSSEFrame(lines []string) (eventName, data string) { } func classifyStreamSSEError(eventName, data string) error { - force := strings.EqualFold(strings.TrimSpace(eventName), "error") - if !force && !streamJSONLooksLikeError(data) { - return nil - } - status := streamErrorStatus(data) - body := strings.TrimSpace(data) - if inner := streamErrorBody(data); inner != "" { - body = inner - } - return executor.ClassifyUpstreamBody(status, body) -} - -func streamJSONLooksLikeError(raw string) bool { - var value any - if json.Unmarshal([]byte(strings.TrimSpace(raw)), &value) != nil { - return false - } - return streamValueLooksLikeError(value) -} - -func streamValueLooksLikeError(value any) bool { - object, ok := value.(map[string]any) - if !ok { - if nested, ok := value.(string); ok { - var parsed any - return json.Unmarshal([]byte(strings.TrimSpace(nested)), &parsed) == nil && streamValueLooksLikeError(parsed) - } - return false - } - if _, ok := object["choices"]; ok { - return false - } - if _, ok := object["error"]; ok { - return true - } - if nested, ok := object["body"]; ok { - if streamValueLooksLikeError(nested) { - return true - } - } - if status, ok := object["status"].(float64); ok && status >= 400 { - return true - } - for _, key := range []string{"code", "msgCode", "kind"} { - if _, ok := object[key]; ok { - return true - } - } - if message, ok := object["message"].(string); ok && strings.TrimSpace(message) != "" { - return true - } - return false -} - -func streamErrorBody(raw string) string { - var value any - if json.Unmarshal([]byte(strings.TrimSpace(raw)), &value) != nil { - return "" - } - for { - switch current := value.(type) { - case string: - var nested any - if json.Unmarshal([]byte(strings.TrimSpace(current)), &nested) != nil { - return current - } - value = nested - case map[string]any: - nested, ok := current["body"] - if !ok { - encoded, err := json.Marshal(current) - if err != nil { - return raw - } - return string(encoded) - } - value = nested - default: - return raw - } - } -} - -func streamErrorStatus(raw string) int { - var value any - if json.Unmarshal([]byte(strings.TrimSpace(raw)), &value) != nil { - return 0 - } - for { - switch current := value.(type) { - case map[string]any: - for _, key := range []string{"status", "statusCode", "statusCodeValue"} { - if status, ok := current[key].(float64); ok && int(status) >= 400 { - return int(status) - } - } - if nested, ok := current["body"]; ok { - value = nested - continue - } - if nested, ok := current["error"]; ok { - value = nested - continue - } - return 0 - case string: - var nested any - if json.Unmarshal([]byte(strings.TrimSpace(current)), &nested) != nil { - return 0 - } - value = nested - default: - return 0 - } - } + return executor.ClassifyStreamEvent(eventName, data) } func IsStreamClientDisconnect(err error) bool { diff --git a/internal/gateway/openai_tool_normalizer.go b/internal/gateway/openai_tool_normalizer.go index ec3ce400f..c59039057 100644 --- a/internal/gateway/openai_tool_normalizer.go +++ b/internal/gateway/openai_tool_normalizer.go @@ -2,30 +2,30 @@ package gateway import ( "encoding/json" - "sort" "strconv" - "github.com/caigee-cmd/cli2api/internal/translate" + "github.com/caigee-cmd/cli2api/internal/toolcall" ) -// openAIToolNormalizer keeps an OpenAI chat-completions stream faithful frame -// by frame except for tool-call arguments. Arguments are accumulated and -// flushed once per call, normalized to valid JSON, because a client that -// concatenates damaged upstream fragments aborts the round with "arguments are -// invalid JSON". Content, reasoning, usage and finish frames relay unchanged. +// openAIToolNormalizer relays content and metadata frame by frame, but holds +// tool-call fragments until the canonical reducer seals the turn. A client that +// concatenates damaged upstream fragments would otherwise abort with "arguments +// are invalid JSON"; the reducer either repairs safe damage or fails the turn. type openAIToolNormalizer struct { - calls map[int]*proxyToolCall - emitted map[int]bool - changed bool - finish string - meta map[string]any + finish string + meta map[string]any + + canonical *toolcall.Reducer + canonicalResult toolcall.TurnResult + canonicalErr error } -func newOpenAIToolNormalizer() *openAIToolNormalizer { - return &openAIToolNormalizer{ - calls: map[int]*proxyToolCall{}, - emitted: map[int]bool{}, +func newOpenAIToolNormalizer(request ...toolcall.Request) *openAIToolNormalizer { + var declared toolcall.Request + if len(request) > 0 { + declared = request[0] } + return &openAIToolNormalizer{canonical: toolcall.NewReducer(declared)} } // absorb consumes one chunk payload and returns the payload that should still @@ -49,18 +49,25 @@ func (n *openAIToolNormalizer) absorb(payload map[string]any) map[string]any { if !ok { continue } - if finish, ok := choice["finish_reason"].(string); ok && finish != "" { - n.finish = finish + finish := "" + if value, ok := choice["finish_reason"].(string); ok && value != "" { + n.finish = value + finish = value + delete(choice, "finish_reason") } delta, ok := choice["delta"].(map[string]any) if !ok { continue } rawCalls, hasCalls := delta["tool_calls"].([]any) + chatDelta := canonicalChatDelta(delta, rawCalls) + chatDelta.FinishReason = finish + if _, err := n.canonical.Absorb(chatDelta); err != nil { + n.canonicalErr = err + } if !hasCalls || len(rawCalls) == 0 { continue } - n.absorbCalls(rawCalls) delete(delta, "tool_calls") if len(delta) == 0 && choice["finish_reason"] == nil { dropped = true @@ -72,125 +79,63 @@ func (n *openAIToolNormalizer) absorb(payload map[string]any) map[string]any { return payload } -func (n *openAIToolNormalizer) absorbCalls(rawCalls []any) { +func canonicalChatDelta(delta map[string]any, rawCalls []any) toolcall.ChatDelta { + chat := toolcall.ChatDelta{} + if text, ok := delta["content"].(string); ok { + chat.Content = text + } + if reasoning, ok := delta["reasoning_content"].(string); ok { + chat.Reasoning = reasoning + } for position, rawCall := range rawCalls { call, ok := rawCall.(map[string]any) if !ok { continue } + index := position + if value, ok := call["index"].(float64); ok { + index = int(value) + } id, _ := call["id"].(string) function, _ := call["function"].(map[string]any) name, _ := function["name"].(string) - arguments := argumentFragment(rawArguments(function["arguments"])) - index := n.resolveIndex(call, id, name, position) - entry := n.calls[index] - if entry == nil { - entry = &proxyToolCall{} - n.calls[index] = entry - } - if id != "" { - entry.ID = id - } - if name != "" { - entry.Name = name - } - merged := mergeToolArguments(entry.Arguments, arguments) - if merged != entry.Arguments { - entry.Arguments = merged - } - } + chat.ToolCalls = append(chat.ToolCalls, toolcall.ChatToolDelta{ + Index: &index, + ID: id, + Name: name, + Arguments: argumentFragment(rawArguments(function["arguments"])), + }) + } + return chat } -func (n *openAIToolNormalizer) resolveIndex(call map[string]any, id, name string, position int) int { - declared := -1 - if value, ok := call["index"].(float64); ok { - declared = int(value) - } - startsCall := id != "" || name != "" - if declared >= 0 && !startsCall { - return declared - } - if declared >= 0 { - if n.callIsDifferent(declared, id, name) { - return n.nextIndex() - } - return declared - } - if startsCall { - if n.callIsDifferent(0, id, name) { - return n.nextIndex() - } - return 0 - } - return n.lastIndex(position) -} - -func (n *openAIToolNormalizer) callIsDifferent(index int, id, name string) bool { - existing := n.calls[index] - if existing == nil || (existing.Name == "" && existing.ID == "") { - return false - } - if id != "" && existing.ID != "" { - return existing.ID != id - } - return name != "" && existing.Name != "" && existing.Name != name -} - -func (n *openAIToolNormalizer) nextIndex() int { - maximum := -1 - for index := range n.calls { - if index > maximum { - maximum = index - } - } - return maximum + 1 -} - -func (n *openAIToolNormalizer) lastIndex(position int) int { - maximum := -1 - for index, call := range n.calls { - if call != nil && call.Name != "" && index > maximum { - maximum = index - } - } - if maximum >= 0 { - return maximum - } - return position -} - -// flushFrames returns one frame per call that has not been delivered yet, each -// carrying the normalized full argument string. +// flushFrames returns one frame per canonical call, each carrying the full +// validated argument string, followed by the terminal finish frame. func (n *openAIToolNormalizer) flushFrames() []map[string]any { - indexes := make([]int, 0, len(n.calls)) - for index, call := range n.calls { - if call == nil || call.Name == "" || n.emitted[index] { - continue - } - indexes = append(indexes, index) - } - sort.Ints(indexes) - frames := make([]map[string]any, 0, len(indexes)) - for _, index := range indexes { - call := n.calls[index] - arguments, changed := translate.NormalizeToolCallArguments(call.Arguments) - if changed { - n.changed = true - } - if call.ID == "" { - call.ID = "call_" + call.Name + "_" + strconv.Itoa(index) + result, err := n.canonical.Finish("done") + n.canonicalResult = result + if err != nil { + n.canonicalErr = err + return nil + } + frames := make([]map[string]any, 0, len(result.Calls)+1) + for position := range result.Calls { + call := result.Calls[position] + id := call.InternalID + if id == "" { + id = "call_" + call.Name + "_" + strconv.Itoa(position) } frames = append(frames, n.frame(map[string]any{ - "index": index, - "id": call.ID, + "index": position, + "id": id, "type": "function", "function": map[string]any{ "name": call.Name, - "arguments": arguments, + "arguments": string(call.Arguments), }, })) - n.emitted[index] = true } + frames = append(frames, n.terminalFrame(result)) return frames } @@ -209,6 +154,40 @@ func (n *openAIToolNormalizer) frame(call map[string]any) map[string]any { return payload } +func (n *openAIToolNormalizer) canonicalFinishReason() string { + if n.canonicalResult.Status == toolcall.TurnToolCalls { + return "tool_calls" + } + if n.canonicalResult.FinishReason != "" { + return n.canonicalResult.FinishReason + } + if n.finish != "" { + return n.finish + } + return "stop" +} + +func (n *openAIToolNormalizer) terminalFrame(result toolcall.TurnResult) map[string]any { + finish := result.FinishReason + if result.Status == toolcall.TurnToolCalls { + finish = "tool_calls" + } else if finish == "" { + finish = "stop" + } + payload := map[string]any{ + "object": "chat.completion.chunk", + "choices": []any{map[string]any{ + "index": 0, + "delta": map[string]any{}, + "finish_reason": finish, + }}, + } + for key, value := range n.meta { + payload[key] = value + } + return payload +} + func rawArguments(value any) json.RawMessage { if value == nil { return nil diff --git a/internal/gateway/prepare.go b/internal/gateway/prepare.go index b634be481..2e000f016 100644 --- a/internal/gateway/prepare.go +++ b/internal/gateway/prepare.go @@ -23,23 +23,28 @@ type Execution struct { PublicModel string ProviderFilter string Prefer string + Route executor.RouteInput // ResponseToolNames restores namespaced Responses tool identities on the // reply. Gateway-local: it is never handed to the executor or a provider. ResponseToolNames map[string]translate.ResponseToolName } func (h *Handler) PrepareNativeResponsesExecution(r *http.Request, native *translate.NativeResponsesRequest, compat translate.ChatRequest) (Execution, error) { + return h.prepareNativeResponsesExecution(r, native, compat, nil) +} + +func (h *Handler) prepareNativeResponsesExecution(r *http.Request, native *translate.NativeResponsesRequest, compat translate.ChatRequest, beforeSideEffects func() error) (Execution, error) { if native == nil { return Execution{}, &chatHTTPError{Status: http.StatusBadRequest, Code: "invalid_request", Message: "responses request required"} } - return h.prepareExecution(r, compat, native) + return h.prepareExecution(r, compat, native, beforeSideEffects) } func (h *Handler) PrepareChatExecution(r *http.Request, request translate.ChatRequest) (Execution, error) { - return h.prepareExecution(r, request, nil) + return h.prepareExecution(r, request, nil, nil) } -func (h *Handler) prepareExecution(r *http.Request, request translate.ChatRequest, native *translate.NativeResponsesRequest) (Execution, error) { +func (h *Handler) prepareExecution(r *http.Request, request translate.ChatRequest, native *translate.NativeResponsesRequest, beforeSideEffects func() error) (Execution, error) { var identity auth.Identity if r != nil { identity = h.requestIdentity(r) @@ -86,6 +91,7 @@ func (h *Handler) prepareExecution(r *http.Request, request translate.ChatReques Catalogs: catalogs, Aggregations: aggregations, Logs: logs, + BeforeSideEffects: beforeSideEffects, }) if err != nil { return Execution{}, err @@ -100,10 +106,15 @@ func (h *Handler) prepareExecution(r *http.Request, request translate.ChatReques ProviderFilter: got.ProviderFilter, Prefer: got.Prefer, + Route: got.Route, }, nil } func writeChatHTTPError(w http.ResponseWriter, err error) { + if errors.Is(err, errKeyConcurrencyLimited) { + writeKeyConcurrencyLimited(w) + return + } var requestErr *chatHTTPError if errors.As(err, &requestErr) { writeErr(w, requestErr.Status, requestErr.Code, requestErr.Message) diff --git a/internal/gateway/public_error_exit_test.go b/internal/gateway/public_error_exit_test.go new file mode 100644 index 000000000..359058e5f --- /dev/null +++ b/internal/gateway/public_error_exit_test.go @@ -0,0 +1,51 @@ +package gateway + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +func TestPublicErrorExitsDoNotRelayProviderBodies(t *testing.T) { + const marker = "SENSITIVE_MARKER_123" + classified := executor.Classified{ + Kind: accounts.KindUnavailable, + Status: http.StatusBadGateway, + Source: "provider_http", + Code: "upstream_error", + Message: "workbuddy rejected: " + marker + " Authorization: Bearer abcdefghijklmnop", + } + executionErr := executor.NewExecutionError(classified, nil) + + t.Run("http", func(t *testing.T) { + recorder := httptest.NewRecorder() + WriteClassifiedErr(recorder, executionErr) + if recorder.Code != http.StatusBadGateway { + t.Fatalf("status = %d", recorder.Code) + } + if strings.Contains(recorder.Body.String(), marker) || strings.Contains(recorder.Body.String(), "Bearer") { + t.Fatalf("HTTP error leaked provider body: %s", recorder.Body.String()) + } + if !strings.Contains(recorder.Body.String(), "upstream service error") { + t.Fatalf("HTTP error lost its public message: %s", recorder.Body.String()) + } + }) + + t.Run("compat sse", func(t *testing.T) { + var output bytes.Buffer + if err := writeStructuredStreamError(&output, executionErr); err != nil { + t.Fatal(err) + } + if strings.Contains(output.String(), marker) || strings.Contains(output.String(), "Bearer") { + t.Fatalf("SSE error leaked provider body: %s", output.String()) + } + if !strings.Contains(output.String(), "upstream service error") { + t.Fatalf("SSE error lost its public message: %s", output.String()) + } + }) +} diff --git a/internal/gateway/quality.go b/internal/gateway/quality.go new file mode 100644 index 000000000..e597fde4d --- /dev/null +++ b/internal/gateway/quality.go @@ -0,0 +1,34 @@ +package gateway + +import ( + "time" + + "github.com/caigee-cmd/cli2api/internal/quality" +) + +// deriveRelayQuality fills the derived throughput, TPOT, and delivery-verdict +// facts on the relay stats. It is pure computation: persisted terminal facts +// remain the source the stats aggregation reads, while these transient values +// are available to tests and in-memory diagnostics. +func deriveRelayQuality(started time.Time, stats *StreamRelayStats) { + if stats == nil { + return + } + finished := time.Now().UTC() + stats.RelayEndAt = finished + completion := 0 + if stats.CompletionTokens != nil { + completion = *stats.CompletionTokens + } + stats.OutputTPS = quality.FullTPS(completion, finished.Sub(started)) + if stats.FirstTokenAt != nil { + stats.DecodeTPS = quality.DecodeTPS(completion, *stats.FirstTokenAt, finished) + stats.TPOT = quality.TPOT(completion, *stats.FirstTokenAt, finished) + } + stats.Completeness = string(quality.ClassifyCompleteness(quality.TerminalFacts{ + UpstreamTerminal: stats.UpstreamTerminal, + DownstreamTerminal: stats.DownstreamTerminal, + FlushState: stats.FlushState, + SawDone: stats.SawDone, + })) +} diff --git a/internal/gateway/quality_test.go b/internal/gateway/quality_test.go new file mode 100644 index 000000000..a7a58b3cd --- /dev/null +++ b/internal/gateway/quality_test.go @@ -0,0 +1,42 @@ +package gateway + +import ( + "testing" + "time" +) + +func TestDeriveRelayQuality(t *testing.T) { + started := time.Now().UTC().Add(-500 * time.Millisecond) + first := started.Add(200 * time.Millisecond) + completion := 40 + stats := &StreamRelayStats{ + CompletionTokens: &completion, + FirstTokenAt: &first, + UpstreamTerminal: "done", + DownstreamTerminal: "done", + FlushState: "ok", + SawDone: true, + } + + deriveRelayQuality(started, stats) + + if stats.OutputTPS <= 0 { + t.Error("OutputTPS not computed") + } + if stats.DecodeTPS <= 0 { + t.Error("DecodeTPS not computed") + } + if stats.TPOT <= 0 { + t.Error("TPOT not computed") + } + if stats.Completeness != "complete" { + t.Errorf("Completeness = %q, want complete", stats.Completeness) + } + if stats.RelayEndAt.IsZero() { + t.Error("RelayEndAt not set") + } +} + +func TestDeriveRelayQualityNilStats(t *testing.T) { + deriveRelayQuality(time.Now().UTC(), nil) // must not panic +} diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index e50d162a1..ec2308a50 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "encoding/json" - "errors" "fmt" "io" "net/http" @@ -13,6 +12,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -24,11 +24,17 @@ func (h *Handler) HandleResponses(w http.ResponseWriter, r *http.Request) { bodyReader := decodeRequestBody(w, r, translate.MaxNativeRequestBytes, translate.MaxNativeRequestBytes) defer bodyReader.Close() if bodyReader.err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request", bodyReader.err.Error()) writeRequestBodyError(w, bodyReader.err) return } body, err := io.ReadAll(io.LimitReader(bodyReader, translate.MaxNativeRequestBytes+1)) if err != nil { + code := "invalid_request" + if isRequestBodyTooLarge(err) { + code = "request_too_large" + } + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, code, err.Error()) if isRequestBodyTooLarge(err) { writeRequestBodyError(w, err) return @@ -37,6 +43,7 @@ func (h *Handler) HandleResponses(w http.ResponseWriter, r *http.Request) { return } if len(body) > translate.MaxNativeRequestBytes { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "request_too_large", "request body too large") writeErr(w, http.StatusRequestEntityTooLarge, "invalid_request", "request body too large") return } @@ -45,6 +52,7 @@ func (h *Handler) HandleResponses(w http.ResponseWriter, r *http.Request) { } native, err := translate.ParseNativeResponses(body) if err != nil { + h.recordEntryRejection(r, "", accounts.KindInvalidRequest, "invalid_request", err.Error()) writeErr(w, http.StatusBadRequest, "invalid_request", err.Error()) return } @@ -57,105 +65,200 @@ func (h *Handler) HandleResponses(w http.ResponseWriter, r *http.Request) { if compatErr == nil { compatRequest = translated.Chat } - execution, err := h.PrepareNativeResponsesExecution(r, native, compatRequest) + reserveKey, releaseKey := h.keySlotHooks(r) + defer releaseKey() + execution, err := h.prepareNativeResponsesExecution(r, native, compatRequest, reserveKey) if err != nil { - writeCompatibilityOpenAIError(w, err) + h.recordPrepareRejection(r, native.Model(), err) + writeChatHTTPError(w, err) return } - releaseKey, ok := h.reserveKeySlot(r) - if !ok { - writeKeyConcurrencyLimited(w) - return - } - defer releaseKey() + w.Header().Set("X-Request-Id", execution.RequestID) execution.ResponseToolNames = translated.ToolNames if len(execution.ResponseToolNames) == 0 && execution.NativeRequest != nil { execution.ResponseToolNames = translate.ResponseToolNames(execution.NativeRequest.Body()) } - execution.UseNativeResponses = h.Executor.HasNativeResponsesRoute(execution.Context, execution.Request, execution.Prefer, execution.ProviderFilter) + // A compatible named aggregation must choose the same member it would for + // Chat first, then let that selected target decide whether native Responses + // is available. An incompatible request still requires a native member. + execution.UseNativeResponses = execution.Route.AggregatePlan != nil && compatErr == nil + if !execution.UseNativeResponses { + execution.UseNativeResponses = h.Executor.HasNativeResponsesRoutePrepared(execution.Context, execution.Request, execution.Route) + } if !execution.UseNativeResponses && compatErr != nil { - writeErr(w, http.StatusBadRequest, "unsupported_request", "this Responses request requires a native Responses adapter") + classified := executor.Classified{ + Kind: accounts.KindInvalidRequest, + Status: http.StatusBadRequest, + Code: "unsupported_request", + Message: "this Responses request requires a native Responses adapter", + } + h.finishCompatibility(execution, "", "", "", accounts.RequestStatusError, 0, nil, executor.NewExecutionError(classified, nil), 0, "") + h.finalizeExecution(execution) + writeTypedErr(w, classified.Status, openaiErrorType(classified), classified.Code, classified.Message) return } - w.Header().Set("X-Request-Id", execution.RequestID) if execution.Request.Stream { h.handleResponsesStream(w, r, execution) return } if execution.UseNativeResponses { - nativeResult, err := h.Executor.NativeResponsesNonStream(execution.Context, execution.Request, execution.NativeRequest, execution.Prefer, execution.ProviderFilter) + nativeResult, err := h.Executor.NativeResponsesNonStreamPrepared(execution.Context, execution.Request, execution.NativeRequest, execution.Route) + defer h.refreshQuotaAfterUse(nativeResult.PoolAccountID, nativeResult.CooldownModel, nativeResult.AggregateFEFO) if err != nil || nativeResult.FinishReason == "error" { if err == nil { err = fmt.Errorf("upstream Responses request failed") } h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusError, 0, nil, err, nativeResult.AttemptCount, nativeResult.ReasoningLevel) - writeCompatibilityOpenAIError(w, err) + h.finalizeExecution(execution) + writeChatHTTPError(w, err) return } - h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, responsesRequestStatus(nativeResult.FinishReason), 0, &StreamRelayStats{ + if nativeResult.CompatResult == nil && execution.Route.Tooling.HasTools() { + if validateErr := validateNativeResponsesToolOutput(nativeResult.Response, execution.Route.Tooling, nativeResult.FinishReason); validateErr != nil { + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusError, 0, nil, validateErr, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, validateErr) + return + } + } + if compatResult := nativeResult.CompatResult; compatResult != nil { + turn, canonicalErr := canonicalNonStreamTurn(execution.Route.Tooling, *compatResult) + if canonicalErr != nil { + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusError, 0, nil, canonicalErr, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, canonicalErr) + return + } + stats := &StreamRelayStats{ + PromptTokens: ptrInt(compatResult.PromptTokens), CompletionTokens: ptrInt(compatResult.CompletionTokens), + CacheReadTokens: compatResult.CacheReadTokens, CacheWriteTokens: compatResult.CacheWriteTokens, + CachedTokens: compatResult.CachedTokens, UsageSource: compatResult.UsageSource, Credits: compatResult.Credits, + ConsumedCredits: compatResult.ConsumedCredits, Model: compatResult.Model, FinishReason: compatResult.FinishReason, + UpstreamTerminal: "done", RequestState: "sent", + } + response, renderErr := canonicalResponsesResponse( + execution.RequestID, firstNonEmpty(compatResult.Model, execution.PublicModel), turn, compatResult.PromptTokens, compatResult.CompletionTokens, toolcall.RenderChat(turn).FinishReason, + compatResult.CacheReadTokens, compatResult.CacheWriteTokens, compatResult.CachedTokens, nil, + ) + if renderErr != nil { + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusError, 0, stats, renderErr, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, renderErr) + return + } + translate.RestoreResponseToolNames(response, execution.ResponseToolNames) + if writeErr := writeJSONResult(w, http.StatusOK, response); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusCanceled, 0, stats, writeErr, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + return + } + stats.DownstreamTerminal, stats.FlushState = "done", "ok" + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, responsesRequestStatus(compatResult.FinishReason), 0, stats, nil, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + return + } + stats := &StreamRelayStats{ PromptTokens: nativeResult.PromptTokens, CompletionTokens: nativeResult.OutputTokens, CachedTokens: nativeResult.CachedTokens, - FinishReason: nativeResult.FinishReason, - }, nil, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + FinishReason: nativeResult.FinishReason, UpstreamTerminal: "done", RequestState: "sent", + } response := restoreNativeResponseJSON(nativeResult.Response, execution.ResponseToolNames) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - _, _ = w.Write(response) + if _, writeErr := w.Write(response); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, accounts.RequestStatusCanceled, 0, stats, writeErr, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) + return + } + stats.DownstreamTerminal, stats.FlushState = "done", "ok" + h.finishCompatibility(execution, nativeResult.AccountID, nativeResult.Provider, nativeResult.Routing, responsesRequestStatus(nativeResult.FinishReason), 0, stats, nil, nativeResult.AttemptCount, nativeResult.ReasoningLevel) + h.finalizeExecution(execution) return } - result, err := h.Executor.ChatNonStream(execution.Context, execution.Request, execution.Prefer, execution.ProviderFilter) + result, err := h.Executor.ChatNonStreamPrepared(execution.Context, execution.Request, execution.Route) + defer h.refreshQuotaAfterUse(result.PoolAccountID, result.CooldownModel, result.AggregateFEFO) if err != nil { h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, nil, err, result.AttemptCount, result.ReasoningLevel) - writeCompatibilityOpenAIError(w, err) + h.finalizeExecution(execution) + writeChatHTTPError(w, err) + return + } + turn, canonicalErr := canonicalNonStreamTurn(execution.Route.Tooling, result) + if canonicalErr != nil { + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, nil, canonicalErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, canonicalErr) return } requestStatus := responsesRequestStatus(result.FinishReason) - h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, requestStatus, 0, &StreamRelayStats{ + stats := &StreamRelayStats{ PromptTokens: ptrInt(result.PromptTokens), CompletionTokens: ptrInt(result.CompletionTokens), CacheReadTokens: result.CacheReadTokens, CacheWriteTokens: result.CacheWriteTokens, CachedTokens: result.CachedTokens, UsageSource: result.UsageSource, Credits: result.Credits, ConsumedCredits: result.ConsumedCredits, Model: result.Model, FinishReason: result.FinishReason, - }, nil, result.AttemptCount, result.ReasoningLevel) - response := responsesResponse( - execution.RequestID, firstNonEmpty(result.Model, execution.PublicModel), result.Content, result.Reasoning, - decodeOpenAIToolCalls(result.ToolCalls), result.PromptTokens, result.CompletionTokens, result.FinishReason, + UpstreamTerminal: "done", RequestState: "sent", + } + response, renderErr := canonicalResponsesResponse( + execution.RequestID, firstNonEmpty(result.Model, execution.PublicModel), turn, result.PromptTokens, result.CompletionTokens, toolcall.RenderChat(turn).FinishReason, result.CacheReadTokens, result.CacheWriteTokens, result.CachedTokens, nil, ) + if renderErr != nil { + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusError, 0, stats, renderErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + writeToolCallResultError(w, renderErr) + return + } translate.RestoreResponseToolNames(response, execution.ResponseToolNames) - writeJSON(w, http.StatusOK, response) + if writeErr := writeJSONResult(w, http.StatusOK, response); writeErr != nil { + stats.DownstreamTerminal, stats.FlushState = "error", "error" + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, accounts.RequestStatusCanceled, 0, stats, writeErr, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) + return + } + stats.DownstreamTerminal, stats.FlushState = "done", "ok" + h.finishCompatibility(execution, result.AccountID, result.Provider, result.Routing, requestStatus, 0, stats, nil, result.AttemptCount, result.ReasoningLevel) + h.finalizeExecution(execution) } func (h *Handler) handleResponsesStream(w http.ResponseWriter, r *http.Request, execution Execution) { var upstream executor.StreamResult var err error if execution.UseNativeResponses { - upstream, err = h.Executor.ChatStreamProxyNativeResponses(execution.Context, execution.Request, execution.NativeRequest, execution.Prefer, execution.ProviderFilter) + upstream, err = h.Executor.ChatStreamProxyNativeResponsesPrepared(execution.Context, execution.Request, execution.NativeRequest, execution.Route) } else { - upstream, err = h.Executor.ChatStreamProxy(execution.Context, execution.Request, execution.Prefer, execution.ProviderFilter) + upstream, err = h.Executor.ChatStreamProxyPrepared(execution.Context, execution.Request, nil, execution.Route) } + defer h.refreshQuotaAfterUse(upstream.PoolAccountID, upstream.CooldownModel, upstream.AggregateFEFO) if err != nil { h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusError, upstream.TTFBMs, nil, err, upstream.AttemptCount, upstream.ReasoningLevel) - writeCompatibilityOpenAIError(w, err) + h.finalizeExecution(execution) + writeChatHTTPError(w, err) return } defer upstream.Response.Body.Close() h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusStreaming, upstream.TTFBMs, nil, nil, upstream.AttemptCount, upstream.ReasoningLevel) setCompatibilityStreamHeaders(w, upstream.AccountID, firstNonEmpty(upstream.Provider, execution.ProviderFilter)) w.WriteHeader(http.StatusOK) - if flusher, ok := w.(http.Flusher); ok { - flusher.Flush() + if flushErr := flushResponse(w); flushErr != nil { + stats := StreamRelayStats{DownstreamTerminal: "error", FlushState: "error"} + h.Executor.FinishStream(execution.Context, upstream, executor.ClientDisconnectError(flushErr)) + h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, accounts.RequestStatusCanceled, upstream.TTFBMs, &stats, flushErr, upstream.AttemptCount, upstream.ReasoningLevel) + h.finalizeExecution(execution) + return } writer := compatibilityStreamWriter(w) - var stats StreamRelayStats + stats := StreamRelayStats{} var relayErr error if upstream.NativeResponses { // The upstream already speaks the Responses protocol: relay verbatim and // observe the terminal event for usage/finish accounting. - stats, relayErr = RelayNativeResponsesStream(writer, upstream.Response.Body, execution.ResponseToolNames) + stats, relayErr = RelayNativeResponsesStream(writer, upstream.Response.Body, execution.ResponseToolNames, execution.Route.Tooling) } else { - stats, relayErr = RelayResponsesStream(writer, upstream.Response.Body, execution.RequestID, firstNonEmpty(execution.PublicModel, execution.Request.Model), execution.ResponseToolNames) + stats, relayErr = RelayResponsesStream(writer, upstream.Response.Body, execution.RequestID, firstNonEmpty(execution.PublicModel, execution.Request.Model), execution.ResponseToolNames, execution.Route.Tooling) } - completed := stats.SawDone || stats.FinishReason != "" - status := streamLogStatus(relayErr, completed, r.Context().Err() != nil) + stats.RequestState = upstream.RequestState + status := streamLogStatus(relayErr, stats, r.Context().Err() != nil) if relayErr == nil { status = responsesRequestStatus(stats.FinishReason) } @@ -169,16 +272,12 @@ func (h *Handler) handleResponsesStream(w http.ResponseWriter, r *http.Request, logErr = nil } h.finishCompatibility(execution, upstream.AccountID, upstream.Provider, upstream.Routing, status, ttfb, &stats, logErr, upstream.AttemptCount, upstream.ReasoningLevel) - if relayErr == nil { - h.Executor.CommitSession(execution.Context, execution.Request, upstream.Routing, firstNonEmpty(upstream.PoolAccountID, upstream.AccountID)) - return - } - // A native failure event was already relayed as the stream's terminal - // frame. Appending a second error event would contradict it. - if !IsStreamClientDisconnect(relayErr) && !(upstream.NativeResponses && stats.FinishReason == "error") { + h.finishRelayedStream(execution.Context, upstream, relayErr) + // When the relay already wrote its structured failure terminal, appending + // another error event would duplicate it. + if relayErr != nil && !IsStreamClientDisconnect(relayErr) && stats.DownstreamTerminal != "error" { _ = writeResponsesStreamError(writer, relayErr) } - h.observeCompatibilityStreamFailure(r, execution, upstream, relayErr) } func restoreNativeResponseJSON(raw json.RawMessage, names map[string]translate.ResponseToolName) []byte { @@ -199,15 +298,6 @@ func restoreNativeResponseJSON(raw json.RawMessage, names map[string]translate.R return encoded } -func writeCompatibilityOpenAIError(w http.ResponseWriter, err error) { - var requestErr *chatHTTPError - if errors.As(err, &requestErr) { - writeErr(w, requestErr.Status, requestErr.Code, requestErr.Message) - return - } - WriteClassifiedErr(w, err) -} - type responsesTerminal struct { status string event string @@ -252,6 +342,60 @@ func responsesRequestStatus(finishReason string) string { return accounts.RequestStatusOK } +// canonicalResponsesResponse renders a non-stream Responses body from the +// canonical turn result. The wire shape stays compatible with the historical +// gateway builder, but text and function-call items come from +// toolcall.RenderResponsesItems rather than being assembled independently. +func canonicalResponsesResponse( + requestID, model string, turn toolcall.TurnResult, + promptTokens, completionTokens int, finishReason string, + cacheReadTokens, cacheWriteTokens, cachedTokens, reasoningTokens *int, +) (map[string]any, error) { + items, err := toolcall.RenderResponsesItems(turn) + if err != nil { + return nil, err + } + output := make([]any, 0, 2+len(items)) + if turn.Reasoning != "" { + output = append(output, map[string]any{"id": "rs_" + requestID, "type": "reasoning", "status": "completed", "summary": []any{map[string]any{"type": "summary_text", "text": turn.Reasoning}}}) + } + callIndex := 0 + for _, item := range items { + switch item.Type { + case "message": + content := make([]any, 0, len(item.Content)) + for _, block := range item.Content { + content = append(content, map[string]any{"type": "output_text", "text": block.Text, "annotations": []any{}}) + } + output = append(output, map[string]any{ + "id": "msg_" + requestID, "type": "message", "status": "completed", "role": "assistant", + "content": content, + }) + case "function_call": + output = append(output, proxyToolCallItem(requestID, callIndex, proxyToolCall{ + ID: item.CallID, Name: item.Name, Arguments: item.Arguments, + })) + callIndex++ + } + } + if len(items) == 0 { + output = append(output, map[string]any{ + "id": "msg_" + requestID, "type": "message", "status": "completed", "role": "assistant", + "content": []any{map[string]any{"type": "output_text", "text": "", "annotations": []any{}}}, + }) + } + terminal := responsesTerminalForFinishReason(finishReason) + response := map[string]any{ + "id": "resp_" + requestID, "object": "response", "created_at": time.Now().Unix(), "status": terminal.status, "model": model, + "output": output, + "usage": responsesUsage(promptTokens, completionTokens, cacheReadTokens, cacheWriteTokens, cachedTokens, reasoningTokens), + } + if terminal.incompleteDetails != nil { + response["incomplete_details"] = terminal.incompleteDetails + } + return response, nil +} + func responsesResponse( requestID, model, content, reasoning string, toolCalls []proxyToolCall, diff --git a/internal/gateway/responses_test.go b/internal/gateway/responses_test.go index 2fe8a8d37..327e9cd64 100644 --- a/internal/gateway/responses_test.go +++ b/internal/gateway/responses_test.go @@ -4,13 +4,47 @@ import ( "context" "encoding/json" "errors" + "net/http" "net/http/httptest" "strings" "testing" "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" + applogs "github.com/caigee-cmd/cli2api/internal/logs" ) +func TestUnsupportedResponsesRequestFinishesLogAndReleasesKey(t *testing.T) { + store := &recordingRequestStore{} + recorder := applogs.NewRequestRecorder(store) + t.Cleanup(recorder.Close) + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-only", Provider: "qoder", Region: "global", Models: []string{"mock"}}) + h := &Handler{Executor: executor.NewChatExecutor(pool, ""), Pool: pool, Recorder: recorder, KeyLimits: &KeyInFlight{}} + id := auth.Identity{Kind: auth.KindKey, KeyID: "limited", MaxInFlight: 1} + response := callGateway(h.HandleResponses, "/v1/responses", `{"model":"qoder/mock","stream":true,"input":[{"type":"input_file","file_id":"fixture"}]}`, id) + requestID := response.Header().Get("X-Request-Id") + if response.Code != http.StatusBadRequest || requestID == "" || response.Header().Get("Content-Type") != "application/json" || !strings.Contains(response.Body.String(), `"code":"unsupported_request"`) { + t.Fatalf("unsupported request response: %d %v %s", response.Code, response.Header(), response.Body.String()) + } + if !h.KeyLimits.acquire(id) { + t.Fatal("unsupported request did not release the Key slot") + } + h.KeyLimits.release(id) + recorder.Close() // Wait for queued Start/Finish writes. + if len(store.updates) != 2 { + t.Fatalf("want one Start and one Finish, got %+v", store.updates) + } + started, finished := store.updates[0], store.updates[1] + if started.ID != requestID || started.Status != accounts.RequestStatusStarted || started.APIKeyID != id.KeyID { + t.Fatalf("unexpected Start: %+v", started) + } + if finished.ID != requestID || finished.Status != accounts.RequestStatusError || finished.FinishedAt == nil || finished.ErrorKind != accounts.KindInvalidRequest || finished.ErrorCode != "unsupported_request" || finished.AccountID != "" || finished.AttemptCount != 0 { + t.Fatalf("unexpected Finish: %+v", finished) + } +} + func TestRelayOpenAIStreamDoneSurvivesUsageReplacement(t *testing.T) { body := strings.Join([]string{ `data: {"choices":[{"delta":{"content":"hi"}}]}`, @@ -31,19 +65,19 @@ func TestRelayOpenAIStreamDoneSurvivesUsageReplacement(t *testing.T) { func TestStreamLogStatusKeepsCompletedDisconnectSuccessful(t *testing.T) { disconnect := &StreamRelayWriteError{err: errors.New("client closed")} - if got := streamLogStatus(disconnect, true, true); got != accounts.RequestStatusOK { + if got := streamLogStatus(disconnect, StreamRelayStats{DownstreamDone: true}, true); got != accounts.RequestStatusOK { t.Fatalf("completed disconnect status=%s", got) } - if got := streamLogStatus(context.Canceled, true, false); got != accounts.RequestStatusOK { + if got := streamLogStatus(context.Canceled, StreamRelayStats{DownstreamDone: true}, false); got != accounts.RequestStatusOK { t.Fatalf("completed context cancel status=%s", got) } - if got := streamLogStatus(context.Canceled, false, true); got != accounts.RequestStatusCanceled { + if got := streamLogStatus(context.Canceled, StreamRelayStats{}, true); got != accounts.RequestStatusCanceled { t.Fatalf("mid-stream cancel status=%s", got) } - if got := streamLogStatus(errors.New("upstream reset"), true, false); got != accounts.RequestStatusError { + if got := streamLogStatus(errors.New("upstream reset"), StreamRelayStats{DownstreamDone: true}, false); got != accounts.RequestStatusError { t.Fatalf("upstream failure status=%s", got) } - if got := streamLogStatus(nil, false, false); got != accounts.RequestStatusOK { + if got := streamLogStatus(nil, StreamRelayStats{}, false); got != accounts.RequestStatusOK { t.Fatalf("clean stream status=%s", got) } } @@ -208,23 +242,7 @@ func TestParseStreamUsageLineCacheReadFallback(t *testing.T) { } } -func TestDecodeOpenAIToolCallsNormalizesInvalidArguments(t *testing.T) { - calls := decodeOpenAIToolCalls(json.RawMessage(`[ - {"id":"call_bad","function":{"name":"mcp__fastctx__read","arguments":"{\"path\":\"x\",\"error_retry:: 240}"}}, - {"id":"call_good","function":{"name":"mcp__fastctx__grep","arguments":"{\"pattern\":\"x\"}"}} - ]`)) - if len(calls) != 2 { - t.Fatalf("calls=%#v", calls) - } - if calls[0].ID != "call_bad" || calls[0].Arguments != `{"path":"x"}` { - t.Fatalf("bad call was not normalized: %#v", calls[0]) - } - if calls[1].Arguments != `{"pattern":"x"}` { - t.Fatalf("good call changed: %#v", calls[1]) - } -} - -func TestRelayResponsesStreamNormalizesInvalidToolArguments(t *testing.T) { +func TestRelayResponsesStreamRejectsInvalidToolArguments(t *testing.T) { upstream := strings.NewReader( `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_bad","function":{"name":"mcp__fastctx__read","arguments":"{\"path\":\"x\",\"error_retry:: 240}"}}]}}]}` + "\n\n" + `data: {"choices":[{"finish_reason":"tool_calls"}]}` + "\n\n" + @@ -232,23 +250,20 @@ func TestRelayResponsesStreamNormalizesInvalidToolArguments(t *testing.T) { ) var output strings.Builder stats, err := RelayResponsesStream(&output, upstream, "req", "model", nil) - if err != nil { - t.Fatalf("error=%v", err) + if err == nil { + t.Fatal("expected invalid tool arguments to fail the turn") + } + if stats.DownstreamDone { + t.Fatalf("a failed tool turn must not report downstream success: %+v", stats) } body := output.String() - for _, event := range []string{ - "event: response.function_call_arguments.done", - "event: response.output_item.done", - "event: response.completed", - } { - if !strings.Contains(body, event) { - t.Fatalf("missing %q in:\n%s", event, body) - } + if !strings.Contains(body, "event: error") { + t.Fatalf("missing error event in:\n%s", body) } - if strings.Contains(body, "error_retry") { - t.Fatalf("garbage arguments leaked into the stream:\n%s", body) + if strings.Contains(body, "event: response.completed") { + t.Fatalf("a failed tool turn must not synthesize response.completed:\n%s", body) } - if stats.FinishReason != "tool_calls" { - t.Fatalf("finish reason=%q", stats.FinishReason) + if strings.Contains(body, "error_retry") || strings.Contains(body, `"path"`) { + t.Fatalf("invalid arguments leaked into the stream:\n%s", body) } } diff --git a/internal/gateway/route_lifecycle_test.go b/internal/gateway/route_lifecycle_test.go new file mode 100644 index 000000000..214022e04 --- /dev/null +++ b/internal/gateway/route_lifecycle_test.go @@ -0,0 +1,803 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type nativeRouteAdapter func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) + +func (f nativeRouteAdapter) ResponsesStream(_ context.Context, accountID string, req *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + return f(accountID, req, options) +} + +type observedStreamBody struct { + io.Reader + closed bool +} + +func (b *observedStreamBody) Close() error { + b.closed = true + return nil +} + +type unexpectedEOFReader struct{ read bool } + +func (r *unexpectedEOFReader) Read([]byte) (int, error) { + r.read = true + return 0, io.ErrUnexpectedEOF +} + +func TestNativeResponsesStreamIgnoresReadErrorAfterTerminal(t *testing.T) { + for _, status := range []string{"completed", "incomplete"} { + t.Run(status, func(t *testing.T) { + const accountID, model = "codex-pool", "model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: accountID, Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{model}, MaxInFlight: 1}) + terminalType := "response." + status + terminal := fmt.Sprintf("event: %s\ndata: %s\n\n", terminalType, fmt.Sprintf(`{"type":%q,"response":{"status":%q,"output":[]}}`, terminalType, status)) + tail := &unexpectedEOFReader{} + body := &observedStreamBody{Reader: io.MultiReader(strings.NewReader(terminal), tail)} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: body}, providers.ResolvedChat{}, nil + })}) + var attempts []accounts.RequestAttempt + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + h := &Handler{Executor: ex, Pool: pool} + resp := callGateway(h.HandleResponses, "/v1/responses", `{"model":"codex/model","stream":true,"input":"hi"}`, auth.Identity{}) + if resp.Code != http.StatusOK || resp.Body.String() != terminal || tail.read || !body.closed { + t.Fatalf("terminal relay: status=%d readTail=%v closed=%v body=%s", resp.Code, tail.read, body.closed, resp.Body.String()) + } + if len(attempts) != 1 || attempts[0].AccountID != accountID || attempts[0].Status != accounts.AttemptStatusOK || attempts[0].ErrorKind != "" { + t.Fatalf("successful terminal must not produce failure feedback: %+v", attempts) + } + item, _ := pool.ByID(accountID) + if item.InFlight != 0 || !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 || item.LastKind != "" { + t.Fatalf("successful terminal affected account health or leaked slot: %+v", item) + } + }) + } +} + +func TestAggregatedNativeResponsesTerminalFailureUsesActualModel(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + const accountID, firstModel, secondModel, logicalModel = "codex-pool", "primary-model", "alternate-model", "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: accountID, Provider: "codex", Region: "global", Runtime: "in_process", + Models: []string{firstModel, secondModel}, NativeModels: map[string]string{firstModel: "provider-primary"}, MaxInFlight: 1}) + var models, quotaRefresh []string + var attempts []accounts.RequestAttempt + var body *observedStreamBody + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(id string, req *translate.NativeResponsesRequest, opts providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + if id != accountID || !strings.Contains(string(req.Fields()["input"]), `"input_file"`) { + t.Fatalf("native dispatch did not preserve input or account: %q %s", id, req.Fields()["input"]) + } + models = append(models, opts.Model) + source := "event: response.created\ndata: {\"type\":\"response.created\",\"response\":{\"status\":\"in_progress\"}}\n\n" + if opts.Model == "provider-primary" { + source += "event: error\ndata: {\"type\":\"error\",\"code\":\"rate_limit_exceeded\",\"message\":\"slow down\"}\n\n" + } else { + source += "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ok\",\"status\":\"completed\",\"output\":[]}}\n\n" + } + body = &observedStreamBody{Reader: strings.NewReader(source)} + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: body}, providers.ResolvedChat{}, nil + })}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + ex.OnAttempt = func(a accounts.RequestAttempt) { + item, ok := pool.ByID(accountID) + if !ok || item.InFlight != 1 { + t.Errorf("attempt feedback must precede account slot release: %+v", item) + } + attempts = append(attempts, a) + } + h := &Handler{Executor: ex, Pool: pool, KeyLimits: &KeyInFlight{}, + Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + return accounts.Aggregation{ID: id, Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 1, + Members: []accounts.AggregationMember{ + {Provider: "codex", Region: "global", Model: firstModel, Priority: 1, Weight: 1}, + {Provider: "codex", Region: "global", Model: secondModel, Priority: 2, Weight: 1}, + }}, nil + }), + AfterAccountUse: func(id, model string, aggregateFEFO bool) { + if body == nil || !body.closed { + t.Error("quota invalidation ran before stream body closed") + } + quotaRefresh = append(quotaRefresh, id+":"+model) + }, + } + identity := auth.Identity{Kind: auth.KindKey, KeyID: "limited", MaxInFlight: 1, ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + input := fmt.Sprintf(`{"model":%q,"stream":%t,"input":[{"type":"input_file","file_id":"fixture"}]}`, logicalModel, stream) + first := callGateway(h.HandleResponses, "/v1/responses", input, identity) + if stream { + if first.Code != http.StatusOK || strings.Count(first.Body.String(), "event: error\n") != 1 { + t.Fatalf("stream must forward one upstream error: %d %s", first.Code, first.Body.String()) + } + } else if first.Code != http.StatusTooManyRequests || !strings.Contains(first.Body.String(), "rate_limit_exceeded") { + t.Fatalf("collecting response should report upstream limit: %d %s", first.Code, first.Body.String()) + } + item, ok := pool.ByID(accountID) + if !ok || item.InFlight != 0 || !item.DownUntil.IsZero() || !item.ModelDownUntil[firstModel].After(time.Now()) || len(item.ModelDownUntil) != 1 { + t.Fatalf("wrong cooldown target or slot state: %+v", item) + } + second := callGateway(h.HandleResponses, "/v1/responses", input, identity) + if second.Code != http.StatusOK || !strings.Contains(second.Body.String(), "resp_ok") { + t.Fatalf("alternate member on same account should remain available: %d %s", second.Code, second.Body.String()) + } + if !reflect.DeepEqual(models, []string{"provider-primary", secondModel}) || !reflect.DeepEqual(quotaRefresh, []string{accountID + ":" + firstModel, accountID + ":" + secondModel}) { + t.Fatalf("dispatched models=%v; quota targets=%v", models, quotaRefresh) + } + if len(attempts) != 2 || attempts[0].Status != accounts.AttemptStatusError || attempts[0].ErrorKind != accounts.KindRateLimit || attempts[1].Status != accounts.AttemptStatusOK { + t.Fatalf("want one terminal record per dispatched attempt; got %+v", attempts) + } + }) + } +} + +func TestWorkerStreamRateLimitUsesPoolAccountNotDisplayLabel(t *testing.T) { + const poolID, displayID, actualModel = "worker-pool", "worker-display", "actual-model" + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("X-Qoder-Account", displayID) + _, _ = io.WriteString(w, "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n"+ + "event: error\ndata: {\"error\":{\"code\":\"rate_limit_exceeded\",\"message\":\"slow down\"}}\n\n") + })) + defer worker.Close() + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: poolID, URL: worker.URL, Provider: "qoder", Region: "global", Runtime: "child_process", + Models: []string{actualModel}, ModelAliases: map[string]string{"alias": actualModel}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: displayID, URL: worker.URL, Provider: "qoder", Region: "global", Runtime: "child_process", Models: []string{actualModel}}) + ex := executor.NewChatExecutor(pool, "") + ex.HTTPClient = worker.Client() + var quotaRefresh []string + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + h := &Handler{Executor: ex, Pool: pool, RequestedAccount: func(*http.Request) string { return poolID }, + AfterAccountUse: func(id, model string, aggregateFEFO bool) { quotaRefresh = append(quotaRefresh, id+":"+model) }} + id := auth.Identity{Kind: auth.KindKey, KeyID: "limited"} + response := callGateway(h.HandleResponses, "/v1/responses", `{"model":"qoder/alias","stream":true,"input":"hello"}`, id) + if response.Code != http.StatusOK || response.Header().Get("X-CLI2API-Account") != displayID || strings.Count(response.Body.String(), "event: error\n") != 1 { + t.Fatalf("public stream label or error changed: %d %v %s", response.Code, response.Header(), response.Body.String()) + } + actual, _ := pool.ByID(poolID) + display, _ := pool.ByID(displayID) + if !actual.ModelDownUntil[actualModel].After(time.Now()) || !actual.DownUntil.IsZero() || actual.InFlight != 0 || len(display.ModelDownUntil) != 0 || !display.DownUntil.IsZero() { + t.Fatalf("wrong feedback: actual=%+v display=%+v", actual, display) + } + if !reflect.DeepEqual(quotaRefresh, []string{poolID + ":" + actualModel}) { + t.Fatalf("quota invalidation targeted %v", quotaRefresh) + } + if len(attempts) != 1 || attempts[0].AccountID != poolID || attempts[0].ErrorKind != accounts.KindRateLimit || attempts[0].Status != accounts.AttemptStatusError { + t.Fatalf("unexpected attempt records: %+v", attempts) + } +} + +type disconnectedStreamWriter struct { + *httptest.ResponseRecorder +} + +func (w *disconnectedStreamWriter) Write([]byte) (int, error) { return 0, io.ErrClosedPipe } + +func TestAnthropicStreamClientDisconnectDoesNotCoolAccount(t *testing.T) { + const poolID, model = "worker-pool", "routed-model" + worker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, `data: {"choices":[{"delta":{"content":"hi"}}]}`+"\n\ndata: [DONE]\n\n") + })) + defer worker.Close() + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: poolID, URL: worker.URL, Provider: "qoder", Region: "global", Runtime: "child_process", + Models: []string{model}, MaxInFlight: 1}) + ex := executor.NewChatExecutor(pool, "") + ex.HTTPClient = worker.Client() + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + h := &Handler{Executor: ex, Pool: pool, KeyLimits: &KeyInFlight{}} + id := auth.Identity{Kind: auth.KindKey, KeyID: "limited", MaxInFlight: 1} + r := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"qoder/routed-model","stream":true,"messages":[{"role":"user","content":"hello"}],"max_tokens":16}`)) + h.HandleAnthropicMessages(&disconnectedStreamWriter{httptest.NewRecorder()}, r.WithContext(auth.WithIdentity(r.Context(), id))) + if len(attempts) != 1 || attempts[0].AccountID != poolID || attempts[0].ErrorKind != accounts.KindCanceled { + t.Fatalf("downstream disconnect should record cancellation once: %+v", attempts) + } + item, _ := pool.ByID(poolID) + if item.InFlight != 0 || !item.DownUntil.IsZero() || item.LastKind != "" || len(item.ModelDownUntil) != 0 { + t.Fatalf("downstream disconnect affected account health or leaked the account slot: %+v", item) + } + if !h.KeyLimits.acquire(id) { + t.Fatal("Key slot leaked on downstream disconnect") + } + h.KeyLimits.release(id) +} + +// cancellationStreamTail can finish the request independently of the read +// result an adapter exposes. No network scheduling is needed to exercise that ordering. +type cancellationStreamTail struct { + reader io.Reader + terminal error + beforeRead func() +} + +func (r cancellationStreamTail) Read(p []byte) (int, error) { + if r.beforeRead != nil { + r.beforeRead() + } + if r.reader != nil { + return r.reader.Read(p) + } + return 0, r.terminal +} + +func TestDispatchCancellationKeepsAccountFeedbackAccurate(t *testing.T) { + nl := string(rune(10)) + frame := func(event, data string) string { return "event: " + event + nl + "data: " + data + nl + nl } + nativeStart := frame("response.created", `{"type":"response.created"}`) + nativeDone := frame("response.completed", `{"type":"response.completed","response":{"status":"completed","output":[]}}`) + rateLimit := frame("error", `{"type":"error","error":{"status":429,"code":"rate_limit_exceeded","message":"slow down","retry_after":79,"failover":false}}`) + unavailable := frame("error", `{"type":"error","error":{"status":503,"code":"temporarily_unavailable","message":"try again later","failover":false}}`) + + for _, mode := range []struct { + name, path, request, provider, successMarker string + handler func(*Handler, http.ResponseWriter, *http.Request) + }{ + {"chat", "/v1/chat/completions", `{"model":"qoder/model","stream":true,"messages":[{"role":"user","content":"hello"}]}`, "qoder", "data: [DONE]", (*Handler).HandleChatCompletions}, + {"messages", "/v1/messages", `{"model":"qoder/model","stream":true,"max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`, "qoder", "event: message_stop", (*Handler).HandleAnthropicMessages}, + {"compat-responses", "/v1/responses", `{"model":"qoder/model","stream":true,"input":"hello"}`, "qoder", "event: response.completed", (*Handler).HandleResponses}, + {"native-responses", "/v1/responses", `{"model":"codex/model","stream":true,"input":"hello"}`, "codex", "event: response.completed", (*Handler).HandleResponses}, + {"native-collect", "/v1/responses", `{"model":"codex/model","stream":false,"input":"hello"}`, "codex", `"status":"completed"`, (*Handler).HandleResponses}, + } { + start, terminal := chatStreamText, chatStreamDone + if mode.provider == "codex" { + start, terminal = nativeStart, nativeDone + } + for _, tc := range []struct { + name, first, tail string + err error + cancel bool + wantKind string + }{ + {name: "cancel-before-first-frame", err: io.EOF, cancel: true, wantKind: accounts.KindCanceled}, + {name: "cancel-at-eof", first: start, err: io.EOF, cancel: true, wantKind: accounts.KindCanceled}, + {name: "cancel-at-read-error", first: start, err: io.ErrUnexpectedEOF, cancel: true, wantKind: accounts.KindCanceled}, + {name: "cancel-with-sentinel", first: start, err: context.Canceled, cancel: true, wantKind: accounts.KindCanceled}, + {name: "eof-while-live", first: start, err: io.EOF, wantKind: accounts.KindUnavailable}, + {name: "read-error-while-live", first: start, err: io.ErrUnexpectedEOF, wantKind: accounts.KindUnavailable}, + {name: "complete-as-client-leaves", first: start, tail: terminal, cancel: true}, + {name: "provider-rate-limit-as-client-leaves", first: start, tail: rateLimit, cancel: true, wantKind: accounts.KindRateLimit}, + {name: "provider-rate-limit-before-first-frame", tail: rateLimit, cancel: true, wantKind: accounts.KindRateLimit}, + {name: "provider-unavailable-as-client-leaves", first: start, tail: unavailable, cancel: true, wantKind: accounts.KindUnavailable}, + {name: "provider-unavailable-before-first-frame", tail: unavailable, cancel: true, wantKind: accounts.KindUnavailable}, + } { + t.Run(mode.name+"/"+tc.name, func(t *testing.T) { + const accountID, backupID, model = "synthetic-pool", "synthetic-backup", "model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: accountID, Provider: mode.provider, Region: "global", Runtime: "in_process", Models: []string{model}, MaxInFlight: 1}) + // Canceled cases must not dispatch a second attempt even when a backup is ready. + // Live transport failures exercise account feedback without retrying this fixture body. + if tc.cancel { + pool.Upsert(executor.Item{ID: backupID, Provider: mode.provider, Region: "global", Runtime: "in_process", Models: []string{model}, MaxInFlight: 1}) + } + identity := auth.Identity{Kind: auth.KindKey, KeyID: "synthetic-cancel", MaxInFlight: 1} + ctx, cancel := context.WithCancel(auth.WithIdentity(t.Context(), identity)) + defer cancel() + + tail := cancellationStreamTail{terminal: tc.err} + if tc.tail != "" { + tail.reader = strings.NewReader(tc.tail) + } + if tc.cancel { + tail.beforeRead = cancel + } + body := &observedStreamBody{Reader: io.MultiReader(strings.NewReader(tc.first), tail)} + response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: body} + registry := providers.NewRegistry() + if mode.provider == "codex" { + registry.Register(providers.Adapter{ID: mode.provider, NativeResponses: nativeRouteAdapter(func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + return response, providers.ResolvedChat{}, nil + })}) + } else { + registry.Register(providers.Adapter{ID: mode.provider, Chat: streamRouteTestAdapter(func(context.Context, string, translate.ChatRequest) (*http.Response, error) { return response, nil })}) + } + var attempts []accounts.RequestAttempt + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + handler := &Handler{Executor: ex, Pool: pool, KeyLimits: &KeyInFlight{}, RequestedAccount: func(*http.Request) string { return accountID }} + r := httptest.NewRequestWithContext(ctx, http.MethodPost, mode.path, strings.NewReader(mode.request)) + w := httptest.NewRecorder() + func() { + defer func() { + if caught := recover(); caught != nil && caught != http.ErrAbortHandler { + panic(caught) + } + }() + mode.handler(handler, w, r) + }() + + item, ok := pool.ByID(accountID) + if !ok || item.InFlight != 0 || !body.closed || (ctx.Err() != nil) != tc.cancel { + t.Fatalf("unexpected release or cancellation: item=%+v bodyClosed=%t ctxErr=%v", item, body.closed, ctx.Err()) + } + if !handler.KeyLimits.acquire(identity) { + t.Fatal("Key slot not released") + } + handler.KeyLimits.release(identity) + wantStatus := accounts.AttemptStatusError + if tc.wantKind == "" { + wantStatus = accounts.AttemptStatusOK + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), mode.successMarker) { + t.Errorf("confirmed terminal success not relayed: %d %s", w.Code, w.Body.String()) + } + } + if len(attempts) != 1 || attempts[0].AccountID != accountID || attempts[0].Status != wantStatus || attempts[0].ErrorKind != tc.wantKind { + t.Errorf("expected one %s/%s attempt, got %+v", wantStatus, tc.wantKind, attempts) + } + switch tc.wantKind { + case accounts.KindUnavailable: + if item.LastKind != accounts.KindUnavailable || !item.DownUntil.After(time.Now()) { + t.Errorf("actual truncation did not cool the account: %+v", item) + } + case accounts.KindRateLimit: + if !item.ModelDownUntil[model].After(time.Now().Add(time.Minute)) || !item.DownUntil.IsZero() { + t.Errorf("confirmed limit or retry hint lost: %+v", item) + } + default: + if item.LastKind != "" || !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 { + t.Errorf("success/cancellation affected account health: %+v", item) + } + } + if tc.first == "" || mode.name == "native-collect" { + switch tc.wantKind { + case accounts.KindCanceled: + if w.Code != 499 || (mode.name != "messages" && !strings.Contains(w.Body.String(), "request_canceled")) { + t.Errorf("canceled dispatch returned %d: %s", w.Code, w.Body.String()) + } + case accounts.KindRateLimit: + if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") != "79" { + t.Errorf("rate-limited dispatch returned %d %v: %s", w.Code, w.Header(), w.Body.String()) + } + case accounts.KindUnavailable: + if tc.tail == unavailable && w.Code != http.StatusServiceUnavailable { + t.Errorf("confirmed 503 returned %d: %s", w.Code, w.Body.String()) + } + } + } + }) + } + } +} + +func TestNamedAggregationResponsesUsesSelectedMemberProtocol(t *testing.T) { + for _, tc := range []struct { + name string + stream bool + nativeFirst bool + }{ + {name: "chat-selected-stream", stream: true}, + {name: "chat-selected-nonstream"}, + {name: "native-selected-stream", stream: true, nativeFirst: true}, + {name: "native-selected-nonstream", nativeFirst: true}, + } { + t.Run(tc.name, func(t *testing.T) { + const logicalModel = "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-account", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"chat-model"}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: "native-account", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"native-model"}, MaxInFlight: 1}) + + chat := &namedAggregationResponsesChat{} + var nativeAccounts, nativeInputs, nativeMetadata, nativeModels []string + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(accountID string, req *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + nativeAccounts = append(nativeAccounts, accountID) + nativeInputs = append(nativeInputs, string(req.Fields()["input"])) + nativeMetadata = append(nativeMetadata, string(req.Fields()["metadata"])) + nativeModels = append(nativeModels, options.Model) + data := fmt.Sprintf(`{"type":"response.completed","response":{"id":"native-response","status":"completed","model":%q,"output":[{"type":"message","content":[{"type":"output_text","text":"native-answer"}]}]}}`, options.Model) + body := strings.Join([]string{"event: response.completed", "data: " + data, "", ""}, string(rune(10))) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + + chatPriority, nativePriority := 0, 1 + if tc.nativeFirst { + chatPriority, nativePriority = 1, 0 + } + aggregation := accounts.Aggregation{ID: logicalModel, Enabled: true, Strategy: accounts.AggregationPriority, MaxAttempts: 1, Members: []accounts.AggregationMember{ + {Provider: "workbuddy", Region: "global", Model: "chat-model", Priority: chatPriority}, + {Provider: "codex", Region: "global", Model: "native-model", Priority: nativePriority}, + }} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool, Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + if id != logicalModel { + t.Fatalf("aggregation id = %q", id) + } + return aggregation, nil + })} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "native-order", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + input := fmt.Sprintf(`{"model":%q,"stream":%t,"input":"hello","metadata":{"fixture":"keep-me"}}`, logicalModel, tc.stream) + response := callGateway(h.HandleResponses, "/v1/responses", input, identity) + if response.Code != http.StatusOK { + t.Fatalf("Responses status=%d body=%s", response.Code, response.Body.String()) + } + if tc.nativeFirst { + if !reflect.DeepEqual(nativeAccounts, []string{"native-account"}) || !reflect.DeepEqual(nativeModels, []string{"native-model"}) || !strings.Contains(nativeInputs[0], "hello") || !strings.Contains(nativeMetadata[0], "keep-me") { + t.Fatalf("selected native route lost target or raw fields: accounts=%v models=%v inputs=%v metadata=%v", nativeAccounts, nativeModels, nativeInputs, nativeMetadata) + } + if len(chat.streamCalls)+len(chat.nonStreamCalls) != 0 || !strings.Contains(response.Body.String(), "native-answer") { + t.Fatalf("native-selected response used compat path: chat=%+v body=%s", chat, response.Body.String()) + } + } else { + gotCalls := len(chat.streamCalls) + if !tc.stream { + gotCalls = len(chat.nonStreamCalls) + } + if len(nativeAccounts) != 0 || gotCalls != 1 || !strings.Contains(response.Body.String(), "compat-answer") { + t.Fatalf("selected Chat member was bypassed: native=%v chat=%+v body=%s", nativeAccounts, chat, response.Body.String()) + } + } + for _, id := range []string{"chat-account", "native-account"} { + item, ok := pool.ByID(id) + if !ok || item.InFlight != 0 { + t.Fatalf("account slot not released for %s: %+v", id, item) + } + } + }) + } +} + +type namedAggregationResponsesChat struct { + streamCalls []string + nonStreamCalls []string + nonStreamErr error +} + +func (c *namedAggregationResponsesChat) ChatNonStream(_ context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + c.nonStreamCalls = append(c.nonStreamCalls, accountID+":"+req.Model) + if c.nonStreamErr != nil { + return providers.ChatOutcome{}, c.nonStreamErr + } + return providers.ChatOutcome{Model: req.Model, Content: "compat-answer", FinishReason: "stop", PromptTokens: 1, CompletionTokens: 1}, nil +} + +func (c *namedAggregationResponsesChat) ChatStream(_ context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + c.streamCalls = append(c.streamCalls, accountID+":"+req.Model) + body := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"compat-answer"}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`, + "data: [DONE]", + }, string(rune(10))+string(rune(10))) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil +} + +func TestNamedAggregationNativeToolFailureDoesNotFallback(t *testing.T) { + const logicalModel = "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-account", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"chat-model"}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: "native-account", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"native-model"}, MaxInFlight: 1}) + + chat := &namedAggregationResponsesChat{} + var nativeAccounts []string + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(accountID string, req *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + nativeAccounts = append(nativeAccounts, accountID) + frames := []string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"native-response","status":"completed","output":[{"type":"function_call","id":"fc_1","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(strings.Join(frames, "\n"))), + }, providers.ResolvedChat{}, nil + })}) + + aggregation := accounts.Aggregation{ID: logicalModel, Enabled: true, Strategy: accounts.AggregationPriority, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "codex", Region: "global", Model: "native-model", Priority: 0}, + {Provider: "workbuddy", Region: "global", Model: "chat-model", Priority: 1}, + }} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool, Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + return aggregation, nil + })} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "native-tool-failure", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + input := fmt.Sprintf(`{"model":%q,"stream":true,"input":"hello","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]}`, logicalModel) + response := callGateway(h.HandleResponses, "/v1/responses", input, identity) + if response.Code != http.StatusOK { + t.Fatalf("Responses status=%d body=%s", response.Code, response.Body.String()) + } + if !reflect.DeepEqual(nativeAccounts, []string{"native-account"}) { + t.Fatalf("native member calls=%v", nativeAccounts) + } + if len(chat.streamCalls)+len(chat.nonStreamCalls) != 0 { + t.Fatalf("tool validation failure fell back to another member: chat=%+v", chat) + } + body := response.Body.String() + if !strings.Contains(body, "event: error") || strings.Contains(body, "response.completed") { + t.Fatalf("native failure was not a single sanitized terminal: %s", body) + } + for _, id := range []string{"chat-account", "native-account"} { + item, ok := pool.ByID(id) + if !ok || item.InFlight != 0 { + t.Fatalf("account slot not released for %s: %+v", id, item) + } + } +} + +func TestNamedAggregationResponsesCompatMemberValidatesTools(t *testing.T) { + const logicalModel = "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-account", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"chat-model"}, MaxInFlight: 1}) + chat := &toolResponsesChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + aggregation := accounts.Aggregation{ID: logicalModel, Enabled: true, Strategy: accounts.AggregationPriority, MaxAttempts: 1, Members: []accounts.AggregationMember{ + {Provider: "workbuddy", Region: "global", Model: "chat-model", Priority: 0}, + }} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool, Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + if id != logicalModel { + t.Fatalf("aggregation id = %q", id) + } + return aggregation, nil + })} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "compat-tools", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + input := `{"model":"logical-model","input":"hello","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"required"}` + response := callGateway(h.HandleResponses, "/v1/responses", input, identity) + if response.Code != http.StatusOK { + t.Fatalf("compat Responses tool status=%d body=%s", response.Code, response.Body.String()) + } + if len(chat.nonStreamCalls) != 1 { + t.Fatalf("compat member calls=%+v", chat) + } + body := response.Body.String() + if !strings.Contains(body, `"type":"function_call"`) || !strings.Contains(body, `"name":"read_file"`) || !strings.Contains(body, `"call_id":"call_1"`) { + t.Fatalf("compat Responses tool output missing: %s", body) + } + if !strings.Contains(body, `"arguments":"{\"path\":\"README.md\"}"`) { + t.Fatalf("compat Responses tool arguments missing: %s", body) + } +} + +type toolResponsesChat struct { + nonStreamCalls []string +} + +func (c *toolResponsesChat) ChatNonStream(_ context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + c.nonStreamCalls = append(c.nonStreamCalls, accountID+":"+req.Model) + if len(req.Tools) == 0 || string(req.ToolChoice) != `"required"` { + return providers.ChatOutcome{}, fmt.Errorf("tool contract was lost before the Chat member: tools=%s choice=%s", req.Tools, req.ToolChoice) + } + return providers.ChatOutcome{ + Model: req.Model, FinishReason: "tool_calls", + ToolCalls: json.RawMessage(`[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\"}"}}]`), + }, nil +} + +func (c *toolResponsesChat) ChatStream(_ context.Context, accountID string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, fmt.Errorf("unexpected stream for non-stream request") +} + +func TestNamedAggregationIncompatibleResponsesKeepsNativeHardFilterAndBudget(t *testing.T) { + const logicalModel = "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-account", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"chat-model"}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: "native-a", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"native-a-model"}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: "native-b", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"native-b-model"}, MaxInFlight: 1}) + chat := &namedAggregationResponsesChat{} + var nativeAccounts, nativeModels, nativeInputs []string + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(accountID string, req *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + nativeAccounts = append(nativeAccounts, accountID) + nativeModels = append(nativeModels, options.Model) + nativeInputs = append(nativeInputs, string(req.Fields()["input"])) + var body string + if accountID == "native-a" { + body = strings.Join([]string{ + "event: response.failed", + `data: {"type":"response.failed","response":{"status":"failed","error":{"status_code":429,"code":"rate_limit_exceeded","message":"limited"}}}`, + "", + "", + }, string(rune(10))) + } else { + body = strings.Join([]string{ + "event: response.completed", + `data: {"type":"response.completed","response":{"id":"native-ok","status":"completed","model":"native-b-model","output":[]}}`, + "", + "", + }, string(rune(10))) + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + aggregation := accounts.Aggregation{ID: logicalModel, Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "workbuddy", Region: "global", Model: "chat-model", Priority: 0}, + {Provider: "codex", Region: "global", Model: "native-a-model", Priority: 1}, + {Provider: "codex", Region: "global", Model: "native-b-model", Priority: 2}, + }} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(attempt accounts.RequestAttempt) { attempts = append(attempts, attempt) } + h := &Handler{Executor: ex, Pool: pool, Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + if id != logicalModel { + t.Fatalf("aggregation id = %q", id) + } + return aggregation, nil + })} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "native-only", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + response := callGateway(h.HandleResponses, "/v1/responses", `{"model":"logical-model","input":[{"type":"input_file","file_id":"fixture"}]}`, identity) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "native-ok") { + t.Fatalf("incompatible response=%d %s", response.Code, response.Body.String()) + } + if !reflect.DeepEqual(nativeAccounts, []string{"native-a", "native-b"}) || !reflect.DeepEqual(nativeModels, []string{"native-a-model", "native-b-model"}) { + t.Fatalf("native failover targets=%v models=%v", nativeAccounts, nativeModels) + } + if !strings.Contains(nativeInputs[0], "input_file") || len(chat.streamCalls)+len(chat.nonStreamCalls) != 0 { + t.Fatalf("incompatible request lost raw fields or downgraded: inputs=%v chat=%+v", nativeInputs, chat) + } + if len(attempts) != 2 || attempts[0].AccountID != "native-a" || attempts[0].ErrorKind != accounts.KindRateLimit || attempts[1].AccountID != "native-b" || attempts[1].Status != accounts.AttemptStatusOK { + t.Fatalf("native failover did not preserve one shared attempt budget: %+v", attempts) + } + first, _ := pool.ByID("native-a") + if first.InFlight != 0 || !first.ModelDownUntil["native-a-model"].After(time.Now()) { + t.Fatalf("native rate-limit feedback or slot state incorrect: %+v", first) + } + for _, id := range []string{"chat-account", "native-b"} { + item, ok := pool.ByID(id) + if !ok || item.InFlight != 0 || !item.DownUntil.IsZero() { + t.Fatalf("slot/health unexpectedly changed for %s: %+v", id, item) + } + } +} + +func TestNamedAggregationCompatibleResponsesSharesAttemptBudget(t *testing.T) { + const logicalModel = "logical-model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "chat-account", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"chat-model"}, MaxInFlight: 1}) + pool.Upsert(executor.Item{ID: "native-account", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"native-model"}, MaxInFlight: 1}) + chat := &namedAggregationResponsesChat{nonStreamErr: &providers.Error{Kind: accounts.KindRateLimit, Status: http.StatusTooManyRequests, Code: "rate_limit_exceeded", Message: "busy"}} + var nativeAccounts []string + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(accountID string, req *translate.NativeResponsesRequest, options providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + nativeAccounts = append(nativeAccounts, accountID) + if !strings.Contains(string(req.Fields()["input"]), "hello") || options.Model != "native-model" { + t.Errorf("native failover lost request or target: input=%s model=%s", req.Fields()["input"], options.Model) + } + body := strings.Join([]string{ + "event: response.completed", + `data: {"type":"response.completed","response":{"id":"native-after-chat","status":"completed","model":"native-model","output":[]}}`, + "", + "", + }, string(rune(10))) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + aggregation := accounts.Aggregation{ID: logicalModel, Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: true, MaxAttempts: 2, Members: []accounts.AggregationMember{ + {Provider: "workbuddy", Region: "global", Model: "chat-model", Priority: 0}, + {Provider: "codex", Region: "global", Model: "native-model", Priority: 1}, + }} + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(attempt accounts.RequestAttempt) { attempts = append(attempts, attempt) } + h := &Handler{Executor: ex, Pool: pool, Aggregations: testAggregationResolver(func(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + if id != logicalModel { + t.Fatalf("aggregation id = %q", id) + } + return aggregation, nil + })} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "compatible-failover", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + response := callGateway(h.HandleResponses, "/v1/responses", `{"model":"logical-model","input":"hello"}`, identity) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "native-after-chat") { + t.Fatalf("compatible failover response=%d %s", response.Code, response.Body.String()) + } + if !reflect.DeepEqual(chat.nonStreamCalls, []string{"chat-account:chat-model"}) || len(chat.streamCalls) != 0 || !reflect.DeepEqual(nativeAccounts, []string{"native-account"}) { + t.Fatalf("selected Chat failure did not share group failover: chat=%+v native=%v", chat, nativeAccounts) + } + if len(attempts) != 2 || attempts[0].AttemptIndex != 0 || attempts[0].AccountID != "chat-account" || attempts[0].Status != accounts.AttemptStatusFailover || attempts[0].ErrorKind != accounts.KindRateLimit || attempts[1].AttemptIndex != 1 || attempts[1].AccountID != "native-account" || attempts[1].Status != accounts.AttemptStatusOK { + t.Fatalf("attempt budget/target sequence = %+v", attempts) + } + for _, id := range []string{"chat-account", "native-account"} { + item, ok := pool.ByID(id) + if !ok || item.InFlight != 0 { + t.Fatalf("slot not released for %s: %+v", id, item) + } + } +} + +func TestNativeResponsesTwoRoundToolTurn(t *testing.T) { + const accountID, model = "codex-two-round", "model" + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: accountID, Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{model}, MaxInFlight: 1}) + var inputs []string + fake := nativeRouteAdapter(func(_ string, req *translate.NativeResponsesRequest, _ providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + input := string(req.Fields()["input"]) + inputs = append(inputs, input) + if strings.Contains(input, `"function_call_output"`) { + body := "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_2\",\"status\":\"completed\",\"output\":[{\"type\":\"message\",\"content\":[{\"type\":\"output_text\",\"text\":\"done\"}]}]}}\n\n" + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + } + body := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}`, + ``, + }, "\n") + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + }) + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: fake}) + var attempts []accounts.RequestAttempt + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "two-round", AllowedProviders: []string{"codex"}} + tools := `,"tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]` + firstBody := `{"model":"codex/model","stream":true,"input":"hi"` + tools + `}` + first := callGateway(h.HandleResponses, "/v1/responses", firstBody, identity) + if first.Code != http.StatusOK { + t.Fatalf("first status=%d body=%s", first.Code, first.Body.String()) + } + var callID string + for _, frame := range parseClientSSE(first.Body.String()) { + var event struct { + Item struct { + CallID string `json:"call_id"` + } `json:"item"` + } + if json.Unmarshal([]byte(frame.Data), &event) == nil && event.Item.CallID != "" { + callID = event.Item.CallID + } + } + if callID == "" { + t.Fatalf("first round delivered no call id: %s", first.Body.String()) + } + secondInput := fmt.Sprintf(`[{"role":"user","content":"hi"},{"type":"function_call_output","call_id":%q,"output":"ok"}]`, callID) + secondBody := `{"model":"codex/model","stream":true,"input":` + secondInput + tools + `}` + second := callGateway(h.HandleResponses, "/v1/responses", secondBody, identity) + if second.Code != http.StatusOK { + t.Fatalf("second status=%d body=%s", second.Code, second.Body.String()) + } + if !strings.Contains(second.Body.String(), "response.completed") || !strings.Contains(second.Body.String(), "done") { + t.Fatalf("second round did not complete: %s", second.Body.String()) + } + if len(inputs) != 2 || !strings.Contains(inputs[0], "hi") || !strings.Contains(inputs[1], callID) || !strings.Contains(inputs[1], "function_call_output") { + t.Fatalf("adapter inputs=%q", inputs) + } + if len(attempts) != 2 || attempts[0].Status != accounts.AttemptStatusOK || attempts[1].Status != accounts.AttemptStatusOK { + t.Fatalf("attempts=%+v", attempts) + } + item, _ := pool.ByID(accountID) + if item.InFlight != 0 { + t.Fatalf("slot leaked after two rounds: %+v", item) + } +} diff --git a/internal/gateway/session_context.go b/internal/gateway/session_context.go index a064932f8..fca30e546 100644 --- a/internal/gateway/session_context.go +++ b/internal/gateway/session_context.go @@ -4,11 +4,16 @@ import ( "bytes" "context" "encoding/json" + "errors" "io" "net/http" "strings" ) +// ErrMultipleJSONValues rejects a body that carries more than one top-level +// JSON value. Handlers must not silently drop a trailing object. +var ErrMultipleJSONValues = errors.New("request body must contain exactly one JSON value") + type conversationContextKey struct{} // WithConversationID records a client-supplied conversation/session id found @@ -105,15 +110,30 @@ func cleanID(value string) string { // handlers can both decode JSON and derive the conversation id. It is only used // for the request body, never the upstream response stream. // -// Decoding goes through json.Decoder, not json.Unmarshal, so a truncated body -// such as "{" reports "unexpected EOF" — the same error json.Decoder.Decode -// produced before the body was buffered for conversation-id extraction. +// The body must contain exactly one JSON value followed by EOF. A decoder that +// stops after the first object would accept `{"a":1}{"b":2}` and ignore the +// trailing value; a client typo must be a 400, not a silently different request. func readConversationBody(reader io.Reader, limit int64) ([]byte, error) { var buf bytes.Buffer - dec := json.NewDecoder(io.TeeReader(io.LimitReader(reader, limit), &buf)) + limited := io.LimitReader(reader, limit+1) + dec := json.NewDecoder(io.TeeReader(limited, &buf)) var raw json.RawMessage if err := dec.Decode(&raw); err != nil { + if int64(buf.Len()) > limit { + return nil, &http.MaxBytesError{Limit: limit} + } return nil, err } + var trailing json.RawMessage + if err := dec.Decode(&trailing); err != nil { + if !errors.Is(err, io.EOF) { + return nil, err + } + } else { + return nil, ErrMultipleJSONValues + } + if int64(buf.Len()) > limit { + return nil, &http.MaxBytesError{Limit: limit} + } return buf.Bytes(), nil } diff --git a/internal/gateway/stream_flush_error_test.go b/internal/gateway/stream_flush_error_test.go new file mode 100644 index 000000000..27549e4be --- /dev/null +++ b/internal/gateway/stream_flush_error_test.go @@ -0,0 +1,80 @@ +package gateway + +import ( + "bytes" + "errors" + "net/http" + "strings" + "testing" +) + +// flushErrorWriter reports failure only through FlushError, the interface +// http.ResponseController knows about. A relay that checks only Write success +// would misreport delivery here. +type flushErrorWriter struct { + header http.Header + body bytes.Buffer +} + +func (w *flushErrorWriter) Header() http.Header { + if w.header == nil { + w.header = make(http.Header) + } + return w.header +} +func (w *flushErrorWriter) WriteHeader(int) {} +func (w *flushErrorWriter) Write(p []byte) (int, error) { + return w.body.Write(p) +} +func (w *flushErrorWriter) FlushError() error { return errors.New("client flush failed") } + +func TestAllStreamRelaysPropagateFlushError(t *testing.T) { + cases := []struct { + name string + run func(*flushErrorWriter) (StreamRelayStats, error) + }{ + { + name: "openai", + run: func(w *flushErrorWriter) (StreamRelayStats, error) { + return RelayOpenAIStream(w, strings.NewReader("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n")) + }, + }, + { + name: "anthropic", + run: func(w *flushErrorWriter) (StreamRelayStats, error) { + flush, ok := newStreamFlushWriter(w) + if !ok { + t.Fatal("flush-error writer was not recognized") + } + return RelayAnthropicStream(flush, strings.NewReader("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"), "req", "model") + }, + }, + { + name: "responses", + run: func(w *flushErrorWriter) (StreamRelayStats, error) { + flush, _ := newStreamFlushWriter(w) + return RelayResponsesStream(flush, strings.NewReader("event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n"), "req", "model", nil) + }, + }, + { + name: "native responses", + run: func(w *flushErrorWriter) (StreamRelayStats, error) { + flush, _ := newStreamFlushWriter(w) + return RelayNativeResponsesStream(flush, strings.NewReader("event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"}}\n\n"), nil) + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + writer := &flushErrorWriter{} + stats, err := tc.run(writer) + var writeErr *StreamRelayWriteError + if !errors.As(err, &writeErr) { + t.Fatalf("err = %T %v, want StreamRelayWriteError", err, err) + } + if stats.DownstreamDone { + t.Fatalf("flush failure was recorded as delivered: %+v", stats) + } + }) + } +} diff --git a/internal/gateway/stream_heartbeat.go b/internal/gateway/stream_heartbeat.go index 98e2baad4..d4a3caa9d 100644 --- a/internal/gateway/stream_heartbeat.go +++ b/internal/gateway/stream_heartbeat.go @@ -69,15 +69,10 @@ func resolveMillisEnv(name string, fallback, floor time.Duration) time.Duration // streamHeartbeat owns the early-commit decision and the comment-frame pump. // -// Three goroutines can touch the ResponseWriter over the life of a request: the -// handler itself, the heartbeat timer, and the pump. net/http does not make -// ResponseWriter safe for concurrent use, so every write goes through writeMu: -// -// - the pump writes comment frames under writeMu; -// - handoff closes stop and then waits for pumpDone, so it returns only after -// the in-flight heartbeat write finished and no further one can start; -// - after handoff the handler owns the writer exclusively, and the pump has -// provably stopped. +// The timer callback and the handler arbitrate ownership under mu. The timer +// owns the writer only if it starts before handoff retires it. The callback +// serially commits the headers and writes heartbeats, and handoff waits for +// it to finish before returning the writer to the handler. // // A nil *streamHeartbeat is a valid no-op value, which is what a writer that // cannot flush gets. @@ -87,28 +82,14 @@ type streamHeartbeat struct { after time.Duration interval time.Duration - // writeMu serialises writes to w between the timer's commit and the pump. - writeMu sync.Mutex - - mu sync.Mutex - state heartbeatState - timer *time.Timer - stop chan struct{} - pumpDone chan struct{} - committed chan struct{} - writeErr error + mu sync.Mutex + retired bool + timer *time.Timer + stop chan struct{} + done chan struct{} // non-nil once the callback claims the writer + writeErr error } -type heartbeatState int - -const ( - heartbeatIdle heartbeatState = iota - heartbeatCommitting - heartbeatCommitted - heartbeatAdopted - heartbeatAbandoned -) - // newStreamHeartbeat returns nil when the writer cannot flush, which leaves the // original behaviour untouched. func newStreamHeartbeat(w http.ResponseWriter) *streamHeartbeat { @@ -129,11 +110,10 @@ func newStreamHeartbeatWith(w http.ResponseWriter, after, interval time.Duration interval = defaultHeartbeatInterval } return &streamHeartbeat{ - w: w, - flusher: flusher, - after: after, - interval: interval, - committed: make(chan struct{}), + w: w, + flusher: flusher, + after: after, + interval: interval, } } @@ -145,108 +125,65 @@ func (h *streamHeartbeat) Arm(setHeaders func()) { return } h.mu.Lock() - if h.state != heartbeatIdle { - h.mu.Unlock() + defer h.mu.Unlock() + if h.retired || h.timer != nil { return } h.timer = time.AfterFunc(h.after, func() { h.mu.Lock() - if h.state != heartbeatIdle { + if h.retired { h.mu.Unlock() return } - h.state = heartbeatCommitting h.stop = make(chan struct{}) - h.pumpDone = make(chan struct{}) + h.done = make(chan struct{}) h.mu.Unlock() + defer close(h.done) - h.writeMu.Lock() setHeaders() h.w.WriteHeader(http.StatusOK) h.flusher.Flush() - h.writeMu.Unlock() - - h.mu.Lock() - h.state = heartbeatCommitted - h.mu.Unlock() - close(h.committed) - h.pump() - close(h.pumpDone) }) - h.mu.Unlock() } // Adopt hands the response to the real relay. It reports whether the timer had // already committed the headers, in which case the caller must not set headers // or call WriteHeader again. func (h *streamHeartbeat) Adopt() bool { - return h.handoff(heartbeatAdopted) + return h.handoff() } // Abandon retires the heartbeat on the error path and reports whether the // headers were already committed. When they were, the failure can only be // reported as an in-stream error event. func (h *streamHeartbeat) Abandon() bool { - return h.handoff(heartbeatAbandoned) + return h.handoff() } -// handoff retires the heartbeat. When the headers were committed it blocks -// until the pump has exited, so the caller owns the writer exclusively. -func (h *streamHeartbeat) handoff(next heartbeatState) bool { +// handoff retires the timer and checks ownership in the same critical section; +// otherwise the timer could claim the writer between the check and retirement. +func (h *streamHeartbeat) handoff() bool { if h == nil { return false } h.mu.Lock() - state := h.state - stop := h.stop - committed := h.committed - pumpDone := h.pumpDone - h.mu.Unlock() - - switch state { - case heartbeatIdle: - // The timer never fired. Flip the state first: a late callback - // re-checks it under the same mutex and bails out before writing. - h.mu.Lock() - if h.state == heartbeatIdle { - h.state = next - } - h.mu.Unlock() - if h.timer != nil { - h.timer.Stop() - } - return false - case heartbeatCommitting, heartbeatCommitted: - if stop != nil { - select { - case <-stop: - default: - close(stop) - } - } - // committed is closed once the headers are on the wire; pumpDone once - // the pump has stopped writing. Waiting on pumpDone is what makes the - // handoff race-free. Both are created by the timer callback before it - // publishes heartbeatCommitting, so they are non-nil whenever this - // branch runs. - if committed != nil { - <-committed - } - if pumpDone != nil { - <-pumpDone - } - h.mu.Lock() - h.state = next - h.mu.Unlock() - if h.timer != nil { + done := h.done + if !h.retired { + h.retired = true + if done != nil { + close(h.stop) + } else if h.timer != nil { h.timer.Stop() } - return true - default: - // Already adopted or abandoned: the timer never committed headers. - return false } + h.mu.Unlock() + + if done != nil { + // This includes any in-progress initial commit, not just the pump. + <-done + } + return done != nil } // pump emits comment frames until handoff closes stop. @@ -258,12 +195,13 @@ func (h *streamHeartbeat) pump() { case <-h.stop: return case <-ticker.C: - h.writeMu.Lock() - _, err := io.WriteString(h.w, ": keepalive\n\n") + n, err := h.w.Write([]byte(": keepalive\n\n")) + if err == nil && n < len(": keepalive\n\n") { + err = io.ErrShortWrite + } if err == nil { h.flusher.Flush() } - h.writeMu.Unlock() if err != nil { h.mu.Lock() if h.writeErr == nil { diff --git a/internal/gateway/stream_heartbeat_followup_test.go b/internal/gateway/stream_heartbeat_followup_test.go index 24bf0cffc..723869863 100644 --- a/internal/gateway/stream_heartbeat_followup_test.go +++ b/internal/gateway/stream_heartbeat_followup_test.go @@ -17,71 +17,59 @@ import ( applogs "github.com/caigee-cmd/cli2api/internal/logs" ) -// When the heartbeat commits before the upstream head arrives, the client must -// still see the account and provider headers on the response. -func TestHeartbeatCommitsAccountHeadersOnLiveStream(t *testing.T) { +// A direct provider request also omits unconfirmed identity after an early +// commit, but the heartbeat still keeps the connection alive for the answer. +func TestHeartbeatKeepsSlowStreamWithoutUnconfirmedIdentity(t *testing.T) { + allowUpstream := make(chan struct{}) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(3 * time.Second) + select { + case <-allowUpstream: + case <-r.Context().Done(): + return + } w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") - w.WriteHeader(http.StatusOK) - flusher := w.(http.Flusher) - _, _ = w.Write([]byte(`data: {"choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}` + "\n\n")) - flusher.Flush() - _, _ = w.Write([]byte("data: [DONE]\n\n")) - flusher.Flush() + _, _ = io.WriteString(w, `data: {"choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}`+"\n\ndata: [DONE]\n\n") })) defer upstream.Close() - t.Setenv(heartbeatEnvAfter, "150") - t.Setenv(heartbeatEnvInterval, "100") + t.Setenv(heartbeatEnvAfter, "1000") + t.Setenv(heartbeatEnvInterval, "1000") handler, closeAll := newHeartbeatFollowupHandler(t, upstream.URL, nil) defer closeAll() gateway := httptest.NewServer(handler) defer gateway.Close() + allow := sync.OnceFunc(func() { close(allowUpstream) }) + defer allow() - resp, err := http.Post(gateway.URL+"/v1/chat/completions", "application/json", + client := gateway.Client() + client.Timeout = 8 * time.Second + resp, err := client.Post(gateway.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"qoder/mock","stream":true,"messages":[{"role":"user","content":"hi"}]}`)) if err != nil { t.Fatalf("request failed: %v", err) } defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - t.Fatalf("status = %d, body = %s", resp.StatusCode, body) - } - if got := resp.Header.Get("X-CLI2API-Account"); got != "acct" { - t.Fatalf("X-CLI2API-Account = %q, want acct", got) - } - if got := resp.Header.Get("X-Qoder-Account"); got != "acct" { - t.Fatalf("X-Qoder-Account = %q, want acct", got) - } - if got := resp.Header.Get("X-CLI2API-Provider"); got != "qoder" { - t.Fatalf("X-CLI2API-Provider = %q, want qoder", got) + if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { + t.Fatalf("status = %d, headers = %v", resp.StatusCode, resp.Header) + } + // The upstream has not returned, so the final routed account is not yet + // known; keep the early heartbeat identity-free to remain correct on retry. + for _, key := range []string{"X-CLI2API-Account", "X-Qoder-Account", "X-CLI2API-Provider"} { + if got := resp.Header.Values(key); len(got) != 0 { + t.Errorf("early heartbeat sent unconfirmed %s header values: %v", key, got) + } } - sawKeepalive, sawDone := false, false reader := bufio.NewReader(resp.Body) - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - line, err := reader.ReadString('\n') - if strings.HasPrefix(line, ": keepalive") { - sawKeepalive = true - } - if strings.HasPrefix(line, "data: [DONE]") { - sawDone = true - break - } - if err != nil { - break - } - } - if !sawKeepalive { - t.Fatal("expected a heartbeat frame before the upstream body, otherwise this did not test the early-commit path") + if line, err := reader.ReadString('\n'); err != nil || line != ": keepalive\n" { + t.Fatalf("expected a heartbeat before releasing the upstream, got %q (%v)", line, err) } - if !sawDone { - t.Fatal("stream did not complete") + allow() + body, err := io.ReadAll(reader) + if err != nil || !strings.Contains(string(body), `"content":"ok"`) || !strings.Contains(string(body), "data: [DONE]") { + t.Fatalf("stream did not complete: %s (%v)", body, err) } } diff --git a/internal/gateway/stream_heartbeat_test.go b/internal/gateway/stream_heartbeat_test.go index f46086289..155579587 100644 --- a/internal/gateway/stream_heartbeat_test.go +++ b/internal/gateway/stream_heartbeat_test.go @@ -6,6 +6,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" ) @@ -103,23 +104,21 @@ func TestHeartbeatCommitsHeadersWhileUpstreamHeadIsPending(t *testing.T) { // A fast upstream must keep the plain HTTP-status path: the timer is disarmed, // nothing is written, and the caller still owns the response. func TestHeartbeatDoesNotCommitBeforeDeadline(t *testing.T) { - w := newRecordingWriter() - h := newStreamHeartbeatWith(w, 5*time.Second, time.Second) - h.Arm(headerFunc(w)) - - if committed := h.Adopt(); committed { - t.Fatal("Adopt reported a commit, but the timer had not fired") - } - status, body, _, _ := w.snapshot() - if status != 0 || body != "" { - t.Fatalf("writer touched before the deadline: status=%d body=%q", status, body) - } - - // Prove the timer really was disarmed rather than merely late. - time.Sleep(80 * time.Millisecond) - if status, _, _, _ := w.snapshot(); status != 0 { - t.Fatalf("timer wrote headers after Adopt, status=%d", status) - } + synctest.Test(t, func(t *testing.T) { + w := newRecordingWriter() + h := newStreamHeartbeatWith(w, time.Second, time.Second) + h.Arm(headerFunc(w)) + + if h.Adopt() { + t.Fatal("Adopt reported a commit, but the timer had not fired") + } + // Advance past the deadline to distinguish a retired timer from a late one. + time.Sleep(2 * time.Second) + synctest.Wait() + if status, body, _, flushes := w.snapshot(); status != 0 || body != "" || flushes != 0 { + t.Fatalf("timer wrote after Adopt: status=%d body=%q flushes=%d", status, body, flushes) + } + }) } // The error path needs to know whether it can still answer with a status code. @@ -172,30 +171,35 @@ func TestHeartbeatDisabledWithoutFlusher(t *testing.T) { // The pump must stop once the relay takes over, otherwise it would keep // writing comment frames into a response body that already has real chunks. func TestHeartbeatPumpStopsAfterAdopt(t *testing.T) { - w := newRecordingWriter() - h := newStreamHeartbeatWith(w, 30*time.Millisecond, 10*time.Millisecond) - h.Arm(headerFunc(w)) - time.Sleep(90 * time.Millisecond) - - if !h.Adopt() { - t.Fatal("expected a commit") - } - _, _, writesAtAdopt, _ := w.snapshot() - writesAtAdopt = append([]time.Duration(nil), writesAtAdopt...) - - time.Sleep(120 * time.Millisecond) - _, _, writesLater, _ := w.snapshot() - if len(writesLater) > len(writesAtAdopt)+1 { - t.Fatalf("pump kept writing after Adopt: %d writes at adopt, %d later", - len(writesAtAdopt), len(writesLater)) - } + synctest.Test(t, func(t *testing.T) { + w := newRecordingWriter() + h := newStreamHeartbeatWith(w, time.Second, time.Second) + h.Arm(headerFunc(w)) + time.Sleep(3 * time.Second) + synctest.Wait() + + if !h.Adopt() { + t.Fatal("expected a commit") + } + _, _, writesAtAdopt, _ := w.snapshot() + if len(writesAtAdopt) == 0 { + t.Fatal("the pump did not write before Adopt") + } + + time.Sleep(3 * time.Second) + synctest.Wait() + _, _, writesLater, _ := w.snapshot() + if len(writesLater) != len(writesAtAdopt) { + t.Fatalf("pump kept writing after Adopt: %d writes at adopt, %d later", len(writesAtAdopt), len(writesLater)) + } + }) } // A heartbeat write failure means the client is gone; record it instead of // spinning. func TestHeartbeatRecordsClientWriteError(t *testing.T) { w := newRecordingWriter() - w.writeErr = errWriteClosed + w.writeErr = http.ErrHandlerTimeout h := newStreamHeartbeatWith(w, 30*time.Millisecond, 10*time.Millisecond) h.Arm(headerFunc(w)) time.Sleep(90 * time.Millisecond) @@ -208,30 +212,44 @@ func TestHeartbeatRecordsClientWriteError(t *testing.T) { } } -var errWriteClosed = &StreamRelayWriteError{err: http.ErrHandlerTimeout} - -// Identity headers registered in setHeaders must already be on the writer when -// the timer commits, because WriteHeader is the last chance to send them. -func TestHeartbeatCommitsAccountProviderHeaders(t *testing.T) { - w := newRecordingWriter() - h := newStreamHeartbeatWith(w, 40*time.Millisecond, 20*time.Millisecond) - h.Arm(func() { - w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") - w.Header().Set("X-Qoder-Account", "acct-1") - w.Header().Set("X-CLI2API-Account", "acct-1") - w.Header().Set("X-CLI2API-Provider", "qoder") - }) - time.Sleep(120 * time.Millisecond) - if !h.Adopt() { - t.Fatal("expected the headers to be committed") - } - if got := w.header.Get("X-CLI2API-Account"); got != "acct-1" { - t.Fatalf("X-CLI2API-Account = %q, want acct-1", got) - } - if got := w.header.Get("X-Qoder-Account"); got != "acct-1" { - t.Fatalf("X-Qoder-Account = %q, want acct-1", got) - } - if got := w.header.Get("X-CLI2API-Provider"); got != "qoder" { - t.Fatalf("X-CLI2API-Provider = %q, want qoder", got) +func TestHeartbeatHandoffWaitsForCommit(t *testing.T) { + for _, tc := range []struct { + name string + handoff func(*streamHeartbeat) bool + }{ + {"adopt", (*streamHeartbeat).Adopt}, + {"abandon", (*streamHeartbeat).Abandon}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + w := newRecordingWriter() + h := newStreamHeartbeatWith(w, time.Second, time.Second) + committing, releaseCommit := make(chan struct{}), make(chan struct{}) + h.Arm(func() { + close(committing) + <-releaseCommit + headerFunc(w)() + }) + <-committing + + returned := make(chan bool, 1) + go func() { returned <- tc.handoff(h) }() + synctest.Wait() + select { + case committed := <-returned: + close(releaseCommit) + t.Fatalf("handoff returned %t during the initial SSE commit", committed) + default: + } + + close(releaseCommit) + if !<-returned { + t.Fatal("handoff missed the committed SSE response") + } + if status, body, _, flushes := w.snapshot(); status != http.StatusOK || body != "" || flushes != 1 { + t.Fatalf("unexpected writes: status=%d body=%q flushes=%d", status, body, flushes) + } + }) + }) } } diff --git a/internal/gateway/stream_route_identity_test.go b/internal/gateway/stream_route_identity_test.go new file mode 100644 index 000000000..29e5dca3a --- /dev/null +++ b/internal/gateway/stream_route_identity_test.go @@ -0,0 +1,183 @@ +package gateway + +import ( + "bufio" + "context" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type streamRouteTestCatalog map[string]accounts.Aggregation + +func (c streamRouteTestCatalog) Resolve(_ context.Context, id string, _ map[string]bool) (accounts.Aggregation, error) { + agg, ok := c[id] + if !ok { + return accounts.Aggregation{}, accounts.ErrAggregationNotFound + } + return agg, nil +} + +func (c streamRouteTestCatalog) Catalog(context.Context) (map[string]accounts.Aggregation, error) { + return c, nil +} + +type streamRouteTestAdapter func(context.Context, string, translate.ChatRequest) (*http.Response, error) + +func (f streamRouteTestAdapter) ChatNonStream(context.Context, string, translate.ChatRequest) (providers.ChatOutcome, error) { + return providers.ChatOutcome{}, providers.ErrUnsupported +} + +func (f streamRouteTestAdapter) ChatStream(ctx context.Context, id string, req translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + resp, err := f(ctx, id, req) + return resp, providers.ResolvedChat{}, err +} + +func TestOpenAIStreamRouteIdentityWithNamedGroup(t *testing.T) { + const primaryID, backupID = "synthetic-primary", "synthetic-backup" + const rootID, tierID = "chat-route", "first-tier" + const pipeline = `{"version":1,"steps":[ + {"id":"first","kind":"group","aggregation_id":"first-tier"}, + {"id":"second","kind":"member","provider":"workbuddy","region":"cn","model":"backup-model"}]}` + + for _, tc := range []struct { + name string + early, fallback bool + }{ + {name: "early failover", early: true, fallback: true}, + {name: "fast failover", fallback: true}, + {name: "early terminal failure", early: true}, + {name: "fast terminal failure"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv(heartbeatEnvInterval, "1000") + if tc.early { + t.Setenv(heartbeatEnvAfter, "1000") + } else { + t.Setenv(heartbeatEnvAfter, "60000") + } + + // Run the real handler and executor with a named priority group + // that tries its account before a separate fallback provider. + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: primaryID, Provider: "qoder", Region: "global", Runtime: "in_process", Models: []string{"primary-model"}}) + pool.Upsert(executor.Item{ID: backupID, Provider: "workbuddy", Region: "cn", Runtime: "in_process", Models: []string{"backup-model"}}) + catalog := streamRouteTestCatalog{ + rootID: {ID: rootID, Enabled: true, Strategy: accounts.AggregationPriority, AllowFallbacks: tc.fallback, MaxAttempts: 2, Document: pipeline}, + tierID: {ID: tierID, Enabled: true, Strategy: accounts.AggregationPriority, Members: []accounts.AggregationMember{ + {AccountID: primaryID, Provider: "qoder", Region: "global", Model: "primary-model", Weight: 1}, + }}, + } + + primaryStarted := make(chan struct{}) + releasePrimary := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(releasePrimary) }) + if !tc.early { + unblock() + } + var calls []string + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "qoder", Chat: streamRouteTestAdapter(func(ctx context.Context, id string, req translate.ChatRequest) (*http.Response, error) { + calls = append(calls, id+"/"+req.Model) + close(primaryStarted) + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-releasePrimary: + return nil, &providers.Error{Kind: accounts.KindRateLimit, Status: http.StatusTooManyRequests, Code: "rate_limit_exceeded", Message: "synthetic primary rate limit"} + } + })}) + registry.Register(providers.Adapter{ID: "workbuddy", Chat: streamRouteTestAdapter(func(_ context.Context, id string, req translate.ChatRequest) (*http.Response, error) { + calls = append(calls, id+"/"+req.Model) + body := `data: {"choices":[{"index":0,"delta":{"content":"served-by-backup"}}]}` + "\n\ndata: [DONE]\n\n" + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + })}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool, Aggregations: catalog} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "synthetic-route-key", ModelAggregation: true, AllowedProviders: []string{accounts.AggregationProvider}} + handled := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) { + defer close(handled) + h.HandleChatCompletions(w, r.WithContext(auth.WithIdentity(r.Context(), identity))) + }) + server := httptest.NewServer(mux) + defer server.Close() + defer unblock() + client := server.Client() + client.Timeout = 8 * time.Second + resp, err := client.Post(server.URL+"/v1/chat/completions", "application/json", strings.NewReader( + `{"model":"chat-route","messages":[{"role":"user","content":"hello"}],"stream":true}`)) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + reader := bufio.NewReader(resp.Body) + if tc.early { + first, err := reader.ReadString('\n') + if err != nil || first != ": keepalive\n" { + t.Fatalf("expected a heartbeat ahead of the blocked upstream, got %q (%v)", first, err) + } + select { + case <-primaryStarted: + default: + t.Fatal("the heartbeat must land after selecting the named group primary") + } + unblock() + } + body, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + <-handled + + wantStatus := http.StatusOK + wantType, wantAccount, wantProvider := "text/event-stream", "", "" + wantCalls := []string{primaryID + "/primary-model"} + if tc.fallback { + wantCalls = append(wantCalls, backupID+"/backup-model") + if !strings.Contains(string(body), "served-by-backup") || !strings.Contains(string(body), "data: [DONE]") { + t.Fatalf("did not relay the backup answer and terminal event: %s", body) + } + if !tc.early { + wantAccount, wantProvider = backupID, "workbuddy" + } + } else { + if !tc.early { + wantStatus = http.StatusTooManyRequests + wantType = "application/json" + } + if !strings.Contains(string(body), `"code":"rate_limit_exceeded"`) || strings.Contains(string(body), "[DONE]") { + t.Fatalf("missing expected terminal rate-limit error: %s", body) + } + if tc.early && strings.Count(string(body), `data: {"error":`) != 1 { + t.Fatalf("want a single error event, got: %s", body) + } + } + if !slices.Equal(calls, wantCalls) { + t.Fatalf("dispatched %v, want %v", calls, wantCalls) + } + if resp.StatusCode != wantStatus || !strings.HasPrefix(resp.Header.Get("Content-Type"), wantType) || resp.Header.Get("X-Request-Id") == "" { + t.Fatalf("unexpected response: status=%d headers=%v body=%s", resp.StatusCode, resp.Header, body) + } + for k, want := range map[string]string{"X-CLI2API-Account": wantAccount, "X-Qoder-Account": wantAccount, "X-CLI2API-Provider": wantProvider} { + got := resp.Header.Values(k) + if (want == "" && len(got) != 0) || (want != "" && !slices.Equal(got, []string{want})) { + t.Errorf("%s = %q, want %q; response body = %s", k, got, want, body) + } + } + }) + } +} diff --git a/internal/gateway/stream_terminal_test.go b/internal/gateway/stream_terminal_test.go new file mode 100644 index 000000000..c84f5ebdd --- /dev/null +++ b/internal/gateway/stream_terminal_test.go @@ -0,0 +1,144 @@ +package gateway + +import ( + "io" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +const chatStreamText = `data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" +const chatStreamFinish = `data: {"choices":[{"delta":{},"finish_reason":"stop"}]}` + "\n\n" +const chatStreamUsage = `data: {"usage":{"prompt_tokens":7,"completion_tokens":3}}` + "\n\n" +const chatStreamDone = "data: [DONE]\n\n" + +var chatStreamRelays = []struct { + name, terminal string + relay func(*httptest.ResponseRecorder, io.Reader) (StreamRelayStats, error) +}{ + {"openai", chatStreamDone, func(w *httptest.ResponseRecorder, body io.Reader) (StreamRelayStats, error) { + return RelayOpenAIStream(w, body) + }}, + {"anthropic", "event: message_stop\n", func(w *httptest.ResponseRecorder, body io.Reader) (StreamRelayStats, error) { + return RelayAnthropicStream(w, body, "req", "model") + }}, + {"responses", "event: response.completed\n", func(w *httptest.ResponseRecorder, body io.Reader) (StreamRelayStats, error) { + return RelayResponsesStream(w, body, "req", "model", nil) + }}, +} + +func TestChatStreamRelaysStopAtDone(t *testing.T) { + for _, tc := range chatStreamRelays { + t.Run(tc.name, func(t *testing.T) { + tail := &unexpectedEOFReader{} + upstream := io.MultiReader(strings.NewReader(chatStreamText+chatStreamFinish+chatStreamUsage+chatStreamDone), tail) + w := httptest.NewRecorder() + stats, err := tc.relay(w, upstream) + if err != nil || tail.read || !stats.SawDone || strings.Count(w.Body.String(), tc.terminal) != 1 { + t.Fatalf("err=%v readTail=%t done=%t body=%s", err, tail.read, stats.SawDone, w.Body.String()) + } + if derefInt(stats.PromptTokens) != 7 || derefInt(stats.CompletionTokens) != 3 { + t.Fatalf("usage before [DONE] was not preserved: %+v", stats) + } + }) + } +} + +func TestChatStreamRelaysKeepMissingDoneBehavior(t *testing.T) { + for _, tc := range chatStreamRelays { + t.Run(tc.name, func(t *testing.T) { + w := httptest.NewRecorder() + stats, err := tc.relay(w, strings.NewReader(chatStreamText+chatStreamFinish)) + if tc.name == "openai" { + if err != nil || !stats.SawDone || strings.Count(w.Body.String(), tc.terminal) != 1 { + t.Fatalf("raw relay should synthesize [DONE]: err=%v done=%t body=%s", err, stats.SawDone, w.Body.String()) + } + } else if err == nil || ClassifyAPIError(err).Code != "upstream_stream_incomplete" || stats.SawDone || strings.Contains(w.Body.String(), tc.terminal) { + t.Fatalf("compatibility relay must require [DONE]: err=%v done=%t body=%s", err, stats.SawDone, w.Body.String()) + } + }) + } +} + +func TestChatStreamRelaysStopAtUpstreamError(t *testing.T) { + for _, tc := range chatStreamRelays { + t.Run(tc.name, func(t *testing.T) { + const upstreamError = "event: error\n" + `data: {"error":{"code":"rate_limit_exceeded","message":"slow down"}}` + "\n\n" + tail := &unexpectedEOFReader{} + upstream := io.MultiReader(strings.NewReader(chatStreamText+upstreamError), tail) + w := httptest.NewRecorder() + stats, err := tc.relay(w, upstream) + if err == nil || ClassifyAPIError(err).Kind != accounts.KindRateLimit || tail.read || stats.SawDone { + t.Fatalf("want original rate limit without reading past it: err=%v readTail=%t done=%t body=%s", err, tail.read, stats.SawDone, w.Body.String()) + } + if tc.name == "openai" && strings.Count(w.Body.String(), "rate_limit_exceeded") != 1 { + t.Fatalf("raw relay should write the upstream failure once: %s", w.Body.String()) + } + if strings.Contains(w.Body.String(), tc.terminal) { + t.Fatalf("relay emitted a success frame after failure: %s", w.Body.String()) + } + }) + } +} + +type rejectDoneWriter struct{ *httptest.ResponseRecorder } + +func (w rejectDoneWriter) Write(p []byte) (int, error) { + if strings.Contains(string(p), "[DONE]") { + return 0, io.ErrClosedPipe + } + return w.ResponseRecorder.Write(p) +} + +func TestOpenAIStreamDoesNotMarkUnwrittenDone(t *testing.T) { + w := rejectDoneWriter{httptest.NewRecorder()} + tail := &unexpectedEOFReader{} + stats, err := RelayOpenAIStream(w, io.MultiReader(strings.NewReader(chatStreamText+chatStreamDone), tail)) + if !IsStreamClientDisconnect(err) || stats.SawDone || tail.read { + t.Fatalf("want a write failure without a terminal marker: err=%v done=%t readTail=%t", err, stats.SawDone, tail.read) + } + if stats.DownstreamTerminal != "error" || stats.FlushState != "error" { + t.Fatalf("downstream terminal not recorded: %+v", stats) + } +} + +type rejectTerminalWriter struct { + *httptest.ResponseRecorder + marker string +} + +func (w rejectTerminalWriter) Write(p []byte) (int, error) { + if strings.Contains(string(p), w.marker) { + return 0, io.ErrClosedPipe + } + return w.ResponseRecorder.Write(p) +} + +func TestCompatibilityRelaysDoNotMarkUnwrittenTerminal(t *testing.T) { + cases := []struct { + name, marker string + relay func(io.Writer, io.Reader) (StreamRelayStats, error) + }{ + {"anthropic", "event: message_stop\n", func(w io.Writer, body io.Reader) (StreamRelayStats, error) { + return RelayAnthropicStream(w, body, "req", "model") + }}, + {"responses", "event: response.completed\n", func(w io.Writer, body io.Reader) (StreamRelayStats, error) { + return RelayResponsesStream(w, body, "req", "model", nil) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + w := &rejectTerminalWriter{ResponseRecorder: httptest.NewRecorder(), marker: tc.marker} + ups := strings.NewReader(chatStreamText + chatStreamFinish + chatStreamUsage + chatStreamDone) + stats, err := tc.relay(w, ups) + if err == nil || !IsStreamClientDisconnect(err) { + t.Fatalf("terminal write failure not propagated: err=%v", err) + } + if stats.DownstreamDone || stats.DownstreamTerminal != "error" || stats.FlushState != "error" { + t.Fatalf("relay marked an unwritten terminal as delivered: %+v", stats) + } + }) + } +} diff --git a/internal/gateway/toolargs_stream_test.go b/internal/gateway/toolargs_stream_test.go index c442004c8..49fe905d2 100644 --- a/internal/gateway/toolargs_stream_test.go +++ b/internal/gateway/toolargs_stream_test.go @@ -5,17 +5,38 @@ import ( "net/http/httptest" "strings" "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" ) func feedChunks(t *testing.T, chunks ...string) *streamedChatOutput { t.Helper() - output := &streamedChatOutput{} + output := &streamedChatOutput{canonical: toolcall.NewReducer(streamToolingRequest(t))} for _, chunk := range chunks { output.add([]byte(chunk)) } + if err := output.finalize("done"); err != nil { + t.Fatal(err) + } return output } +func streamToolingRequest(t *testing.T) toolcall.Request { + t.Helper() + tools := json.RawMessage(`[ + {"type":"function","function":{"name":"read_file","parameters":{"type":"object","additionalProperties":true}}}, + {"type":"function","function":{"name":"write_file","parameters":{"type":"object","additionalProperties":true}}}, + {"type":"function","function":{"name":"grep","parameters":{"type":"object","additionalProperties":true}}}, + {"type":"function","function":{"name":"a","parameters":{"type":"object","additionalProperties":true}}}, + {"type":"function","function":{"name":"b","parameters":{"type":"object","additionalProperties":true}}} + ]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, tools, nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + func TestStreamAccumulatesSplitArguments(t *testing.T) { output := feedChunks(t, `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":""}}]}}]}`, @@ -43,11 +64,11 @@ func TestStreamHandlesCumulativeArguments(t *testing.T) { if len(calls) != 1 { t.Fatalf("calls = %d, want 1: %+v", len(calls), calls) } - if calls[0].Arguments != `{"path":"a.go","body":"x"}` { + if calls[0].Arguments != `{"body":"x","path":"a.go"}` { t.Fatalf("arguments = %q", calls[0].Arguments) } - if normalizeProxyToolCallArguments(calls) { - t.Fatal("valid arguments should not be reported as changed") + if !json.Valid([]byte(calls[0].Arguments)) { + t.Fatalf("arguments not valid JSON: %q", calls[0].Arguments) } } @@ -110,7 +131,7 @@ func TestStreamSameToolTwiceStaysSeparate(t *testing.T) { } } -func TestRelayOpenAIStreamNormalizesFragmentedToolArguments(t *testing.T) { +func TestRelayOpenAIStreamRejectsTruncatedToolArguments(t *testing.T) { body := strings.Join([]string{ `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"write_file","arguments":"{\"path\":"}}]}}]}`, "", @@ -124,72 +145,21 @@ func TestRelayOpenAIStreamNormalizesFragmentedToolArguments(t *testing.T) { "", }, "\n") recorder := httptest.NewRecorder() - stats, err := RelayOpenAIStream(recorder, strings.NewReader(body)) - if err != nil { - t.Fatal(err) - } - if !stats.SawDone { - t.Fatalf("stats=%+v", stats) - } - var arguments []string - for _, line := range strings.Split(recorder.Body.String(), "\n") { - payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) - if payload == "" || payload == "[DONE]" { - continue - } - var chunk struct { - Choices []struct { - Delta struct { - ToolCalls []struct { - Function struct { - Arguments string `json:"arguments"` - } `json:"function"` - } `json:"tool_calls"` - } `json:"delta"` - } `json:"choices"` - } - if json.Unmarshal([]byte(payload), &chunk) != nil { - continue - } - for _, choice := range chunk.Choices { - for _, call := range choice.Delta.ToolCalls { - arguments = append(arguments, call.Function.Arguments) - } - } - } - if len(arguments) != 1 { - t.Fatalf("expected exactly one arguments frame, got %d: %#v", len(arguments), arguments) - } - // The body field was cut mid-string, so it is dropped rather than padded - // into a plausible-looking value; everything the model finished survives. - if arguments[0] != `{"path":"a.go"}` { - t.Fatalf("arguments = %q", arguments[0]) - } - if !json.Valid([]byte(arguments[0])) { - t.Fatalf("arguments not valid JSON: %q", arguments[0]) - } -} - -func TestNormalizeRepairsFormattingDamage(t *testing.T) { - calls := []proxyToolCall{{ID: "call_1", Name: "write_file", Arguments: `{"path":"a.go",`}} - if !normalizeProxyToolCallArguments(calls) { - t.Fatal("expected repair to be reported") + stats, err := RelayOpenAIStream(recorder, strings.NewReader(body), streamToolingRequest(t)) + if err == nil { + t.Fatal("expected a truncated tool argument to fail the turn") } - if !json.Valid([]byte(calls[0].Arguments)) { - t.Fatalf("arguments not valid after normalize: %q", calls[0].Arguments) + if stats.DownstreamDone { + t.Fatalf("a failed tool turn must not report downstream success: %+v", stats) } -} - -func TestNormalizeTruncatedArgumentsNeverFails(t *testing.T) { - calls := []proxyToolCall{{ID: "call_1", Name: "run_command", Arguments: `{"cmd":"rm -rf /tmp/fo`}} - if !normalizeProxyToolCallArguments(calls) { - t.Fatal("expected normalize to change truncated arguments") + bodyText := recorder.Body.String() + if !strings.Contains(bodyText, `"error"`) { + t.Fatalf("expected an in-stream error frame, got:\n%s", bodyText) } - if !json.Valid([]byte(calls[0].Arguments)) { - t.Fatalf("arguments still invalid: %q", calls[0].Arguments) + if strings.Contains(bodyText, "data: [DONE]") { + t.Fatalf("a failed tool turn must not synthesize [DONE]:\n%s", bodyText) } - // The unfinished command must not survive as a runnable string. - if strings.Contains(calls[0].Arguments, "rm -rf") { - t.Fatalf("truncated command leaked into arguments: %q", calls[0].Arguments) + if strings.Contains(bodyText, `"path"`) || strings.Contains(bodyText, `"body"`) { + t.Fatalf("partial arguments leaked to the client:\n%s", bodyText) } } diff --git a/internal/gateway/toolcall_acceptance_test.go b/internal/gateway/toolcall_acceptance_test.go new file mode 100644 index 000000000..964e13bfe --- /dev/null +++ b/internal/gateway/toolcall_acceptance_test.go @@ -0,0 +1,282 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +type truncatedToolChat struct { + calls int +} + +func (c *truncatedToolChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + c.calls++ + return providers.ChatOutcome{ + Model: req.Model, Content: "partial answer", FinishReason: "length", + ToolCalls: json.RawMessage(`[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"README.md\"}"}}]`), + }, nil +} + +func (c *truncatedToolChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, fmt.Errorf("unexpected stream") +} + +func TestChatNonStreamTruncatedTurnDoesNotDeliverToolCalls(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "workbuddy", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + chat := &truncatedToolChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "truncated", AllowedProviders: []string{"workbuddy"}} + body := `{"model":"workbuddy/model","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]}` + response := callGateway(h.HandleChatCompletions, "/v1/chat/completions", body, identity) + if response.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + if chat.calls != 1 { + t.Fatalf("adapter calls=%d", chat.calls) + } + var envelope struct { + Choices []struct { + FinishReason string `json:"finish_reason"` + Message struct { + Content any `json:"content"` + ToolCalls []json.RawMessage `json:"tool_calls"` + } `json:"message"` + } `json:"choices"` + } + if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil { + t.Fatal(err) + } + if len(envelope.Choices) != 1 { + t.Fatalf("choices=%+v", envelope.Choices) + } + choice := envelope.Choices[0] + if choice.FinishReason != "length" || choice.Message.Content != "partial answer" { + t.Fatalf("truncated answer changed: %+v", choice) + } + if len(choice.Message.ToolCalls) != 0 { + t.Fatalf("truncated turn delivered tool_calls: %s", response.Body.String()) + } +} + +type violatingToolChat struct { + calls int +} + +func (c *violatingToolChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + c.calls++ + return providers.ChatOutcome{Model: req.Model, Content: "no tool", FinishReason: "stop"}, nil +} + +func (c *violatingToolChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, fmt.Errorf("unexpected stream") +} + +func TestToolChoiceViolationIsRecordedAsErrorNotSuccess(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "workbuddy", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + chat := &violatingToolChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(attempt accounts.RequestAttempt) { attempts = append(attempts, attempt) } + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "violating", AllowedProviders: []string{"workbuddy"}} + body := `{"model":"workbuddy/model","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}],"tool_choice":"required"}` + response := callGateway(h.HandleChatCompletions, "/v1/chat/completions", body, identity) + if response.Code != http.StatusBadGateway { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + if !strings.Contains(response.Body.String(), `"code":"invalid_upstream_tool_call"`) { + t.Fatalf("missing tool failure code: %s", response.Body.String()) + } + if len(attempts) != 1 { + t.Fatalf("attempts=%+v", attempts) + } + if attempts[0].Status != accounts.AttemptStatusError || attempts[0].ErrorKind != accounts.KindInvalidRequest { + t.Fatalf("violating dispatch was not recorded as error: %+v", attempts[0]) + } + item, _ := pool.ByID("workbuddy") + if item.LastKind != "" || !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 { + t.Fatalf("client-side contract violation changed account health: %+v", item) + } +} + +type noCallStreamChat struct { + calls int +} + +func (c *noCallStreamChat) ChatNonStream(context.Context, string, translate.ChatRequest) (providers.ChatOutcome, error) { + return providers.ChatOutcome{}, fmt.Errorf("unexpected non-stream") +} + +func (c *noCallStreamChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + c.calls++ + body := strings.Join([]string{ + `data: {"choices":[{"delta":{"content":"no tool"}}]}`, + `data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`, + "data: [DONE]", + "", + }, "\n\n") + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil +} + +func TestNativeResponsesToolViolationIsRecordedAsErrorNotSuccess(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "codex", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + body := "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n" + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(attempt accounts.RequestAttempt) { attempts = append(attempts, attempt) } + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "native-violating", AllowedProviders: []string{"codex"}} + body := `{"model":"codex/model","input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"required"}` + response := callGateway(h.HandleResponses, "/v1/responses", body, identity) + if response.Code != http.StatusBadGateway { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + if !strings.Contains(response.Body.String(), `"code":"invalid_upstream_tool_call"`) { + t.Fatalf("missing tool failure code: %s", response.Body.String()) + } + if len(attempts) != 1 || attempts[0].Status != accounts.AttemptStatusError || attempts[0].ErrorKind != accounts.KindInvalidRequest { + t.Fatalf("native violating dispatch was recorded as success: %+v", attempts) + } +} + +func TestNativeNonStreamRejectsTerminalEventBodyDisagreement(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "codex", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + // SSE terminal claims completion, embedded body claims incomplete and carries a tool call. + body := `data: {"type":"response.completed","response":{"status":"incomplete","output":[{"id":"fc_1","type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"README.md\"}"}]}}` + "\n\n" + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(a accounts.RequestAttempt) { attempts = append(attempts, a) } + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "nonstream-disagreement", AllowedProviders: []string{"codex"}} + body := `{"model":"codex/model","input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"required"}` + response := callGateway(h.HandleResponses, "/v1/responses", body, identity) + if response.Code != http.StatusBadGateway { + t.Fatalf("terminal/body disagreement was accepted: status=%d body=%s", response.Code, response.Body.String()) + } + if strings.Contains(response.Body.String(), "function_call") || strings.Contains(response.Body.String(), "call_1") { + t.Fatalf("tool call leaked in rejection: %s", response.Body.String()) + } + if !strings.Contains(response.Body.String(), "invalid_upstream_tool_call") { + t.Fatalf("rejection did not come from canonical tool validation: %s", response.Body.String()) + } + if len(attempts) != 1 || attempts[0].Status != accounts.AttemptStatusError { + t.Fatalf("rejected turn was recorded as success: %+v", attempts) + } +} + +func TestNativeResponsesStreamToolViolationDoesNotCoolAccount(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "codex", Provider: "codex", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "codex", NativeResponses: nativeRouteAdapter(func(string, *translate.NativeResponsesRequest, providers.RequestOptions) (*http.Response, providers.ResolvedChat, error) { + body := "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n" + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, providers.ResolvedChat{}, nil + })}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + var attempts []accounts.RequestAttempt + ex.OnAttempt = func(attempt accounts.RequestAttempt) { attempts = append(attempts, attempt) } + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "native-stream-violating", AllowedProviders: []string{"codex"}} + body := `{"model":"codex/model","stream":true,"input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"required"}` + response := callGateway(h.HandleResponses, "/v1/responses", body, identity) + if response.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + frames := parseClientSSE(response.Body.String()) + if len(frames) != 1 || frames[0].Event != "error" { + t.Fatalf("stream failure wrote %d frames: %s", len(frames), response.Body.String()) + } + var payload struct { + Error struct { + Code string `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal([]byte(frames[0].Data), &payload); err != nil { + t.Fatalf("stream error payload: %v (%q)", err, frames[0].Data) + } + if payload.Error.Code != "invalid_upstream_tool_call" { + t.Fatalf("code=%q body=%s", payload.Error.Code, response.Body.String()) + } + if len(attempts) != 1 || attempts[0].Status != accounts.AttemptStatusError || attempts[0].ErrorKind != accounts.KindInvalidRequest { + t.Fatalf("stream violation attempts=%+v", attempts) + } + item, _ := pool.ByID("codex") + if item.LastKind != "" || !item.DownUntil.IsZero() || len(item.ModelDownUntil) != 0 { + t.Fatalf("stream tool violation changed account health: %+v", item) + } +} + +func TestCompatibilityStreamsWriteToolFailureTerminalOnce(t *testing.T) { + for _, tc := range []struct { + name string + path string + body string + handler func(*Handler) http.HandlerFunc + }{ + { + name: "messages", path: "/v1/messages", + body: `{"model":"workbuddy/model","stream":true,"max_tokens":16,"messages":[{"role":"user","content":"hi"}],"tools":[{"name":"read_file","input_schema":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":{"type":"any"}}`, + handler: func(h *Handler) http.HandlerFunc { return h.HandleAnthropicMessages }, + }, + { + name: "responses", path: "/v1/responses", + body: `{"model":"workbuddy/model","stream":true,"input":"hi","tools":[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}],"tool_choice":"required"}`, + handler: func(h *Handler) http.HandlerFunc { return h.HandleResponses }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + pool := executor.NewPool(nil, nil) + pool.Upsert(executor.Item{ID: "workbuddy", Provider: "workbuddy", Region: "global", Runtime: "in_process", Models: []string{"model"}, MaxInFlight: 1}) + chat := &noCallStreamChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + ex := executor.NewChatExecutor(pool, "") + ex.Providers = registry + h := &Handler{Executor: ex, Pool: pool} + identity := auth.Identity{Kind: auth.KindKey, KeyID: "stream-" + tc.name, AllowedProviders: []string{"workbuddy"}} + response := callGateway(tc.handler(h), tc.path, tc.body, identity) + if response.Code != http.StatusOK { + t.Fatalf("status=%d body=%s", response.Code, response.Body.String()) + } + if chat.calls != 1 { + t.Fatalf("adapter calls=%d", chat.calls) + } + if count := strings.Count(response.Body.String(), "event: error\n"); count != 1 { + t.Fatalf("failure terminal written %d times: %s", count, response.Body.String()) + } + }) + } +} diff --git a/internal/gateway/toolcall_result.go b/internal/gateway/toolcall_result.go new file mode 100644 index 000000000..1a89733bc --- /dev/null +++ b/internal/gateway/toolcall_result.go @@ -0,0 +1,69 @@ +package gateway + +import ( + "encoding/json" + "net/http" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +// canonicalNonStreamTurn validates one buffered provider outcome against the +// request's tool contract. Adapters may normalize bytes, but only the canonical +// reducer is allowed to declare the turn successful. +func canonicalNonStreamTurn(request toolcall.Request, result executor.ChatResult) (toolcall.TurnResult, error) { + turn, err := toolcall.ReduceChatCompletion(request, result.Content, result.Reasoning, result.FinishReason, result.ToolCalls) + if err != nil { + return turn, err + } + if err := turn.Validate(); err != nil { + return turn, err + } + return turn, nil +} + +// validateNativeResponsesToolOutput delegates to the shared canonical +// validator so the gateway and the executor cannot disagree about a native +// Responses body. When the SSE terminal finish is known it is passed through, +// so event/body disagreement cannot be reintroduced at the HTTP layer. +func validateNativeResponsesToolOutput(raw json.RawMessage, request toolcall.Request, eventFinish ...string) error { + finish := "" + if len(eventFinish) > 0 { + finish = eventFinish[0] + } + return toolcall.ValidateNativeResponsesTurn(raw, request, finish) +} + +func writeToolCallResultError(w http.ResponseWriter, err error) { + WriteClassifiedErr(w, executor.NewExecutionError(executor.Classified{ + Kind: accounts.KindUnavailable, + Status: http.StatusBadGateway, + Code: "invalid_upstream_tool_call", + Type: "api_error", + Message: err.Error(), + }, nil)) +} + +func canonicalChatToolCalls(calls []toolcall.Call) []any { + out := make([]any, 0, len(calls)) + for _, call := range calls { + out = append(out, map[string]any{ + "id": call.InternalID, + "type": "function", + "function": map[string]any{ + "name": call.Name, + "arguments": string(call.Arguments), + }, + }) + } + return out +} + +func canonicalProxyToolCalls(turn toolcall.TurnResult) []proxyToolCall { + out := make([]proxyToolCall, 0, len(turn.Calls)) + for _, call := range turn.Calls { + out = append(out, proxyToolCall{ID: call.InternalID, Name: call.Name, Arguments: string(call.Arguments)}) + } + return out +} diff --git a/internal/gateway/toolcall_result_test.go b/internal/gateway/toolcall_result_test.go new file mode 100644 index 000000000..29111b90e --- /dev/null +++ b/internal/gateway/toolcall_result_test.go @@ -0,0 +1,55 @@ +package gateway + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/executor" + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +func TestValidateNativeResponsesToolOutput(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + valid := json.RawMessage(`{"status":"completed","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":\"a\"}"}]}`) + if err := validateNativeResponsesToolOutput(valid, request); err != nil { + t.Fatalf("valid native Responses body rejected: %v", err) + } + truncated := json.RawMessage(`{"status":"completed","output":[{"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{\"path\":"}]}`) + if err := validateNativeResponsesToolOutput(truncated, request); err == nil { + t.Fatal("truncated native Responses arguments accepted") + } + missing := json.RawMessage(`{"status":"completed","output":[]}`) + if err := validateNativeResponsesToolOutput(missing, request); err == nil || !strings.Contains(err.Error(), "required") { + t.Fatalf("missing required call error = %v", err) + } +} + +func TestCanonicalNonStreamTurnRejectsInvalidOrMissingCalls(t *testing.T) { + tools := json.RawMessage(`[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`) + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, tools, json.RawMessage(`"required"`), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + if _, err := canonicalNonStreamTurn(request, executor.ChatResult{ + ToolCalls: json.RawMessage(`[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":"}}]`), + }); err == nil || !strings.Contains(err.Error(), "read_file") { + t.Fatalf("truncated arguments error = %v", err) + } + if _, err := canonicalNonStreamTurn(request, executor.ChatResult{Content: "plain text"}); err == nil || !strings.Contains(err.Error(), "required") { + t.Fatalf("missing required call error = %v", err) + } + valid, err := canonicalNonStreamTurn(request, executor.ChatResult{ + ToolCalls: json.RawMessage(`[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a\"}"}}]`), + }) + if err != nil { + t.Fatal(err) + } + if valid.Status != toolcall.TurnToolCalls || len(valid.Calls) != 1 || string(valid.Calls[0].Arguments) != `{"path":"a"}` { + t.Fatalf("valid turn = %+v", valid) + } +} diff --git a/internal/gateway/toolcall_stream_test.go b/internal/gateway/toolcall_stream_test.go new file mode 100644 index 000000000..aa277eede --- /dev/null +++ b/internal/gateway/toolcall_stream_test.go @@ -0,0 +1,170 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/toolcall" +) + +func canonicalRequest(t *testing.T, tools, choice string) toolcall.Request { + t.Helper() + request, err := toolcall.ParseRequest(toolcall.ProtocolChat, json.RawMessage(tools), json.RawMessage(choice), nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + return request +} + +func TestRelayOpenAIStreamCanonicalKeepsSameIndexCallsSeparate(t *testing.T) { + request := canonicalRequest(t, `[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`, "") + body := strings.Join([]string{ + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a\"}"}}]}}]}`, + "", + `data: {"id":"c1","model":"m","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_2","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"b\"}"}}]},"finish_reason":"tool_calls"}]}`, + "", + "data: [DONE]", + "", + }, "\n") + recorder := httptest.NewRecorder() + stats, err := RelayOpenAIStream(recorder, strings.NewReader(body), request) + if err != nil { + t.Fatal(err) + } + if !stats.DownstreamDone || stats.FinishReason != "tool_calls" { + t.Fatalf("stats = %+v body=%s", stats, recorder.Body.String()) + } + var arguments []string + for _, line := range strings.Split(recorder.Body.String(), "\n") { + payload := strings.TrimSpace(strings.TrimPrefix(line, "data:")) + if payload == "" || payload == "[DONE]" { + continue + } + var chunk struct { + Choices []struct { + Delta struct { + ToolCalls []struct { + Function struct { + Arguments string `json:"arguments"` + } `json:"function"` + } `json:"tool_calls"` + } `json:"delta"` + } `json:"choices"` + } + if json.Unmarshal([]byte(payload), &chunk) != nil { + continue + } + for _, choice := range chunk.Choices { + for _, call := range choice.Delta.ToolCalls { + arguments = append(arguments, call.Function.Arguments) + } + } + } + if len(arguments) != 2 || arguments[0] != `{"path":"a"}` || arguments[1] != `{"path":"b"}` { + t.Fatalf("arguments = %#v", arguments) + } +} + +func TestRelayOpenAIStreamCanonicalRequiredWithoutCallFailsWithoutDone(t *testing.T) { + request := canonicalRequest(t, `[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`, `"required"`) + body := "data: {\"choices\":[{\"delta\":{\"content\":\"no tool\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n" + recorder := httptest.NewRecorder() + stats, err := RelayOpenAIStream(recorder, strings.NewReader(body), request) + if err == nil { + t.Fatalf("expected required-choice violation; body=%s", recorder.Body.String()) + } + if strings.Contains(recorder.Body.String(), "data: [DONE]") { + t.Fatalf("failure must not synthesize [DONE]: %s", recorder.Body.String()) + } + if stats.DownstreamDone { + t.Fatalf("stats = %+v", stats) + } +} + +func TestRelayOpenAIStreamCanonicalTruncatedArgumentsFail(t *testing.T) { + request := canonicalRequest(t, `[{"type":"function","function":{"name":"run","parameters":{"type":"object","properties":{"cmd":{"type":"string"}},"required":["cmd"]}}}]`, "") + body := "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"run\",\"arguments\":\"{\\\"cmd\\\":\\\"rm -rf\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n" + recorder := httptest.NewRecorder() + _, err := RelayOpenAIStream(recorder, strings.NewReader(body), request) + if err == nil { + t.Fatal("expected truncated arguments to fail") + } + if strings.Contains(recorder.Body.String(), `"finish_reason":"tool_calls"`) { + t.Fatalf("failure must not emit a success finish: %s", recorder.Body.String()) + } +} + +func TestRelayAnthropicStreamCanonicalBuffersToolBlocksUntilValid(t *testing.T) { + request := canonicalRequest(t, `[{"type":"function","function":{"name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}}]`, "") + body := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read_file","arguments":"{\"path\":"}}]}}]}`, + "", + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"\"a\"}"}}]},"finish_reason":"tool_calls"}]}`, + "", + "data: [DONE]", + "", + }, "\n") + recorder := httptest.NewRecorder() + stats, err := RelayAnthropicStream(recorder, strings.NewReader(body), "req", "model", request) + if err != nil { + t.Fatal(err) + } + if !stats.DownstreamDone { + t.Fatalf("stats = %+v", stats) + } + output := recorder.Body.String() + if !strings.Contains(output, `"id":"call_1"`) || !strings.Contains(output, `"name":"read_file"`) || !strings.Contains(output, `"partial_json":"{\"path\":\"a\"}"`) { + t.Fatalf("canonical tool block missing: %s", output) + } + if strings.Contains(output, "event: error") { + t.Fatalf("valid turn emitted an error: %s", output) + } +} + +func TestRelayResponsesStreamCanonicalKeepsCallIDAndArguments(t *testing.T) { + request, err := toolcall.ParseRequest(toolcall.ProtocolResponses, json.RawMessage(`[{"type":"function","name":"read_file","parameters":{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}}]`), nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + body := strings.Join([]string{ + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read_file","arguments":"{\"path\":"}}]}}]}`, + "", + `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"arguments":"\"a\"}"}}]},"finish_reason":"tool_calls"}]}`, + "", + "data: [DONE]", + "", + }, "\n") + recorder := httptest.NewRecorder() + stats, err := RelayResponsesStream(recorder, strings.NewReader(body), "req", "model", nil, request) + if err != nil { + t.Fatal(err) + } + if !stats.DownstreamDone || stats.FinishReason != "tool_calls" { + t.Fatalf("stats = %+v", stats) + } + output := recorder.Body.String() + if !strings.Contains(output, `"call_id":"call_1"`) || !strings.Contains(output, `"name":"read_file"`) || !strings.Contains(output, `"arguments":"{\"path\":\"a\"}"`) { + t.Fatalf("canonical Responses item missing: %s", output) + } + if strings.Contains(output, "event: error") { + t.Fatalf("valid turn emitted an error: %s", output) + } +} + +func TestRelayAnthropicStreamCanonicalChoiceNoneViolation(t *testing.T) { + request := canonicalRequest(t, `[{"type":"function","function":{"name":"read_file","parameters":{"type":"object"}}}]`, `"none"`) + body := "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read_file\",\"arguments\":\"{}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n" + recorder := httptest.NewRecorder() + stats, err := RelayAnthropicStream(recorder, strings.NewReader(body), "req", "model", request) + if err == nil { + t.Fatal("expected none-choice violation") + } + if stats.DownstreamDone { + t.Fatalf("stats = %+v", stats) + } + if !strings.Contains(recorder.Body.String(), "event: error") { + t.Fatalf("missing error event: %s", recorder.Body.String()) + } +} diff --git a/internal/gateway/usage.go b/internal/gateway/usage.go index 00496f2b1..e81f5bc50 100644 --- a/internal/gateway/usage.go +++ b/internal/gateway/usage.go @@ -59,5 +59,5 @@ func WriteClassifiedErr(w http.ResponseWriter, err error) { } else { w.Header().Set("X-Qoder-Failover", "0") } - writeErr(w, classified.Status, classified.Code, classified.Message) + writeTypedErr(w, classified.Status, openaiErrorType(classified), classified.Code, executor.PublicErrorMessage(classified)) } diff --git a/internal/logs/attempt_buffer_test.go b/internal/logs/attempt_buffer_test.go new file mode 100644 index 000000000..7cb663526 --- /dev/null +++ b/internal/logs/attempt_buffer_test.go @@ -0,0 +1,145 @@ +package logs + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +type orderPersister struct { + mu sync.Mutex + events []string + insertErr error +} + +func (p *orderPersister) add(event string) { + p.mu.Lock() + defer p.mu.Unlock() + p.events = append(p.events, event) +} + +func (p *orderPersister) InsertRequestLog(context.Context, accounts.RequestLog) error { + p.add("log") + p.mu.Lock() + defer p.mu.Unlock() + return p.insertErr +} +func (p *orderPersister) UpdateRequestLog(context.Context, accounts.RequestLog) error { + p.add("update") + return nil +} +func (p *orderPersister) InsertRequestAttempt(_ context.Context, attempt accounts.RequestAttempt) error { + p.add("attempt:" + attempt.ID) + return nil +} +func (p *orderPersister) InsertRequestStreamDiagnostic(context.Context, accounts.RequestStreamDiagnostic) error { + return nil +} +func (p *orderPersister) InsertRequestUsageDetail(context.Context, accounts.RequestUsageDetail) error { + return nil +} +func (p *orderPersister) PurgeRequestLogs(context.Context, time.Duration, int) (int64, error) { + return 0, nil +} +func (p *orderPersister) ExpireRequestLogDetail(context.Context, time.Duration) (int64, error) { + return 0, nil +} + +// An attempt from an aggregation classifier can be recorded before Prepare +// starts the parent log. It must wait for the parent row instead of failing +// the request_attempts foreign key. +func TestAttemptBeforeStartWaitsForParentLog(t *testing.T) { + p := &orderPersister{} + recorder := NewRequestRecorder(p) + recorder.Attempt(accounts.RequestAttempt{ + ID: "att-1", RequestID: "req-1", AttemptIndex: 0, Status: accounts.AttemptStatusOK, StartedAt: time.Now(), + }) + recorder.Start(accounts.RequestLog{ID: "req-1", CreatedAt: time.Now(), Status: accounts.RequestStatusStarted}) + recorder.Close() + + p.mu.Lock() + defer p.mu.Unlock() + if len(p.events) != 2 || p.events[0] != "log" || p.events[1] != "attempt:att-1" { + t.Fatalf("events = %v", p.events) + } +} + +// A completed request id must not stay in memory forever. Finish cannot delete +// it (the stream may still write its last attempt), so expiry is the fallback. +func TestAttemptBufferExpiresCompletedRequestIDs(t *testing.T) { + old := attemptBufferTTL + attemptBufferTTL = 20 * time.Millisecond + defer func() { attemptBufferTTL = old }() + + recorder := NewRequestRecorder(&orderPersister{}) + for i := 0; i < 8; i++ { + id := fmt.Sprintf("req-%d", i) + recorder.Start(accounts.RequestLog{ID: id, CreatedAt: time.Now(), Status: accounts.RequestStatusStarted}) + recorder.Finish(accounts.RequestLog{ID: id, CreatedAt: time.Now(), Status: accounts.RequestStatusOK}) + } + recorder.Close() + time.Sleep(2 * attemptBufferTTL) + if got := recorder.attemptBufferSize(); got != 0 { + t.Fatalf("retained %d completed request ids after expiry", got) + } +} + +// A classifier attempt dispatched to a request whose Prepare never starts has +// no parent row and no Finish. It must be dropped on expiry, and a failed +// parent insert must drop it immediately because the foreign key can never be +// satisfied. +func TestAttemptBufferDropsPendingWhenParentNeverStarts(t *testing.T) { + old := attemptBufferTTL + attemptBufferTTL = 20 * time.Millisecond + defer func() { attemptBufferTTL = old }() + + p := &orderPersister{insertErr: errors.New("insert failed")} + recorder := NewRequestRecorder(p) + recorder.Attempt(accounts.RequestAttempt{ID: "att-orphan", RequestID: "req-orphan", Status: accounts.AttemptStatusOK, StartedAt: time.Now()}) + recorder.Start(accounts.RequestLog{ID: "req-orphan", CreatedAt: time.Now(), Status: accounts.RequestStatusStarted}) + recorder.Close() + time.Sleep(2 * attemptBufferTTL) + if got := recorder.attemptBufferSize(); got != 0 { + t.Fatalf("retained %d pending attempts after failed parent insert", got) + } +} + +// The stream path can write its main log before the final attempt. That +// attempt must still be inserted after Finish, not dropped with the parent id. +func TestAttemptAfterFinishStillInserts(t *testing.T) { + p := &orderPersister{} + recorder := NewRequestRecorder(p) + recorder.Start(accounts.RequestLog{ID: "req-late", CreatedAt: time.Now(), Status: accounts.RequestStatusStarted}) + recorder.Finish(accounts.RequestLog{ID: "req-late", CreatedAt: time.Now(), Status: accounts.RequestStatusOK}) + recorder.Attempt(accounts.RequestAttempt{ID: "att-late", RequestID: "req-late", Status: accounts.AttemptStatusOK, StartedAt: time.Now()}) + recorder.Finalize("req-late") + recorder.Close() + + p.mu.Lock() + defer p.mu.Unlock() + found := false + for _, event := range p.events { + if event == "attempt:att-late" { + found = true + } + } + if !found { + t.Fatalf("late attempt not inserted: %v", p.events) + } +} + +func TestFinalizeReleasesCompletedRequestID(t *testing.T) { + recorder := NewRequestRecorder(&orderPersister{}) + recorder.Start(accounts.RequestLog{ID: "req-final", CreatedAt: time.Now(), Status: accounts.RequestStatusStarted}) + recorder.Finish(accounts.RequestLog{ID: "req-final", CreatedAt: time.Now(), Status: accounts.RequestStatusOK}) + recorder.Finalize("req-final") + recorder.Close() + if got := recorder.attemptBufferSize(); got != 0 { + t.Fatalf("Finalize retained %d request ids", got) + } +} diff --git a/internal/logs/recent_completions_test.go b/internal/logs/recent_completions_test.go index 3121d033d..31aa27492 100644 --- a/internal/logs/recent_completions_test.go +++ b/internal/logs/recent_completions_test.go @@ -14,7 +14,7 @@ func TestDrainRecentCompletions(t *testing.T) { r.Finish(accounts.RequestLog{AccountID: "a1", Status: accounts.RequestStatusOK}) r.Finish(accounts.RequestLog{AccountID: "a2", Status: accounts.RequestStatusError}) r.Finish(accounts.RequestLog{AccountID: "a3", Status: accounts.RequestStatusStreaming}) // ignored - r.Finish(accounts.RequestLog{AccountID: "", Status: accounts.RequestStatusError}) // ignored + r.Finish(accounts.RequestLog{AccountID: "", Status: accounts.RequestStatusError}) // ignored got := r.DrainRecentCompletions() if len(got) != 2 { diff --git a/internal/logs/recorder.go b/internal/logs/recorder.go index 6f523fc7a..a1a907653 100644 --- a/internal/logs/recorder.go +++ b/internal/logs/recorder.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/caigee-cmd/cli2api/internal/accounts" @@ -117,6 +118,22 @@ type RequestStore interface { RequestQuery } +type attemptBuffer struct { + declared bool + started bool + touched time.Time + pending []accounts.RequestAttempt +} + +// attemptBufferTTL bounds the in-memory attempt buffer. It is deliberately +// longer than any normal request: an entry must survive until the parent row +// exists (classifier before Prepare) or until a late terminal attempt arrives. +// After that the request can no longer produce child rows, so retaining the id +// only leaks memory in a long-running process. +// attemptBufferTTL bounds the in-memory attempt buffer. It is a variable so +// tests can exercise expiry without sleeping for the production window. +var attemptBufferTTL = 30 * time.Minute + type statsCacheEntry struct { stats accounts.RequestStats expiresAt time.Time @@ -190,6 +207,16 @@ type RequestRecorder struct { recent []RecentCompletion openMu sync.Mutex open map[string]*OpenRequest + // Attempts can be produced by an aggregation classifier before Prepare + // starts the parent request log. SQLite enforces the request_attempts -> + // request_logs foreign key, so those attempts are buffered per request id + // and inserted immediately after the parent row. Entries are expiry-based: + // Finish cannot delete them because a stream may write its last attempt + // after the main log row. A request whose Prepare never starts never + // reaches Finish either, so pending entries need the same sweep. + attemptMu sync.Mutex + attemptBuffers map[string]*attemptBuffer + attemptSeq int64 } func NewRequestRecorder(store RequestPersister) *RequestRecorder { @@ -241,13 +268,120 @@ func (r *RequestRecorder) Close() { func (r *RequestRecorder) Start(log accounts.RequestLog) { r.rateCounter().Add() r.noteOpen(log) + r.markDeclared(log.ID) r.enqueue(func() { if err := r.store.InsertRequestLog(context.Background(), log); err != nil { logf("insert request log: %v", err) + // The parent row never exists, so buffered child rows can never + // satisfy the foreign key. Dropping them here is the only correct + // outcome; a later retry of the request gets a fresh id. + r.dropAttemptBuffer(log.ID) + return } + r.flushPendingAttempts(log.ID) }) } +func (r *RequestRecorder) markDeclared(requestID string) { + if r == nil || requestID == "" { + return + } + r.attemptMu.Lock() + defer r.attemptMu.Unlock() + r.pruneAttemptBuffersLocked(time.Now()) + if r.attemptBuffers == nil { + r.attemptBuffers = map[string]*attemptBuffer{} + } + entry := r.attemptBuffers[requestID] + if entry == nil { + entry = &attemptBuffer{} + r.attemptBuffers[requestID] = entry + } + entry.declared = true + entry.touched = time.Now() +} + +// WasDeclared reports whether a request log row was requested for this id. +// Entry-level rejections use it to avoid writing a second row for a request +// that already reached Prepare. +func (r *RequestRecorder) WasDeclared(requestID string) bool { + if r == nil || requestID == "" { + return false + } + r.attemptMu.Lock() + defer r.attemptMu.Unlock() + r.pruneAttemptBuffersLocked(time.Now()) + entry := r.attemptBuffers[requestID] + return entry != nil && entry.declared +} + +func (r *RequestRecorder) dropAttemptBuffer(requestID string) { + if r == nil || requestID == "" { + return + } + r.attemptMu.Lock() + delete(r.attemptBuffers, requestID) + r.attemptMu.Unlock() +} + +// Finalize releases the per-request buffer once the handler has enqueued both +// the main log update and the final attempt. It runs on the same FIFO queue, +// so it cannot overtake an attempt recorded after Finish. TTL remains as the +// fallback for a request whose handler dies before Finalize (for example a +// classifier dispatched for a Prepare that never starts). +func (r *RequestRecorder) Finalize(requestID string) { + if r == nil || requestID == "" { + return + } + r.enqueue(func() { r.dropAttemptBuffer(requestID) }) +} + +// flushPendingAttempts marks the parent log durable and inserts any attempts +// that were recorded before it (for example classifier sub-calls that ran +// during aggregation resolution). +func (r *RequestRecorder) flushPendingAttempts(requestID string) { + r.attemptMu.Lock() + r.pruneAttemptBuffersLocked(time.Now()) + if r.attemptBuffers == nil { + r.attemptBuffers = map[string]*attemptBuffer{} + } + entry := r.attemptBuffers[requestID] + if entry == nil { + entry = &attemptBuffer{declared: true} + r.attemptBuffers[requestID] = entry + } + entry.started = true + entry.touched = time.Now() + pending := entry.pending + entry.pending = nil + r.attemptMu.Unlock() + for _, attempt := range pending { + if err := r.store.InsertRequestAttempt(context.Background(), attempt); err != nil { + logf("insert request attempt: %v", err) + } + } +} + +func (r *RequestRecorder) pruneAttemptBuffersLocked(now time.Time) { + for id, entry := range r.attemptBuffers { + if entry == nil || now.Sub(entry.touched) > attemptBufferTTL { + delete(r.attemptBuffers, id) + } + } +} + +// attemptBufferSize exposes the number of retained request ids for tests in +// this package. It is not part of the operational surface. +func (r *RequestRecorder) attemptBufferSize() int { + if r == nil { + return 0 + } + r.attemptMu.Lock() + defer r.attemptMu.Unlock() + r.pruneAttemptBuffersLocked(time.Now()) + return len(r.attemptBuffers) +} + func (r *RequestRecorder) rateCounter() *RateCounter { if r == nil { return nil @@ -517,7 +651,37 @@ func (r *RequestRecorder) trimOpenLocked() { } func (r *RequestRecorder) Attempt(attempt accounts.RequestAttempt) { + if r == nil { + return + } + // Sequence is assigned at record time, before the async queue, so classifier + // sub-calls and the main route keep a stable total order even when both + // carry AttemptIndex 0. + if attempt.Sequence <= 0 { + attempt.Sequence = atomic.AddInt64(&r.attemptSeq, 1) + } r.enqueue(func() { + requestID := attempt.RequestID + if requestID != "" { + r.attemptMu.Lock() + r.pruneAttemptBuffersLocked(time.Now()) + if r.attemptBuffers == nil { + r.attemptBuffers = map[string]*attemptBuffer{} + } + entry := r.attemptBuffers[requestID] + if entry == nil { + entry = &attemptBuffer{} + r.attemptBuffers[requestID] = entry + } + if !entry.started { + entry.pending = append(entry.pending, attempt) + entry.touched = time.Now() + r.attemptMu.Unlock() + return + } + entry.touched = time.Now() + r.attemptMu.Unlock() + } if err := r.store.InsertRequestAttempt(context.Background(), attempt); err != nil { logf("insert request attempt: %v", err) } diff --git a/internal/providers/kiro/tools_test.go b/internal/providers/kiro/tools_test.go index 9459dd4f9..573fef24f 100644 --- a/internal/providers/kiro/tools_test.go +++ b/internal/providers/kiro/tools_test.go @@ -14,6 +14,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/gateway" "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/toolcall" "github.com/caigee-cmd/cli2api/internal/translate" ) @@ -68,7 +69,11 @@ func TestCreateResponseToolStreamMatchesAnthropicMessages(t *testing.T) { } var anthropic strings.Builder - if _, err := gateway.RelayAnthropicStream(&anthropic, strings.NewReader(string(openai)), "req1", "claude-sonnet-4.5"); err != nil { + request, err := toolcall.ParseRequest(toolcall.ProtocolMessages, json.RawMessage(`[{"name":"Read","input_schema":{"type":"object"}},{"name":"Grep","input_schema":{"type":"object"}}]`), nil, nil, toolcall.RepairSafe) + if err != nil { + t.Fatal(err) + } + if _, err := gateway.RelayAnthropicStream(&anthropic, strings.NewReader(string(openai)), "req1", "claude-sonnet-4.5", request); err != nil { t.Fatal(err) } events := parseSSE(t, anthropic.String()) diff --git a/internal/quality/completeness.go b/internal/quality/completeness.go new file mode 100644 index 000000000..d9f0c54bc --- /dev/null +++ b/internal/quality/completeness.go @@ -0,0 +1,59 @@ +package quality + +// TerminalFacts mirrors the delivery facts the gateway already records for a +// request. The string values reuse the request_logs vocabulary +// (done/error/eof/none; ok/error) so classification has one source of truth. +type TerminalFacts struct { + UpstreamTerminal string + DownstreamTerminal string + FlushState string + SawDone bool + Status string + CancellationSource string +} + +// Verdict classifies one request's delivery completeness. It separates a +// client leaving early from an upstream cut-off or a lost terminal frame, so +// availability and loss-rate accounting do not treat every cancel as a +// gateway failure. +type Verdict string + +const ( + VerdictComplete Verdict = "complete" + VerdictTruncated Verdict = "truncated" + VerdictUpstreamEOF Verdict = "upstream_eof" + VerdictDeliveryLost Verdict = "delivery_lost" + VerdictClientCanceled Verdict = "client_canceled" + VerdictUnknown Verdict = "unknown" +) + +// ClassifyCompleteness derives the delivery verdict from terminal facts. The +// ordering matters: a client disconnect is not an upstream loss, and a +// downstream flush error outranks an otherwise clean upstream. +func ClassifyCompleteness(f TerminalFacts) Verdict { + switch { + case f.CancellationSource == "client_disconnect" || f.Status == "canceled": + return VerdictClientCanceled + case f.DownstreamTerminal == "error" || f.FlushState == "error": + return VerdictDeliveryLost + case f.UpstreamTerminal == "error": + return VerdictTruncated + case f.SawDone || f.DownstreamTerminal == "done" || f.UpstreamTerminal == "done": + return VerdictComplete + case f.UpstreamTerminal == "eof": + return VerdictUpstreamEOF + default: + return VerdictUnknown + } +} + +// Lost reports whether the verdict counts against availability or the loss +// rate. Client cancellations and unobserved outcomes are not gateway losses. +func (v Verdict) Lost() bool { + switch v { + case VerdictTruncated, VerdictUpstreamEOF, VerdictDeliveryLost: + return true + default: + return false + } +} diff --git a/internal/quality/doc.go b/internal/quality/doc.go new file mode 100644 index 000000000..444ce35d0 --- /dev/null +++ b/internal/quality/doc.go @@ -0,0 +1,19 @@ +// Package quality owns the gateway's quality model: the metric definitions, +// completeness verdict, bounded outcome sample, and the pure SLO gate +// evaluation. +// +// This package is a leaf utility: it imports only the standard library. It +// deliberately contains no HTTP, store, executor, or provider dependency so +// the same definitions can be exercised by gateway relay instrumentation, +// stats aggregation, and tests without crossing package boundaries. +// +// Metric vocabulary follows the mature LLM-serving terminology (IETF LLM +// benchmarking drafts, NVIDIA AIPerf, Bifrost gateway observability): +// +// - TTFT (time to first token): acceptance → first non-empty content token. +// - Head wait: acceptance → upstream response head (headers + first byte). +// - E2E latency: acceptance → terminal frame flushed. +// - Full-request output rate: completion tokens / E2E latency. +// - Decode-only output rate: tokens after the first / generation window. +// - TPOT: generation window / (output tokens − 1), seconds per output token. +package quality diff --git a/internal/quality/gate.go b/internal/quality/gate.go new file mode 100644 index 000000000..09efbf455 --- /dev/null +++ b/internal/quality/gate.go @@ -0,0 +1,128 @@ +package quality + +import ( + "os" + "strconv" + "strings" +) + +// Thresholds are the SLO budgets a route sample is evaluated against. Zero +// values disable the corresponding check. Defaults target an interactive +// streaming UX; operators can override them through environment variables. +type Thresholds struct { + // MaxTTFTMs is the P95 TTFT budget above which a route is degraded. + MaxTTFTMs int + // MaxTPOTMs is the per-token decode budget (documentation only; the gate + // uses AvgTPS for throughput). + MaxTPOTMs int + // MinTPS is the floor for average output throughput; below it the route + // is degraded. + MinTPS float64 + // MaxErrorRate is the failure-ratio ceiling above which the gate trips. + MaxErrorRate float64 + // MaxLossRate is the incompletion/delivery-loss ratio ceiling. + MaxLossRate float64 + // MinSample is the minimum observed requests before the gate draws a + // conclusion; smaller samples stay healthy rather than over-react. + MinSample int +} + +// DefaultThresholds returns the built-in budgets, adjusted by CLI2API_QUALITY_* +// environment variables when present and parseable. +func DefaultThresholds() Thresholds { + return Thresholds{ + MaxTTFTMs: envInt("CLI2API_QUALITY_MAX_TTFT_MS", 8000), + MaxTPOTMs: envInt("CLI2API_QUALITY_MAX_TPOT_MS", 100), + MinTPS: envFloat("CLI2API_QUALITY_MIN_TPS", 4.0), + MaxErrorRate: envRatio("CLI2API_QUALITY_MAX_ERROR_RATE", 0.10), + MaxLossRate: envRatio("CLI2API_QUALITY_MAX_LOSS_RATE", 0.05), + MinSample: envInt("CLI2API_QUALITY_MIN_SAMPLE", 20), + } +} + +// State is the gate verdict for a sampled route. +type State string + +const ( + StateHealthy State = "healthy" + StateDegraded State = "degraded" + StateTripped State = "tripped" +) + +// Report is the outcome of a gate evaluation: state plus human-readable +// reasons. Reasons are stable strings suitable for logs and tests. +type Report struct { + State State + Reasons []string +} + +// Evaluate compares a Snapshot against thresholds. It is pure: it performs no +// I/O and changes no state. Breaker/cooldown policy remains the executor's +// responsibility; this function only produces a verdict the routing layer may +// act on. +func Evaluate(snap Snapshot, th Thresholds) Report { + if snap.Requests < th.MinSample { + return Report{State: StateHealthy, Reasons: []string{"insufficient sample"}} + } + reasons := []string{} + + if snap.LossRate > th.MaxLossRate { + reasons = append(reasons, "loss rate above budget") + } + if snap.ErrorRate > th.MaxErrorRate { + reasons = append(reasons, "error rate above budget") + } + if len(reasons) > 0 { + return Report{State: StateTripped, Reasons: reasons} + } + + degraded := false + if th.MaxTTFTMs > 0 && snap.TTFTP95 != nil && *snap.TTFTP95 > th.MaxTTFTMs { + reasons = append(reasons, "ttft p95 above budget") + degraded = true + } + if th.MinTPS > 0 && snap.AvgTPS < th.MinTPS { + reasons = append(reasons, "output throughput below floor") + degraded = true + } + if degraded { + return Report{State: StateDegraded, Reasons: reasons} + } + return Report{State: StateHealthy, Reasons: []string{"within budget"}} +} + +func envInt(key string, fallback int) int { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return fallback + } + value, err := strconv.Atoi(raw) + if err != nil || value <= 0 { + return fallback + } + return value +} + +func envFloat(key string, fallback float64) float64 { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return fallback + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil || value <= 0 { + return fallback + } + return value +} + +func envRatio(key string, fallback float64) float64 { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return fallback + } + value, err := strconv.ParseFloat(raw, 64) + if err != nil || value < 0 { + return fallback + } + return value +} diff --git a/internal/quality/quality_test.go b/internal/quality/quality_test.go new file mode 100644 index 000000000..08775dcea --- /dev/null +++ b/internal/quality/quality_test.go @@ -0,0 +1,195 @@ +package quality + +import ( + "testing" + "time" +) + +func TestTimelineDerivedDurations(t *testing.T) { + started := time.Date(2026, 12, 4, 10, 0, 0, 0, time.UTC) + tl := Timeline{ + StartedAt: started, + HeadAt: started.Add(120 * time.Millisecond), + FirstTokenAt: started.Add(350 * time.Millisecond), + FinishedAt: started.Add(2 * time.Second), + } + + if d, ok := tl.HeadWait(); !ok || d != 120*time.Millisecond { + t.Errorf("HeadWait = %v, %v", d, ok) + } + if d, ok := tl.TTFT(); !ok || d != 350*time.Millisecond { + t.Errorf("TTFT = %v, %v", d, ok) + } + if d, ok := tl.Latency(); !ok || d != 2*time.Second { + t.Errorf("Latency = %v, %v", d, ok) + } + + var zero Timeline + if _, ok := zero.TTFT(); ok { + t.Error("zero timeline must report unobserved TTFT") + } +} + +func TestThroughputHelpers(t *testing.T) { + started := time.Date(2026, 12, 4, 10, 0, 0, 0, time.UTC) + first := started.Add(400 * time.Millisecond) + finished := started.Add(2 * time.Second) + + if got := FullTPS(100, 2*time.Second); got != 50 { + t.Errorf("FullTPS = %v, want 50", got) + } + if got := DecodeTPS(101, first, finished); got <= 0 { + t.Errorf("DecodeTPS = %v, want positive", got) + } + if got := TPOT(101, first, finished); got <= 0 { + t.Errorf("TPOT = %v, want positive", got) + } + // Fewer than two output tokens carry no decode window. + if got := DecodeTPS(1, first, finished); got != 0 { + t.Errorf("DecodeTPS single token = %v, want 0", got) + } + if got := TPOT(1, first, finished); got != 0 { + t.Errorf("TPOT single token = %v, want 0", got) + } +} + +func TestCompletenessClassification(t *testing.T) { + cases := []struct { + name string + in TerminalFacts + want Verdict + }{ + {"client disconnect is not loss", TerminalFacts{CancellationSource: "client_disconnect"}, VerdictClientCanceled}, + {"downstream flush error is delivery lost", TerminalFacts{DownstreamTerminal: "error", FlushState: "error"}, VerdictDeliveryLost}, + {"upstream error truncates", TerminalFacts{UpstreamTerminal: "error"}, VerdictTruncated}, + {"saw done completes", TerminalFacts{SawDone: true}, VerdictComplete}, + {"downstream done completes", TerminalFacts{DownstreamTerminal: "done"}, VerdictComplete}, + {"upstream done completes", TerminalFacts{UpstreamTerminal: "done"}, VerdictComplete}, + {"bare eof is upstream eof", TerminalFacts{UpstreamTerminal: "eof"}, VerdictUpstreamEOF}, + {"nothing observed unknown", TerminalFacts{}, VerdictUnknown}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := ClassifyCompleteness(tc.in); got != tc.want { + t.Errorf("ClassifyCompleteness = %v, want %v", got, tc.want) + } + }) + } +} + +func TestLostVerdicts(t *testing.T) { + lost := []Verdict{VerdictTruncated, VerdictUpstreamEOF, VerdictDeliveryLost} + for _, v := range lost { + if !v.Lost() { + t.Errorf("%v should count as lost", v) + } + } + notLost := []Verdict{VerdictComplete, VerdictClientCanceled, VerdictUnknown} + for _, v := range notLost { + if v.Lost() { + t.Errorf("%v should not count as lost", v) + } + } +} + +func TestSampleRatesAndPercentiles(t *testing.T) { + s := NewSample(8) + outcomes := []Outcome{ + {LatencyMs: 100, TTFTMs: 80, TPS: 10, OK: true}, + {LatencyMs: 200, TTFTMs: 90, TPS: 12, OK: true}, + {LatencyMs: 300, TTFTMs: 100, TPS: 8, Errored: true}, + {LatencyMs: 400, TTFTMs: 110, TPS: 6, Lost: true}, + } + for _, o := range outcomes { + s.Observe(o) + } + snap := s.Snapshot() + if snap.Requests != 4 { + t.Errorf("Requests = %d, want 4", snap.Requests) + } + if snap.OK != 2 { + t.Errorf("OK = %d, want 2", snap.OK) + } + if snap.Errored != 1 { + t.Errorf("Errored = %d, want 1", snap.Errored) + } + if snap.Lost != 1 { + t.Errorf("Lost = %d, want 1", snap.Lost) + } + if snap.SuccessRate != 0.5 { + t.Errorf("SuccessRate = %v, want 0.5", snap.SuccessRate) + } + if snap.ErrorRate != 0.25 { + t.Errorf("ErrorRate = %v, want 0.25", snap.ErrorRate) + } + if snap.LossRate != 0.25 { + t.Errorf("LossRate = %v, want 0.25", snap.LossRate) + } + if snap.LatencyP50 == nil || *snap.LatencyP50 != 300 { + t.Errorf("LatencyP50 = %v, want 300", snap.LatencyP50) + } + if snap.TTFTP95 == nil || *snap.TTFTP95 != 110 { + t.Errorf("TTFTP95 = %v, want 110", snap.TTFTP95) + } + if snap.AvgTPS != 9 { + t.Errorf("AvgTPS = %v, want 9", snap.AvgTPS) + } +} + +func TestSampleRingOverwrite(t *testing.T) { + s := NewSample(3) + for i := 0; i < 5; i++ { + s.Observe(Outcome{LatencyMs: i + 1}) + } + snap := s.Snapshot() + if snap.Requests != 3 { + t.Errorf("Requests = %d, want ring capacity 3", snap.Requests) + } +} + +func TestGateInsufficientSampleStaysHealthy(t *testing.T) { + th := DefaultThresholds() + report := Evaluate(Snapshot{Requests: 3}, th) + if report.State != StateHealthy { + t.Errorf("State = %v, want healthy", report.State) + } +} + +func TestGateTripsOnLoss(t *testing.T) { + th := DefaultThresholds() + snap := Snapshot{Requests: 30, Lost: 6, LossRate: 0.2, OK: 24} + report := Evaluate(snap, th) + if report.State != StateTripped { + t.Errorf("State = %v, want tripped", report.State) + } +} + +func TestGateTripsOnError(t *testing.T) { + th := DefaultThresholds() + snap := Snapshot{Requests: 30, Errored: 9, ErrorRate: 0.3, OK: 21} + report := Evaluate(snap, th) + if report.State != StateTripped { + t.Errorf("State = %v, want tripped", report.State) + } +} + +func TestGateDegradedOnSlowTTFT(t *testing.T) { + th := DefaultThresholds() + ttft := 9_000 + snap := Snapshot{Requests: 30, OK: 30, TTFTP95: &ttft, AvgTPS: 10} + report := Evaluate(snap, th) + if report.State != StateDegraded { + t.Errorf("State = %v, want degraded", report.State) + } +} + +func TestGateHealthyWithinBudget(t *testing.T) { + th := DefaultThresholds() + snap := Snapshot{Requests: 30, OK: 30, AvgTPS: 10} + ttft := 500 + snap.TTFTP95 = &ttft + report := Evaluate(snap, th) + if report.State != StateHealthy { + t.Errorf("State = %v, reasons %v", report.State, report.Reasons) + } +} diff --git a/internal/quality/sample.go b/internal/quality/sample.go new file mode 100644 index 000000000..aafa342e6 --- /dev/null +++ b/internal/quality/sample.go @@ -0,0 +1,148 @@ +package quality + +import ( + "sort" + "sync" +) + +// Outcome is one request's quality-relevant result. Zero values are treated +// as unobserved, so a partially populated outcome never biases an aggregate. +type Outcome struct { + LatencyMs int + TTFTMs int + TPS float64 + OK bool + Errored bool + Lost bool +} + +// Sample is a thread-safe bounded ring of recent outcomes. It is in-memory +// only: a restart resets it, mirroring the live rate counter in logs. The +// capacity bounds memory; oldest observations are overwritten. +type Sample struct { + mu sync.Mutex + cap int + ring []Outcome + head int + n int +} + +// NewSample returns a Sample holding at most capacity outcomes. A non-positive +// capacity falls back to 256. +func NewSample(capacity int) *Sample { + if capacity <= 0 { + capacity = 256 + } + return &Sample{cap: capacity, ring: make([]Outcome, capacity)} +} + +// Observe records one outcome. +func (s *Sample) Observe(o Outcome) { + if s == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + s.ring[s.head] = o + s.head = (s.head + 1) % s.cap + if s.n < s.cap { + s.n++ + } +} + +// Snapshot is the aggregated quality view over the sampled window. +type Snapshot struct { + Requests int + OK int + Errored int + Lost int + SuccessRate float64 + ErrorRate float64 + LossRate float64 + LatencyP50 *int + LatencyP95 *int + TTFTP50 *int + TTFTP95 *int + AvgTPS float64 +} + +// Snapshot reduces the ring to rates and nearest-rank percentiles. Nil +// percentiles mean no sample was observed for that series. +func (s *Sample) Snapshot() Snapshot { + if s == nil { + return Snapshot{} + } + s.mu.Lock() + defer s.mu.Unlock() + + snap := Snapshot{Requests: s.n} + if s.n == 0 { + return snap + } + var latencies, ttfts []int + var tpsSum float64 + for i := 0; i < s.n; i++ { + o := s.ring[(s.head-1-i+s.cap)%s.cap] + switch { + case o.OK: + snap.OK++ + case o.Errored: + snap.Errored++ + } + if o.Lost { + snap.Lost++ + } + if o.LatencyMs > 0 { + latencies = append(latencies, o.LatencyMs) + } + if o.TTFTMs > 0 { + ttfts = append(ttfts, o.TTFTMs) + } + if o.TPS > 0 { + tpsSum += o.TPS + } + } + snap.SuccessRate = ratio(snap.OK, snap.Requests) + snap.ErrorRate = ratio(snap.Errored, snap.Requests) + snap.LossRate = ratio(snap.Lost, snap.Requests) + if len(latencies) > 0 { + snap.LatencyP50 = percentile(latencies, 50) + snap.LatencyP95 = percentile(latencies, 95) + } + if len(ttfts) > 0 { + snap.TTFTP50 = percentile(ttfts, 50) + snap.TTFTP95 = percentile(ttfts, 95) + } + if snap.Requests > 0 { + snap.AvgTPS = tpsSum / float64(snap.Requests) + } + return snap +} + +func ratio(numerator, total int) float64 { + if total <= 0 { + return 0 + } + return float64(numerator) / float64(total) +} + +func percentile(values []int, rank int) *int { + if len(values) == 0 { + return nil + } + sorted := make([]int, len(values)) + copy(sorted, values) + sort.Ints(sorted) + if rank <= 0 { + return &sorted[0] + } + if rank >= 100 { + return &sorted[len(sorted)-1] + } + idx := rank * len(sorted) / 100 + if idx >= len(sorted) { + idx = len(sorted) - 1 + } + out := sorted[idx] + return &out +} diff --git a/internal/quality/timing.go b/internal/quality/timing.go new file mode 100644 index 000000000..7a6738c8c --- /dev/null +++ b/internal/quality/timing.go @@ -0,0 +1,82 @@ +package quality + +import "time" + +// Timeline captures the gateway-observed wall-clock events for one request. +// A zero time means the event was not observed; every derived report returns +// ok=false rather than a misleading zero duration. +type Timeline struct { + // StartedAt is when the gateway accepted the public request. + StartedAt time.Time + // HeadAt is when the upstream response head (headers + first byte) arrived. + HeadAt time.Time + // FirstTokenAt is when the first non-empty content token was relayed. + FirstTokenAt time.Time + // FinishedAt is when the terminal frame was flushed / the stream closed. + FinishedAt time.Time +} + +// HeadWait is the queue + connect + prefill wait up to the upstream head. It +// is separate from TTFT: a proxy may return 200 and then black-hole the body. +func (t Timeline) HeadWait() (time.Duration, bool) { + if t.StartedAt.IsZero() || t.HeadAt.IsZero() { + return 0, false + } + return t.HeadAt.Sub(t.StartedAt), true +} + +// TTFT is the wait from acceptance to the first non-empty content token. It is +// the dominant perceived-latency signal for streaming UIs. +func (t Timeline) TTFT() (time.Duration, bool) { + if t.StartedAt.IsZero() || t.FirstTokenAt.IsZero() { + return 0, false + } + return t.FirstTokenAt.Sub(t.StartedAt), true +} + +// Latency is the full end-to-end wall-clock duration. +func (t Timeline) Latency() (time.Duration, bool) { + if t.StartedAt.IsZero() || t.FinishedAt.IsZero() { + return 0, false + } + return t.FinishedAt.Sub(t.StartedAt), true +} + +// FullTPS is the full-request output rate: completion tokens divided by the +// end-to-end latency window. It includes TTFT and queue wait, matching the +// "full-request output rate" definition in the LLM serving benchmarks. +func FullTPS(completionTokens int, latency time.Duration) float64 { + if completionTokens <= 0 || latency <= 0 { + return 0 + } + return float64(completionTokens) / latency.Seconds() +} + +// DecodeTPS is the decode-only output rate: tokens after the first divided by +// the generation window (first token → finish). It isolates decode smoothness +// from prefill and queue stalls. +func DecodeTPS(completionTokens int, firstTokenAt, finishedAt time.Time) float64 { + after := completionTokens - 1 + if after <= 0 { + return 0 + } + window := finishedAt.Sub(firstTokenAt) + if window <= 0 { + return 0 + } + return float64(after) / window.Seconds() +} + +// TPOT is time per output token over the decode window, in seconds/token. It +// is the request-level average counterpart to per-token inter-token latency. +func TPOT(completionTokens int, firstTokenAt, finishedAt time.Time) float64 { + after := completionTokens - 1 + if after <= 0 { + return 0 + } + window := finishedAt.Sub(firstTokenAt) + if window <= 0 { + return 0 + } + return window.Seconds() / float64(after) +} diff --git a/internal/runtime/checkin_status_test.go b/internal/runtime/checkin_status_test.go index f2d434cb9..0292bf0f9 100644 --- a/internal/runtime/checkin_status_test.go +++ b/internal/runtime/checkin_status_test.go @@ -186,11 +186,15 @@ func TestSyncCheckinStatusDoesNotOverwriteCheckinFinishedDuringProbe(t *testing. } func TestSyncCheckinStatusUnknownKeepsRealLocalSuccess(t *testing.T) { + oldNow := checkinStatusNow + fakeNow := time.Date(2026, 1, 2, 12, 0, 0, 0, time.UTC) + checkinStatusNow = func() time.Time { return fakeNow } + defer func() { checkinStatusNow = oldNow }() manager, account := newStatusManager(t, checkinStatusFunc(func(context.Context, string) (providers.CheckinResult, error) { // A provisional rollover answer: the provider cannot yet confirm today. return providers.CheckinResult{Status: "unknown", Message: "上游日界尚未确认,稍后复核", EarliestCheckin: "00:00"}, nil })) - old := time.Now().UTC().Add(-2 * time.Hour) + old := fakeNow.Add(-2 * time.Hour) if err := manager.store.RecordCheckin(context.Background(), account.ID, "success", "claimed earlier", old); err != nil { t.Fatal(err) } diff --git a/internal/runtime/manager_catalog.go b/internal/runtime/manager_catalog.go index 1bbc61496..85d4ed6a6 100644 --- a/internal/runtime/manager_catalog.go +++ b/internal/runtime/manager_catalog.go @@ -86,6 +86,7 @@ func (m *Manager) fetchAccountModels(ctx context.Context, item Item) { } m.pool.MergeModelsWithPricing(item.ID, qoder.CatalogIDsFromInfos(models), qoder.FreeCatalogIDsFromInfos(models)) m.pool.MergeNativeModels(item.ID, qoder.NativeCatalogIDsFromInfos(models)) + m.pool.MergeModelToolSupport(item.ID, noToolModelIDs(models)) return } client := qoder.WorkerClient{ @@ -142,4 +143,19 @@ func (m *Manager) fetchProviderModels(ctx context.Context, item Item) { ids = append(ids, model.PublicModel, model.NativeModel, model.DisplayName) } m.pool.MergeModels(item.ID, ids) + m.pool.MergeModelToolSupport(item.ID, noToolModelIDs(models)) +} + +// noToolModelIDs returns every catalog spelling for models whose entry does +// not advertise Tools. Providers build ModelInfo from their live catalog, so +// `Tools: false` is treated as an explicit negative fact rather than unknown. +func noToolModelIDs(models []providers.ModelInfo) []string { + noTools := make([]string, 0, len(models)) + for _, model := range models { + if model.Capabilities.Tools { + continue + } + noTools = append(noTools, model.PublicModel, model.NativeModel, model.DisplayName) + } + return noTools } diff --git a/internal/runtime/manager_fefo.go b/internal/runtime/manager_fefo.go index 767396925..d45dbab16 100644 --- a/internal/runtime/manager_fefo.go +++ b/internal/runtime/manager_fefo.go @@ -5,12 +5,30 @@ import ( "time" ) -// RefreshFEFOQuotaAfterUse invalidates a trusted credit balance after the whole -// response (including an SSE body) finishes. It never waits on upstream quota in -// the request path. Concurrent completions share one fetch; a completion during -// that fetch requests one trailing fetch so its consumption is not lost. +// RefreshFEFOQuotaAfterUse is the legacy entry point for a public model under +// the global FEFO strategy. func (m *Manager) RefreshFEFOQuotaAfterUse(accountID, publicModel string) { - if m == nil || m.pool == nil || m.runCtx == nil || !m.pool.HasFEFOQuota(accountID, publicModel) { + if m == nil || m.pool == nil || !m.pool.HasFEFOQuota(accountID, publicModel) { + return + } + m.queueFEFOQuotaAfterUse(accountID) +} + +// RefreshRouteQuotaAfterUse requests an asynchronous refresh after the whole +// response (including any SSE body) finishes. The model key and aggregate +// FEFO flag describe the actual dispatch, not the public model or other seats. +func (m *Manager) RefreshRouteQuotaAfterUse(accountID, concreteModel string, aggregateFEFO bool) { + if m == nil || m.pool == nil || !m.pool.HasRouteFEFOQuota(accountID, concreteModel, aggregateFEFO) { + return + } + m.queueFEFOQuotaAfterUse(accountID) +} + +// Admission is per completion; fetching and coalescing are per account. An +// admitted completion during a fetch requests one trailing fetch, even if its +// model or strategy differs from the one that started the worker. +func (m *Manager) queueFEFOQuotaAfterUse(accountID string) { + if m.runCtx == nil { return } m.mu.Lock() @@ -33,7 +51,7 @@ func (m *Manager) RefreshFEFOQuotaAfterUse(accountID, publicModel string) { go func() { defer m.quotaAfterUseDone.Done() for { - if item, ok := m.pool.ByID(accountID); ok && m.pool.HasFEFOQuota(accountID, publicModel) { + if item, ok := m.pool.FEFOQuotaAccount(accountID); ok { ctx, cancel := context.WithTimeout(m.runCtx, 10*time.Second) m.refreshQuotaOnly(ctx, item) cancel() diff --git a/internal/runtime/manager_fefo_test.go b/internal/runtime/manager_fefo_test.go index 8b2a17f8b..08443b785 100644 --- a/internal/runtime/manager_fefo_test.go +++ b/internal/runtime/manager_fefo_test.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "net/http" "path/filepath" "sync/atomic" "testing" @@ -11,6 +12,7 @@ import ( "github.com/caigee-cmd/cli2api/internal/executor" "github.com/caigee-cmd/cli2api/internal/providers" sqlstore "github.com/caigee-cmd/cli2api/internal/store" + "github.com/caigee-cmd/cli2api/internal/translate" ) type fefoRefreshProber struct { @@ -121,6 +123,81 @@ func TestFEFOCompletionRefreshSkipsHistoricalStrategiesAndFreeRoutes(t *testing. } } +type fefoRefreshChat struct{ accountID, model string } + +func (p *fefoRefreshChat) ChatNonStream(_ context.Context, accountID string, req translate.ChatRequest) (providers.ChatOutcome, error) { + p.accountID, p.model = accountID, req.Model + return providers.ChatOutcome{Model: "free", Content: "ok"}, nil +} + +func (*fefoRefreshChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, providers.ErrUnsupported +} + +func TestRouteFEFOCompletionRefreshUsesSelectedAggregatePath(t *testing.T) { + m, id, p := newFEFORefreshFixture(t) + m.pool.SetRoutingStrategy(accounts.RoutingStrategyFillFirst) + item, _ := m.pool.ByID(id) + item.ModelAliases = map[string]string{"alias": "paid", "paid": "free"} + item.NativeModels = map[string]string{"paid": "native-paid-key"} + m.pool.Upsert(item) + close(p.release) + chat := &fefoRefreshChat{} + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat, Prober: p}) + m.SetProviders(registry) + exec := executor.NewChatExecutor(m.pool, "") + exec.Providers = registry + + // Both seats send the same real model to the same account, but only the + // second seat enters a FEFO subtree. The model name alone cannot opt in. + const public = "bundle" + member := accounts.AggregationMember{Provider: "workbuddy", Region: "cn", Model: "alias"} + plan := executor.NewAggregatePlan(accounts.Aggregation{ID: public, Strategy: accounts.AggregationRoundRobin}) + plan.Seats = []accounts.RouteSeat{ + {ID: "direct", Kind: "member", Member: member}, + {ID: "group", Kind: "group", GroupID: "inner", GroupStrategy: accounts.AggregationFEFOStrategy, GroupMembers: []accounts.AggregationMember{member}}, + } + for i, wantFEFO := range []bool{false, true} { + result, err := exec.ChatNonStreamPrepared(t.Context(), translate.ChatRequest{Model: public}, executor.RouteInput{PublicModel: public, RouteModel: public, AggregatePlan: plan}) + if err != nil { + t.Fatal(err) + } + if chat.accountID != id || chat.model != "native-paid-key" || result.PoolAccountID != id || result.CooldownModel != "paid" || result.AggregateFEFO != wantFEFO { + t.Fatalf("dispatch %d: adapter got %s/%s, result got %s/%s FEFO=%t; want %s/paid FEFO=%t", i, chat.accountID, chat.model, result.PoolAccountID, result.CooldownModel, result.AggregateFEFO, id, wantFEFO) + } + m.RefreshRouteQuotaAfterUse(result.PoolAccountID, result.CooldownModel, result.AggregateFEFO) + m.quotaAfterUseDone.Wait() + if got := p.calls.Load(); got != int32(i) { + t.Fatalf("dispatch %d: %d quota fetches, want %d", i, got, i) + } + } + stored, err := m.store.Get(t.Context(), id) + if err != nil || stored.Quota == nil || !stored.Quota.Exceeded { + t.Fatalf("selected aggregate completion did not persist depleted quota: %v, %+v", err, stored.Quota) + } +} + +func TestRouteFEFOCompletionRefreshCoalescesAcrossStrategies(t *testing.T) { + m, id, p := newFEFORefreshFixture(t) + m.RefreshFEFOQuotaAfterUse(id, "paid") + awaitFEFORefresh(t, p, 1) + + // The legacy event that opened the worker no longer qualifies under the + // new global strategy; independently admitted aggregate events still do. + m.pool.SetRoutingStrategy(accounts.RoutingStrategyRoundRobin) + for i := 0; i < 100; i++ { + m.RefreshRouteQuotaAfterUse(id, "paid", true) + } + p.release <- struct{}{} + awaitFEFORefresh(t, p, 2) + p.release <- struct{}{} + m.quotaAfterUseDone.Wait() + if got := p.calls.Load(); got != 2 { + t.Fatalf("mixed-strategy completions made %d requests, want one initial and one trailing", got) + } +} + func TestFEFOCompletionRefreshStopsOnClose(t *testing.T) { m, id, p := newFEFORefreshFixture(t) m.RefreshFEFOQuotaAfterUse(id, "paid") diff --git a/internal/runtime/manager_maintenance.go b/internal/runtime/manager_maintenance.go index 8be1e926c..a5fec3389 100644 --- a/internal/runtime/manager_maintenance.go +++ b/internal/runtime/manager_maintenance.go @@ -218,6 +218,8 @@ const ( checkinStatusGrace = 15 * time.Minute ) +var checkinStatusNow = time.Now + // SyncCheckinStatuses refreshes every check-in-capable account from upstream. // It is safe to call concurrently; only one pass runs at a time. func (manager *Manager) SyncCheckinStatuses(ctx context.Context) { @@ -296,7 +298,7 @@ func (manager *Manager) syncCheckinStatus(ctx context.Context, account Account) stop := context.AfterFunc(manager.runCtx, cancel) defer stop() result, readErr := adapter.CheckinStatus.CheckinStatus(syncCtx, account.ID) - now := time.Now().UTC() + now := checkinStatusNow().UTC() // A manual/scheduled check-in can finish while the read-only probe is in // flight. Re-read the account before deciding, so the slower probe cannot // overwrite a fresh success with the state that preceded it. diff --git a/internal/server/http.go b/internal/server/http.go index 3416fd5ae..1baa24532 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -3,6 +3,8 @@ package server import ( "encoding/json" "net/http" + + "github.com/caigee-cmd/cli2api/internal/endpoint" ) func writeJSON(w http.ResponseWriter, status int, v any) { @@ -20,3 +22,38 @@ func writeErr(w http.ResponseWriter, status int, code, msg string) { }, }) } + +// writeProtocolErr keeps an early rejection (auth, maintenance, concurrency +// gate) in the protocol dialect of the endpoint that produced it. Messages +// clients parse the Anthropic envelope; Chat and Responses clients parse the +// OpenAI envelope. +func writeProtocolErr(w http.ResponseWriter, r *http.Request, status int, code, msg string) { + if r != nil && r.URL.Path == endpoint.MessagesPath { + writeJSON(w, status, map[string]any{ + "type": "error", + "error": map[string]any{ + "type": anthropicErrorType(status), + "message": msg, + }, + }) + return + } + writeErr(w, status, code, msg) +} + +func anthropicErrorType(status int) string { + switch status { + case http.StatusBadRequest, http.StatusUnprocessableEntity: + return "invalid_request_error" + case http.StatusUnauthorized: + return "authentication_error" + case http.StatusForbidden: + return "permission_error" + case http.StatusNotFound: + return "not_found_error" + case http.StatusTooManyRequests: + return "rate_limit_error" + default: + return "api_error" + } +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go index c57946b9d..3d0e4cbd3 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -1,17 +1,29 @@ package server import ( + "log" "net/http" "strings" + "github.com/caigee-cmd/cli2api/internal/accounts" "github.com/caigee-cmd/cli2api/internal/auth" "github.com/caigee-cmd/cli2api/internal/endpoint" + "github.com/caigee-cmd/cli2api/internal/executor" appupdate "github.com/caigee-cmd/cli2api/internal/update" ) func (s *Server) Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if isOpenAIEndpoint(r.URL.Path) { + // Allocate the request ID before authentication, maintenance and + // parsing so every rejection (401, 503, bad body) can be correlated. + // The gateway reuses this value instead of minting one later. + id := s.newRequestID() + w.Header().Set("X-Request-Id", id) + // Anthropic SDKs read `request-id`; OpenAI SDKs read `x-request-id`. + // Emitting both keeps either client's error message correlatable. + w.Header().Set("request-id", id) + r = r.WithContext(executor.WithEntryRequestID(r.Context(), id)) setOpenAICORSHeaders(w, r) if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) @@ -19,13 +31,31 @@ func (s *Server) Handler() http.Handler { } } if s.updater().Maintenance.Load() && appupdate.BlocksDuringUpdate(r.URL.Path) { - writeErr(w, http.StatusServiceUnavailable, "service_updating", "Service update in progress") + logRequestRejection(r, http.StatusServiceUnavailable, "service_updating") + writeProtocolErr(w, r, http.StatusServiceUnavailable, "service_updating", "Service update in progress") return } s.mux.ServeHTTP(w, r) }) } +func (s *Server) newRequestID() string { + if s != nil && s.RequestID != nil { + return s.RequestID() + } + return accounts.NewRequestID() +} + +// logRequestRejection leaves a correlatable trace for failures that happen +// before any handler (and therefore before any request log row exists). +func logRequestRejection(r *http.Request, status int, code string) { + id := executor.EntryRequestIDFromContext(r.Context()) + if id == "" { + return + } + log.Printf("request rejected id=%s path=%s status=%d code=%s", id, r.URL.Path, status, code) +} + func isOpenAIEndpoint(path string) bool { switch path { case endpoint.ModelsPath, endpoint.ChatCompletionsPath, endpoint.MessagesPath, endpoint.ResponsesPath: @@ -35,19 +65,6 @@ func isOpenAIEndpoint(path string) bool { } } -func setOpenAICORSHeaders(w http.ResponseWriter, r *http.Request) { - header := w.Header() - header.Set("Access-Control-Allow-Origin", "*") - header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") - requestedHeaders := strings.TrimSpace(r.Header.Get("Access-Control-Request-Headers")) - if requestedHeaders == "" { - requestedHeaders = "Authorization, Content-Type, X-API-Key, X-Requested-With" - } - header.Set("Access-Control-Allow-Headers", requestedHeaders) - header.Set("Access-Control-Expose-Headers", "X-Request-Id, X-Qoder-Account, X-CLI2API-Account, X-CLI2API-Provider") - header.Set("Access-Control-Max-Age", "600") -} - // setUISecurityHeaders applies browser-facing hardening to the authenticated // operator console and its static assets only. These headers are deliberately // NOT set on the OpenAI/Anthropic gateway endpoints, where client SDKs parse @@ -68,11 +85,25 @@ func withUISecurityHeaders(next http.Handler) http.Handler { }) } +func setOpenAICORSHeaders(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("Access-Control-Allow-Origin", "*") + header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + requestedHeaders := strings.TrimSpace(r.Header.Get("Access-Control-Request-Headers")) + if requestedHeaders == "" { + requestedHeaders = "Authorization, Content-Type, X-API-Key, X-Requested-With" + } + header.Set("Access-Control-Allow-Headers", requestedHeaders) + header.Set("Access-Control-Expose-Headers", "X-Request-Id, request-id, Retry-After, X-Qoder-Account, X-CLI2API-Account, X-CLI2API-Provider") + header.Set("Access-Control-Max-Age", "600") +} + func (s *Server) withAPIKey(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { identity, ok := s.Auth.Authenticate(r.Context(), r) if !ok { - writeErr(w, http.StatusUnauthorized, "invalid_api_key", "Missing/invalid API key") + logRequestRejection(r, http.StatusUnauthorized, "invalid_api_key") + writeProtocolErr(w, r, http.StatusUnauthorized, "invalid_api_key", "Missing/invalid API key") return } if identity.Kind == auth.KindKey && s.TouchKey != nil { diff --git a/internal/server/protocol_error_test.go b/internal/server/protocol_error_test.go new file mode 100644 index 000000000..b4f3e38fd --- /dev/null +++ b/internal/server/protocol_error_test.go @@ -0,0 +1,95 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/caigee-cmd/cli2api/internal/endpoint" + appupdate "github.com/caigee-cmd/cli2api/internal/update" +) + +// An early rejection must carry the protocol dialect of its endpoint and the +// entry-allocated request id before any handler runs. +func TestEarlyRejectionKeepsProtocolShapeAndRequestID(t *testing.T) { + for _, tc := range []struct { + name string + path string + wantKeys []string + wantTypes []string + }{ + {"messages", endpoint.MessagesPath, []string{"type", "error"}, []string{"invalid_request_error"}}, + {"chat", endpoint.ChatCompletionsPath, []string{"message", "type", "code"}, nil}, + {"responses", endpoint.ResponsesPath, []string{"message", "type", "code"}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + update := &appupdate.Coordinator{} + update.Maintenance.Store(true) + s := New(Server{ + Update: update, + RequestID: func() string { return "req-entry-1" }, + }) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(`{}`)) + s.Handler().ServeHTTP(rec, req) + + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d", rec.Code) + } + if got := rec.Header().Get("X-Request-Id"); got != "req-entry-1" { + t.Fatalf("X-Request-Id = %q", got) + } + if got := rec.Header().Get("request-id"); got != "req-entry-1" { + t.Fatalf("request-id = %q", got) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body: %v (%s)", err, rec.Body.String()) + } + if tc.name == "messages" { + if body["type"] != "error" { + t.Fatalf("missing anthropic envelope: %v", body) + } + inner, _ := body["error"].(map[string]any) + if inner["type"] != "api_error" { + t.Fatalf("anthropic error type = %v", inner) + } + return + } + inner, _ := body["error"].(map[string]any) + if inner == nil || inner["message"] == nil || inner["type"] == nil || inner["code"] == nil { + t.Fatalf("missing openai envelope: %v", body) + } + }) + } +} + +func TestProtocolErrorUsesRequestStatusMapping(t *testing.T) { + for _, tc := range []struct { + status int + want string + }{ + {http.StatusUnauthorized, "authentication_error"}, + {http.StatusForbidden, "permission_error"}, + {http.StatusTooManyRequests, "rate_limit_error"}, + {http.StatusBadRequest, "invalid_request_error"}, + {http.StatusServiceUnavailable, "api_error"}, + } { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, endpoint.MessagesPath, nil) + writeProtocolErr(rec, req, tc.status, "x", "y") + var body struct { + Error struct { + Type string `json:"type"` + } `json:"error"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.Error.Type != tc.want { + t.Fatalf("status %d -> %s, want %s", tc.status, body.Error.Type, tc.want) + } + } +} diff --git a/internal/server/router.go b/internal/server/router.go index 845541ba7..b59db03de 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -25,7 +25,7 @@ func (s *Server) routes() { s.mux.HandleFunc("/api/keys", s.withConsoleKey(s.consoleHandler().HandleAPIKeys)) s.mux.HandleFunc("/api/keys/", s.withConsoleKey(s.consoleHandler().HandleAPIKeyByID)) s.mux.HandleFunc("/api/aggregations", s.withConsoleKey(s.consoleHandler().HandleAggregations)) - s.mux.HandleFunc("/api/aggregations/preview", s.withConsoleKey(s.consoleHandler().HandleAggregationPreview)) + s.mux.HandleFunc("POST /api/aggregations/preview", s.withConsoleKey(s.consoleHandler().HandleAggregationPreview)) s.mux.HandleFunc("/api/aggregations/", s.withConsoleKey(s.consoleHandler().HandleAggregationByID)) s.mux.HandleFunc("/api/models", s.withConsoleKey(s.consoleHandler().HandleModelsAPI)) s.mux.HandleFunc("/api/models/check", s.withConsoleKey(s.consoleHandler().HandleModelProbe)) diff --git a/internal/server/server.go b/internal/server/server.go index 139c3c79d..3b6b310bf 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -20,6 +20,9 @@ type Server struct { Update *appupdate.Coordinator TouchKey func(ctx context.Context, keyID string) CrossProvider *atomic.Bool + // RequestID, when set, allocates the per-request correlation id at the + // HTTP entry. Nil falls back to accounts.NewRequestID. + RequestID func() string mux *http.ServeMux } diff --git a/internal/store/backup_test.go b/internal/store/backup_test.go index 9f4d5155f..58b8cf5ef 100644 --- a/internal/store/backup_test.go +++ b/internal/store/backup_test.go @@ -115,6 +115,7 @@ func TestPublishedMigrationsKeepOrderedFilenameAndSQLDigest(t *testing.T) { {"033_account_checkin_status.sql", "0e4b4466a23d58eb9e7e370053ad7b52bc3285ea9461a8b99cac2bae88bba49d"}, {"034_aggregation_capabilities.sql", "9a280f0afde18d33a6a278fe2577668c315abd88591d6aa1eebdfd3cf18ab74d"}, {"035_aggregation_document.sql", "50fde5d314590553cf82caf1b593d807c92a569eaec54bd552caabdbc9be3f39"}, + {"036_request_outcome_facts.sql", "ca75ffd6f4bf2319abfe9b0366014ee639f774745d2e63a5d2ee13ee4e5f0b90"}, } if len(sqliteMigrations) != len(want) { t.Fatalf("migration count = %d, want %d", len(sqliteMigrations), len(want)) diff --git a/internal/store/migrations.go b/internal/store/migrations.go index 1f9461c7d..3ee27d7a4 100644 --- a/internal/store/migrations.go +++ b/internal/store/migrations.go @@ -296,6 +296,21 @@ ALTER TABLE aggregation_models ADD COLUMN reasoning_options TEXT NOT NULL DEFAUL ALTER TABLE aggregation_models ADD COLUMN reasoning_effort TEXT NOT NULL DEFAULT '';`}, {filename: "035_aggregation_document.sql", sql: ` ALTER TABLE aggregation_models ADD COLUMN document TEXT NOT NULL DEFAULT '';`}, + {filename: "036_request_outcome_facts.sql", sql: ` +ALTER TABLE request_attempts ADD COLUMN error_code TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN route_model TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN phase TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN request_sent INTEGER NOT NULL DEFAULT 0; +ALTER TABLE request_attempts ADD COLUMN cooldown_scope TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN stop_reason TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN internal_retries INTEGER NOT NULL DEFAULT 0; +ALTER TABLE request_attempts ADD COLUMN request_state TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_attempts ADD COLUMN sequence INTEGER NOT NULL DEFAULT 0; +ALTER TABLE request_attempts ADD COLUMN attempt_kind TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_logs ADD COLUMN upstream_terminal TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_logs ADD COLUMN downstream_terminal TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_logs ADD COLUMN flush_state TEXT NOT NULL DEFAULT ''; +ALTER TABLE request_logs ADD COLUMN request_state TEXT NOT NULL DEFAULT '';`}, } const schemaMigrationsDDL = ` diff --git a/internal/store/request_attempt_outcome_test.go b/internal/store/request_attempt_outcome_test.go new file mode 100644 index 000000000..ac9529976 --- /dev/null +++ b/internal/store/request_attempt_outcome_test.go @@ -0,0 +1,51 @@ +package store + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +func TestRequestAttemptOutcomeFactsRoundTrip(t *testing.T) { + ctx := context.Background() + store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + now := time.Now().UTC() + parent := accounts.RequestLog{ + ID: "req-outcome", CreatedAt: now, Status: accounts.RequestStatusOK, + UpstreamTerminal: "done", DownstreamTerminal: "done", FlushState: "ok", RequestState: "sent", + } + if err := store.InsertRequestLog(ctx, parent); err != nil { + t.Fatal(err) + } + attempt := accounts.RequestAttempt{ + ID: "att-outcome", RequestID: parent.ID, AttemptIndex: 0, AccountID: "acc", + StartedAt: now, Status: accounts.AttemptStatusOK, RequestState: "sent", RequestSent: true, + Sequence: 7, AttemptKind: "classifier", Model: "m", Phase: "response", + InternalRetries: 1, ErrorCode: "none", + } + if err := store.InsertRequestAttempt(ctx, attempt); err != nil { + t.Fatal(err) + } + log, err := store.GetRequestLog(ctx, parent.ID) + if err != nil { + t.Fatal(err) + } + if len(log.Attempts) != 1 { + t.Fatalf("attempts = %d", len(log.Attempts)) + } + got := log.Attempts[0] + if got.RequestState != "sent" || !got.RequestSent || got.Sequence != 7 || got.AttemptKind != "classifier" || got.InternalRetries != 1 { + t.Fatalf("attempt facts not persisted: %+v", got) + } + if log.UpstreamTerminal != "done" || log.DownstreamTerminal != "done" || log.FlushState != "ok" { + t.Fatalf("request terminal facts not persisted: %+v", log) + } +} diff --git a/internal/store/request_logs.go b/internal/store/request_logs.go index c249b6782..d0829a5ea 100644 --- a/internal/store/request_logs.go +++ b/internal/store/request_logs.go @@ -29,14 +29,16 @@ func (s *Store) InsertRequestLog(ctx context.Context, log accounts.RequestLog) e INSERT INTO request_logs ( id, created_at, finished_at, stream, status, requested_model, mapped_model, requested_reasoning, resolved_reasoning, account_id, api_key_id, provider, routing, prompt_tokens, completion_tokens, cache_read_tokens, cache_write_tokens, usage_source, credits, - latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, message_count, empty_message_indexes, message_roles - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, message_count, empty_message_indexes, message_roles, + upstream_terminal, downstream_terminal, flush_state, request_state + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, log.ID, formatTime(log.CreatedAt), finished, boolToInt(log.Stream), log.Status, log.RequestedModel, log.MappedModel, strings.TrimSpace(log.RequestedReasoning), strings.TrimSpace(log.ResolvedReasoning), nullIfEmpty(log.AccountID), strings.TrimSpace(log.APIKeyID), strings.TrimSpace(log.Provider), strings.TrimSpace(log.Routing), nullableInt(log.PromptTokens), nullableInt(log.CompletionTokens), nullableInt(log.CacheReadTokens), nullableInt(log.CacheWriteTokens), log.UsageSource, nullableFloat(log.Credits), nullableInt(log.LatencyMs), nullableInt(log.TTFBMs), log.ErrorKind, log.ErrorCode, log.ErrorMessage, log.AttemptCount, log.MessageCount, encodeIntSlice(log.EmptyMessageIndexes), encodeStringSlice(log.MessageRoles), + log.UpstreamTerminal, log.DownstreamTerminal, log.FlushState, log.RequestState, ) if err != nil { return fmt.Errorf("insert request log: %w", err) @@ -58,13 +60,15 @@ func (s *Store) UpdateRequestLog(ctx context.Context, log accounts.RequestLog) e api_key_id = COALESCE(NULLIF(?, ''), api_key_id), provider = ?, routing = ?, prompt_tokens = ?, completion_tokens = ?, cache_read_tokens = ?, cache_write_tokens = ?, usage_source = ?, credits = ?, latency_ms = ?, ttfb_ms = ?, - error_kind = ?, error_code = ?, error_message = ?, attempt_count = ?, message_count = ?, empty_message_indexes = ?, message_roles = ? + error_kind = ?, error_code = ?, error_message = ?, attempt_count = ?, message_count = ?, empty_message_indexes = ?, message_roles = ?, + upstream_terminal = ?, downstream_terminal = ?, flush_state = ?, request_state = ? WHERE id = ?`, finished, log.Status, log.RequestedModel, log.MappedModel, strings.TrimSpace(log.RequestedReasoning), strings.TrimSpace(log.ResolvedReasoning), nullIfEmpty(log.AccountID), strings.TrimSpace(log.APIKeyID), strings.TrimSpace(log.Provider), strings.TrimSpace(log.Routing), nullableInt(log.PromptTokens), nullableInt(log.CompletionTokens), nullableInt(log.CacheReadTokens), nullableInt(log.CacheWriteTokens), log.UsageSource, nullableFloat(log.Credits), nullableInt(log.LatencyMs), nullableInt(log.TTFBMs), - log.ErrorKind, log.ErrorCode, log.ErrorMessage, log.AttemptCount, log.MessageCount, encodeIntSlice(log.EmptyMessageIndexes), encodeStringSlice(log.MessageRoles), log.ID, + log.ErrorKind, log.ErrorCode, log.ErrorMessage, log.AttemptCount, log.MessageCount, encodeIntSlice(log.EmptyMessageIndexes), encodeStringSlice(log.MessageRoles), + log.UpstreamTerminal, log.DownstreamTerminal, log.FlushState, log.RequestState, log.ID, ) if err != nil { return fmt.Errorf("update request log: %w", err) @@ -93,12 +97,17 @@ func (s *Store) InsertRequestAttempt(ctx context.Context, attempt accounts.Reque _, err := s.db.ExecContext(ctx, ` INSERT INTO request_attempts ( id, request_id, attempt_index, account_id, started_at, finished_at, status, http_status, - error_kind, error_message, latency_ms, prompt_tokens, completion_tokens, usage_source -) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + error_kind, error_message, latency_ms, prompt_tokens, completion_tokens, usage_source, + error_code, route_model, phase, request_sent, cooldown_scope, stop_reason, internal_retries, + request_state, sequence, attempt_kind +) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, attempt.ID, attempt.RequestID, attempt.AttemptIndex, attempt.AccountID, formatTime(attempt.StartedAt), finished, attempt.Status, nullableInt(attempt.HTTPStatus), attempt.ErrorKind, attempt.ErrorMessage, nullableInt(attempt.LatencyMs), nullableInt(attempt.PromptTokens), nullableInt(attempt.CompletionTokens), attempt.UsageSource, + attempt.ErrorCode, attempt.Model, attempt.Phase, boolToInt(attempt.RequestSent), + attempt.CooldownScope, attempt.StopReason, attempt.InternalRetries, + attempt.RequestState, attempt.Sequence, attempt.AttemptKind, ) if err != nil { return fmt.Errorf("insert request attempt: %w", err) @@ -128,7 +137,8 @@ func (s *Store) ListRequestLogs(ctx context.Context, filter accounts.RequestLogF COALESCE(NULLIF(provider, ''), (SELECT provider FROM accounts WHERE accounts.id = request_logs.account_id), ''), routing, prompt_tokens, completion_tokens, cache_read_tokens, cache_write_tokens, usage_source, COALESCE(credits, (SELECT credit FROM request_usage_details WHERE request_usage_details.request_id = request_logs.id)), - latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, detail_expired, message_count, empty_message_indexes, message_roles + latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, detail_expired, message_count, empty_message_indexes, message_roles, + upstream_terminal, downstream_terminal, flush_state, request_state FROM request_logs` + where + ` ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?` args = append(args, limit, offset) rows, err := s.db.QueryContext(ctx, query, args...) @@ -428,7 +438,8 @@ func (s *Store) GetRequestLog(ctx context.Context, id string) (accounts.RequestL COALESCE(NULLIF(provider, ''), (SELECT provider FROM accounts WHERE accounts.id = request_logs.account_id), ''), routing, prompt_tokens, completion_tokens, cache_read_tokens, cache_write_tokens, usage_source, COALESCE(credits, (SELECT credit FROM request_usage_details WHERE request_usage_details.request_id = request_logs.id)), - latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, detail_expired, message_count, empty_message_indexes, message_roles + latency_ms, ttfb_ms, error_kind, error_code, error_message, attempt_count, detail_expired, message_count, empty_message_indexes, message_roles, + upstream_terminal, downstream_terminal, flush_state, request_state FROM request_logs WHERE id = ?`, strings.TrimSpace(id)) log, err := scanRequestLog(row) if errors.Is(err, sql.ErrNoRows) { @@ -574,8 +585,10 @@ FROM request_stream_diagnostics WHERE request_id = ?`, requestID).Scan( func (s *Store) listRequestAttempts(ctx context.Context, requestID string) ([]accounts.RequestAttempt, error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, request_id, attempt_index, account_id, started_at, finished_at, status, http_status, - error_kind, error_message, latency_ms, prompt_tokens, completion_tokens, usage_source -FROM request_attempts WHERE request_id = ? ORDER BY attempt_index ASC, started_at ASC`, requestID) + error_kind, error_message, latency_ms, prompt_tokens, completion_tokens, usage_source, + error_code, route_model, phase, request_sent, cooldown_scope, stop_reason, internal_retries, + request_state, sequence, attempt_kind +FROM request_attempts WHERE request_id = ? ORDER BY sequence ASC, started_at ASC, attempt_index ASC`, requestID) if err != nil { return nil, fmt.Errorf("list request attempts: %w", err) } @@ -851,6 +864,7 @@ func scanRequestLog(row rowScanner) (accounts.RequestLog, error) { &log.ID, &created, &finished, &stream, &log.Status, &log.RequestedModel, &log.MappedModel, &log.RequestedReasoning, &log.ResolvedReasoning, &accountID, &log.APIKeyID, &log.Provider, &log.Routing, &prompt, &completion, &cacheRead, &cacheWrite, &log.UsageSource, &credits, &latency, &ttfb, &log.ErrorKind, &log.ErrorCode, &log.ErrorMessage, &log.AttemptCount, &detailExpired, &log.MessageCount, &emptyIndexes, &messageRoles, + &log.UpstreamTerminal, &log.DownstreamTerminal, &log.FlushState, &log.RequestState, ) if err != nil { return accounts.RequestLog{}, err @@ -886,15 +900,19 @@ func scanRequestAttempt(row rowScanner) (accounts.RequestAttempt, error) { finished sql.NullString httpStatus sql.NullInt64 latency, prompt, completion sql.NullInt64 + requestSent int started string ) err := row.Scan( &attempt.ID, &attempt.RequestID, &attempt.AttemptIndex, &attempt.AccountID, &started, &finished, &attempt.Status, &httpStatus, &attempt.ErrorKind, &attempt.ErrorMessage, &latency, &prompt, &completion, &attempt.UsageSource, + &attempt.ErrorCode, &attempt.Model, &attempt.Phase, &requestSent, &attempt.CooldownScope, &attempt.StopReason, &attempt.InternalRetries, + &attempt.RequestState, &attempt.Sequence, &attempt.AttemptKind, ) if err != nil { return accounts.RequestAttempt{}, err } + attempt.RequestSent = requestSent != 0 attempt.StartedAt = parseTime(started) if finished.Valid && finished.String != "" { parsed := parseTime(finished.String) diff --git a/internal/store/request_logs_test.go b/internal/store/request_logs_test.go index bfc3bdcc4..975dab2df 100644 --- a/internal/store/request_logs_test.go +++ b/internal/store/request_logs_test.go @@ -237,6 +237,27 @@ func TestForeignKeyPragmaSurvivesConnectionRecycle(t *testing.T) { } } +// TestBusyTimeoutPragmaSurvivesConnectionRecycle pins the DSN fix: a connection +// database/sql opens after dropping the original one must still wait on +// locked databases instead of failing immediately with SQLITE_BUSY. +func TestBusyTimeoutPragmaSurvivesConnectionRecycle(t *testing.T) { + ctx := context.Background() + store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + store.DB().SetMaxIdleConns(0) + var timeout int + if err := store.DB().QueryRowContext(ctx, `PRAGMA busy_timeout`).Scan(&timeout); err != nil { + t.Fatal(err) + } + if timeout != 5000 { + t.Fatalf("busy_timeout = %d ms on a recycled connection, want 5000", timeout) + } +} + func TestUsageDetailBackfillUsesProviderThenAccountFallback(t *testing.T) { ctx := context.Background() store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) diff --git a/internal/store/request_quality_stats_test.go b/internal/store/request_quality_stats_test.go new file mode 100644 index 000000000..ca58a3485 --- /dev/null +++ b/internal/store/request_quality_stats_test.go @@ -0,0 +1,74 @@ +package store + +import ( + "context" + "path/filepath" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" +) + +func TestSummarizeQualitySignals(t *testing.T) { + ctx := context.Background() + store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + base := time.Date(2026, 8, 28, 10, 0, 0, 0, time.UTC) + mk := func(i int, status string, ttfb, latency, completion int, up, down, flush string) accounts.RequestLog { + log := accounts.RequestLog{ + ID: accounts.NewRequestID(), CreatedAt: base.Add(time.Duration(i) * time.Minute), + Status: status, RequestedModel: "m", AccountID: "acc", Provider: "p", + UpstreamTerminal: up, DownstreamTerminal: down, FlushState: flush, + } + if ttfb > 0 { + log.TTFBMs = &ttfb + } + if latency > 0 { + log.LatencyMs = &latency + } + if completion > 0 { + log.CompletionTokens = &completion + } + return log + } + + rows := []accounts.RequestLog{ + mk(0, accounts.RequestStatusOK, 100, 200, 40, "done", "done", "ok"), + mk(1, accounts.RequestStatusOK, 300, 400, 80, "done", "done", "ok"), + mk(2, accounts.RequestStatusIncomplete, 0, 0, 0, "eof", "none", "ok"), + mk(3, accounts.RequestStatusError, 0, 0, 0, "none", "error", "error"), + } + for _, row := range rows { + if err := store.InsertRequestLog(ctx, row); err != nil { + t.Fatal(err) + } + } + + stats, err := store.SummarizeRequestLogs(ctx, base.Add(-time.Minute), base.Add(5*time.Minute)) + if err != nil { + t.Fatal(err) + } + + if stats.Quality.Requests != 4 || stats.Quality.OK != 2 || stats.Quality.Errored != 1 { + t.Fatalf("quality counts = %+v", stats.Quality) + } + if stats.Quality.Lost != 2 { + t.Fatalf("lost = %d, want 2", stats.Quality.Lost) + } + if stats.Quality.LossRate != 0.5 { + t.Fatalf("loss rate = %v, want 0.5", stats.Quality.LossRate) + } + if stats.Quality.ErrorRate != 0.25 { + t.Fatalf("error rate = %v, want 0.25", stats.Quality.ErrorRate) + } + if stats.Quality.AvgOutputTPS <= 0 { + t.Fatalf("avg output tps = %v, want positive", stats.Quality.AvgOutputTPS) + } + if stats.Latency.TTFTP50Ms == nil || stats.Latency.TTFTP95Ms == nil { + t.Fatalf("ttft percentiles = %+v", stats.Latency) + } +} diff --git a/internal/store/request_stats_singlepass.go b/internal/store/request_stats_singlepass.go index 243c31cb5..1f6b371f4 100644 --- a/internal/store/request_stats_singlepass.go +++ b/internal/store/request_stats_singlepass.go @@ -127,9 +127,11 @@ func (s *Store) summarizeRequestLogsSinglePass(ctx context.Context, opts account statusCounts := make(map[string]int) errorCounts := make(map[string]int) var totalLatencies []int + var totalTTFB []int seriesLatencies := make([][]int, len(plan.points)) var latencySum, ttfbSum int64 var latencyCount, ttfbCount int + var lossyRows, completionTokens, latencySeconds int64 var creditSum kahanSum rows, err := s.db.QueryContext(ctx, ` @@ -142,6 +144,7 @@ SELECT created_at, stream, latency_ms, ttfb_ms, prompt_tokens, completion_tokens, cache_read_tokens, cache_write_tokens, + upstream_terminal, downstream_terminal, flush_state, `+creditExprNullable+` FROM request_logs`+where, args...) if err != nil { @@ -158,11 +161,13 @@ FROM request_logs`+where, args...) latency, ttfb sql.NullInt64 prompt, completion sql.NullInt64 cacheRead, cacheWrite sql.NullInt64 + upTerm, downTerm, flush string credit sql.NullFloat64 ) if err := rows.Scan( &created, &status, &errorKind, &modelKey, &accountKey, &prov, &stream, - &latency, &ttfb, &prompt, &completion, &cacheRead, &cacheWrite, &credit, + &latency, &ttfb, &prompt, &completion, &cacheRead, &cacheWrite, + &upTerm, &downTerm, &flush, &credit, ); err != nil { return accounts.RequestStats{}, fmt.Errorf("scan request stats row: %w", err) } @@ -196,6 +201,20 @@ FROM request_logs`+where, args...) if ttfb.Valid { ttfbSum += ttfb.Int64 ttfbCount++ + totalTTFB = append(totalTTFB, int(ttfb.Int64)) + } + // App-layer loss: the upstream ended without its terminal frame, the + // downstream terminal frame could not be delivered, or the final flush + // failed. Client cancellations are excluded by the gateway classifier. + if status == accounts.RequestStatusIncomplete || status == accounts.RequestStatusError || + upTerm == "eof" || downTerm == "error" || flush == "error" { + lossyRows++ + } + if completion.Valid { + completionTokens += completion.Int64 + } + if latency.Valid { + latencySeconds += latency.Int64 } statusCounts[status]++ @@ -246,6 +265,24 @@ FROM request_logs`+where, args...) stats.Latency.P50Ms = roundedInt(percentileNearestRank(totalLatencies, 50)) stats.Latency.P95Ms = roundedInt(percentileNearestRank(totalLatencies, 95)) } + if len(totalTTFB) > 0 { + sort.Ints(totalTTFB) + stats.Latency.TTFTP50Ms = roundedInt(percentileNearestRank(totalTTFB, 50)) + stats.Latency.TTFTP95Ms = roundedInt(percentileNearestRank(totalTTFB, 95)) + } + + stats.Quality.Requests = stats.Totals.Requests + stats.Quality.OK = stats.Totals.OK + stats.Quality.Errored = stats.Totals.Error + stats.Quality.Lost = int(lossyRows) + if stats.Totals.Requests > 0 { + stats.Quality.SuccessRate = float64(stats.Totals.OK) / float64(stats.Totals.Requests) + stats.Quality.ErrorRate = float64(stats.Totals.Error) / float64(stats.Totals.Requests) + stats.Quality.LossRate = float64(lossyRows) / float64(stats.Totals.Requests) + } + if latencySeconds > 0 { + stats.Quality.AvgOutputTPS = float64(completionTokens) / (float64(latencySeconds) / 1000.0) + } stats.Status = statsBucketsFromCounts(statusCounts, 0) stats.Errors = statsBucketsFromCounts(errorCounts, 8) stats.Models = statsNamedFromAggs(models, limit) diff --git a/internal/translate/toolargs.go b/internal/translate/toolargs.go deleted file mode 100644 index 7ab618a19..000000000 --- a/internal/translate/toolargs.go +++ /dev/null @@ -1,276 +0,0 @@ -package translate - -import ( - "encoding/json" - "strings" -) - -const maxCloseClosers = 24 - -// NormalizeToolCallArguments always returns valid JSON for a function tool's -// argument text, so a damaged tool call degrades into a call the model can -// retry instead of killing the whole turn. The bool reports whether anything -// had to change. -// -// Order: formatting repair first; then drop the trailing incomplete member -// (a value cut mid-string, usually by the output-token limit) and keep only -// fields the model finished writing; last resort an empty object. Dropping -// beats inventing: a tool called without its unfinished field validates and -// fails visibly, while padding a truncated `rm -rf /tmp/fo` would execute -// something the model never wrote. -func NormalizeToolCallArguments(raw string) (string, bool) { - text := strings.TrimSpace(raw) - if text == "" { - return "{}", true - } - if json.Valid([]byte(text)) { - return text, false - } - if repaired, ok := RepairToolCallArguments(text); ok { - return repaired, true - } - if trimmed, ok := dropIncompleteMember(text); ok { - return trimmed, true - } - return "{}", true -} - -// RepairToolCallArguments fixes formatting-level damage only: bare quotes -// inside a value, a trailing comma, missing closing brackets after a complete -// value, or prose appended after the object. It never pads a value that was -// cut mid-string and reports ok=false for that case. -func RepairToolCallArguments(raw string) (string, bool) { - text := strings.TrimSpace(raw) - if text == "" { - return "{}", true - } - if json.Valid([]byte(text)) { - return text, true - } - candidates := argumentRepairCandidates(text) - for _, candidate := range candidates { - if json.Valid([]byte(candidate)) { - return candidate, true - } - } - for _, candidate := range candidates { - if closed, ok := closeArgumentTail(candidate); ok { - return closed, true - } - } - // A model sometimes appends prose after a complete object: keep the value - // the decoder actually finished and drop the trailing noise. - if prefix, ok := decodeArgumentPrefix(text); ok { - return prefix, true - } - return "", false -} - -// dropIncompleteMember keeps only the members the model finished writing: it -// cuts at the last top-level comma whose prefix can be closed into valid JSON. -func dropIncompleteMember(text string) (string, bool) { - if !strings.HasPrefix(text, "{") { - return "", false - } - commas := topLevelCommaPositions(text) - for index := len(commas) - 1; index >= 0; index-- { - prefix := strings.TrimSpace(strings.TrimSuffix(text[:commas[index]], ",")) - if prefix == "" || prefix == "{" { - continue - } - if closed, ok := closeArgumentTail(prefix); ok { - return closed, true - } - } - if closed, ok := closeArgumentTail("{"); ok { - return closed, true - } - return "", false -} - -// topLevelCommaPositions returns the byte offsets of commas that sit directly -// inside the outermost object, outside any nested structure or string. -func topLevelCommaPositions(text string) []int { - positions := make([]int, 0, 8) - depth := 0 - inString := false - for index := 0; index < len(text); index++ { - character := text[index] - if inString { - if character == '\\' { - index++ - continue - } - if character == '"' { - inString = false - } - continue - } - switch character { - case '"': - inString = true - case '{', '[': - depth++ - case '}', ']': - depth-- - case ',': - if depth == 1 { - positions = append(positions, index) - } - } - } - return positions -} - -func argumentRepairCandidates(text string) []string { - candidates := []string{text} - if withoutTrailing := stripTrailingCommas(text); withoutTrailing != text { - candidates = append(candidates, withoutTrailing) - } - if escaped := escapeBareQuotes(text); escaped != text { - candidates = append(candidates, escaped, stripTrailingCommas(escaped)) - } - return candidates -} - -// stripTrailingCommas removes `,` that directly precede a closing brace or -// bracket, which models emit routinely and strict JSON rejects. -func stripTrailingCommas(text string) string { - var out strings.Builder - out.Grow(len(text)) - for index := 0; index < len(text); index++ { - character := text[index] - if character == ',' { - next := index + 1 - for next < len(text) && isJSONSpace(text[next]) { - next++ - } - if next < len(text) && (text[next] == '}' || text[next] == ']') { - continue - } - } - out.WriteByte(character) - } - return out.String() -} - -// escapeBareQuotes escapes `"` characters that appear inside a JSON string -// value. A closing quote is accepted only when the next non-space byte is one -// of `, } ] :` or the end of the buffer. -func escapeBareQuotes(text string) string { - var out strings.Builder - out.Grow(len(text)) - inString := false - for index := 0; index < len(text); { - character := text[index] - if !inString { - out.WriteByte(character) - if character == '"' { - inString = true - } - index++ - continue - } - if character == '\\' && index+1 < len(text) { - out.WriteString(text[index : index+2]) - index += 2 - continue - } - if character == '"' { - next := index + 1 - for next < len(text) && isJSONSpace(text[next]) { - next++ - } - if next >= len(text) || strings.IndexByte(",}]:", text[next]) >= 0 { - out.WriteByte(character) - inString = false - } else { - out.WriteString(`\"`) - } - index++ - continue - } - out.WriteByte(character) - index++ - } - return out.String() -} - -// closeArgumentTail appends the closers the model never got to emit, but only -// when no string is left open — a value cut mid-string stays unrepaired. -func closeArgumentTail(text string) (string, bool) { - stack := make([]byte, 0, maxCloseClosers) - var out strings.Builder - out.Grow(len(text) + maxCloseClosers) - inString := false - for index := 0; index < len(text); index++ { - character := text[index] - if inString { - out.WriteByte(character) - if character == '\\' && index+1 < len(text) { - out.WriteByte(text[index+1]) - index++ - continue - } - if character == '"' { - inString = false - } - continue - } - switch character { - case '"': - inString = true - out.WriteByte(character) - case '{', '[': - if len(stack) >= maxCloseClosers { - return "", false - } - stack = append(stack, character) - out.WriteByte(character) - case '}', ']': - if len(stack) == 0 { - return "", false - } - open := stack[len(stack)-1] - if (character == '}' && open != '{') || (character == ']' && open != '[') { - return "", false - } - stack = stack[:len(stack)-1] - out.WriteByte(character) - default: - out.WriteByte(character) - } - } - if inString || len(stack) == 0 { - return "", false - } - for index := len(stack) - 1; index >= 0; index-- { - if stack[index] == '{' { - out.WriteString("}") - } else { - out.WriteString("]") - } - } - closed := stripTrailingCommas(out.String()) - if json.Valid([]byte(closed)) { - return closed, true - } - return "", false -} - -func decodeArgumentPrefix(text string) (string, bool) { - decoder := json.NewDecoder(strings.NewReader(text)) - var value any - if decoder.Decode(&value) != nil { - return "", false - } - prefix := strings.TrimSpace(text[:decoder.InputOffset()]) - if prefix == "" || !json.Valid([]byte(prefix)) { - return "", false - } - return prefix, true -} - -func isJSONSpace(character byte) bool { - return character == ' ' || character == '\t' || character == '\r' || character == '\n' -} diff --git a/internal/translate/toolargs_normalize_test.go b/internal/translate/toolargs_normalize_test.go deleted file mode 100644 index c2cb00e8d..000000000 --- a/internal/translate/toolargs_normalize_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package translate - -import ( - "encoding/json" - "testing" -) - -func TestNormalizeToolCallArgumentsNeverReturnsInvalidJSON(t *testing.T) { - cases := []struct { - name string - raw string - want string - wantChange bool - }{ - {name: "valid", raw: `{"path":"a.go"}`, want: `{"path":"a.go"}`}, - {name: "blank", raw: " ", want: "{}", wantChange: true}, - {name: "trailing comma", raw: `{"path":"a.go",}`, want: `{"path":"a.go"}`, wantChange: true}, - {name: "missing brace", raw: `{"path":"a.go"`, want: `{"path":"a.go"}`, wantChange: true}, - {name: "truncated last field dropped", raw: `{"path":"a.go","body":"partial`, want: `{"path":"a.go"}`, wantChange: true}, - {name: "truncated only field becomes empty", raw: `{"command":"rm -rf /tmp/fo`, want: "{}", wantChange: true}, - {name: "truncated nested field dropped", raw: `{"path":"a.go","edits":[{"old":"x","new":"y`, want: `{"path":"a.go"}`, wantChange: true}, - {name: "not json at all", raw: `please read the file`, want: "{}", wantChange: true}, - } - for _, tc := range cases { - got, changed := NormalizeToolCallArguments(tc.raw) - if !json.Valid([]byte(got)) { - t.Fatalf("%s: result is not valid JSON: %q", tc.name, got) - } - if got != tc.want { - t.Fatalf("%s: got %q, want %q", tc.name, got, tc.want) - } - if changed != tc.wantChange { - t.Fatalf("%s: changed = %v, want %v", tc.name, changed, tc.wantChange) - } - } -} diff --git a/internal/translate/toolargs_test.go b/internal/translate/toolargs_test.go deleted file mode 100644 index 5232e1f06..000000000 --- a/internal/translate/toolargs_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package translate - -import ( - "encoding/json" - "testing" -) - -func TestRepairToolCallArguments(t *testing.T) { - cases := []struct { - name string - raw string - want string - ok bool - }{ - {name: "valid passthrough", raw: `{"path":"a.go"}`, want: `{"path":"a.go"}`, ok: true}, - {name: "blank becomes object", raw: " ", want: "{}", ok: true}, - {name: "trailing comma", raw: `{"path":"a.go",}`, want: `{"path":"a.go"}`, ok: true}, - {name: "missing closing brace", raw: `{"path":"a.go"`, want: `{"path":"a.go"}`, ok: true}, - {name: "missing nested closers", raw: `{"pattern":"x","paths":["a","b"`, want: `{"pattern":"x","paths":["a","b"]}`, ok: true}, - {name: "bare quote inside value", raw: `{"cmd":"echo "hi""}`, want: `{"cmd":"echo \"hi\""}`, ok: true}, - {name: "prose after object", raw: `{"path":"a.go"} and then explain`, want: `{"path":"a.go"}`, ok: true}, - {name: "cut mid string", raw: `{"cmd":"rm -rf /tmp/fo`, ok: false}, - {name: "cut mid key", raw: `{"pa`, ok: false}, - {name: "not json at all", raw: `please read the file`, ok: false}, - } - for _, tc := range cases { - got, ok := RepairToolCallArguments(tc.raw) - if ok != tc.ok { - t.Fatalf("%s: ok = %v, want %v (got %q)", tc.name, ok, tc.ok, got) - } - if !ok { - continue - } - if got != tc.want { - t.Fatalf("%s: got %q, want %q", tc.name, got, tc.want) - } - if !json.Valid([]byte(got)) { - t.Fatalf("%s: repaired value is not valid JSON: %q", tc.name, got) - } - } -}