sanitizeOpenAIResponsesToolSchemasForPlatform runs on every OpenAI Responses
forward attempt, on WS normalization and on /v1/messages conversion, and its two
passes both ran far more often than they need to:
* the regex-pattern pass was gated on "the body contains '('", and tool
descriptions, code samples and user messages contain parentheses
constantly, so the gate let essentially everything through;
* the parameter-type pass had no gate at all and ran for OpenAI, Anthropic,
Grok and every CN platform.
A 1MiB Codex request therefore walked its body twice with the hand-written
parser before reaching the upstream. Profiling put 92% of that in parseString,
which scanned strings byte by byte while long content strings are most of a
request body.
Changes:
1. parseString skips the plain run of a string eight bytes at a time (SWAR),
stopping only on '"', '\\' or a control byte - exactly the three bytes it has
to stop at. 2.2 GB/s -> 10.5 GB/s.
2. An input item is no longer walked twice. The type probe walked the whole item
and then the item was walked again just to skip it; the probe's end position
is now reused. Messages dominate input history.
3. json.Valid(body) only runs when the walk actually produced an edit. With no
edits the body is returned untouched, so that second full-body validation
proved nothing; patches are still validated after they are applied.
4. Both gates are now necessary conditions that can be proven complete.
hasUnsupportedOpenAIRegexPattern only fires on an unsupported backslash
escape, a trailing backslash, or group syntax "(?"; the first two need a
decoded backslash, which JSON can only spell "\\\\" or \\u005c, and the third
can have either character escaped. The parameter pass only edits a literal
null value or a oneOf/anyOf union, and the union repair accepts any
parameters object containing a backslash, so an escaped keyword such as
"one\\u004ff" counts too - hence the \\u00XX needle.
5. Patterns are checked in place when the JSON span carries no escape, instead
of strconv.Unquote per pattern, and object member names are parsed once into
openAIResponsesJSONKey rather than rescanning the span for every candidate
name.
Benchmark (Apple M5 Pro, 1MiB Codex-shaped body: 30 tools + 1MiB input):
platform entry, OpenAI 7.48ms / 512 allocs -> 96us / 0 allocs
platform entry, Anthropic 3.75ms / 256 allocs -> 66us / 0 allocs
patterns pass 3.71ms / 256 allocs -> 30us / 0 allocs
parameter-types pass 3.69ms / 256 allocs -> 66us / 0 allocs
Existing benchmarks:
..._Patterns_ByteSpanPatch 1586609ns / 2017 allocs -> 915199ns / 17
..._ParameterTypes_ByteSpanPatch 1011697ns / 17 allocs -> 647160ns / 17
Correctness: parseString keeps the previous byte-at-a-time scanner as legacy*
and compares return values and error positions across a corpus plus fuzzing;
the probe reuse asserts that the probe and the skip walk stop at the same byte;
the gates are pinned by the invariant "if the sanitizer changed the body, the
gate must have let it through", over a corpus that spells out every unsupported
pattern shape and fuzzing; dropping the pre-edit json.Valid relies on "the
parser accepts implies encoding/json accepts", which is fuzzed too.
Fuzzing found two bugs in this change, both fixed and kept as regression seeds
under testdata/fuzz: an out-of-range read when a body ended in "\\\\", and a gate
that was narrower than the necessary condition for a pattern whose value is a
lone backslash. The second means such patterns are now cleaned up where the old
gate only caught them by accident, when the body happened to contain a
parenthesis elsewhere.
The benchmark body builder discarded the results of strings.Builder.WriteString,
which errcheck rejects (the repo enables errcheck with check-blank off, so a
plain call is flagged even though Builder never returns an error). Route the
writes through one helper that assigns the result.
stripOpenAIResponsesInputNamespaces runs on every OpenAI OAuth / API-key HTTP
forward attempt. Its entry check only proves that the *body* contains a
namespace literal, and Codex clients advertise the image_gen namespace tool on
ordinary requests, so the check passes for most traffic and the function runs
even when there is nothing to strip.
Three avoidable copies showed up in that path:
1. gjson.GetBytes(body, "input") materialises the input array. On a 1MiB body
that is a 1MiB allocation on every request, including the no-op case.
Use the zero-copy parse view (parseRawJSONView) instead.
2. The rewrite built the new input array in a buffer and then handed it to
sjson.SetRawBytes, which allocates a second full body copy. Assemble the
output directly instead: prefix + rewritten array + suffix in one buffer
sized to the body.
3. sjson.DeleteBytes([]byte(item.Raw), ...) converted each changed item to a
byte slice first. Use the string form.
hasOpenAIResponsesNamespaceToolDeclaration reads input the same way and gets
the same treatment; it runs for API-key accounts on every request.
Benchmark (Apple M5 Pro, -benchmem), legacy = the previous implementation:
1MiB tools_only 545us / 1056768 B / 1 alloc -> 495us / 0 B / 0 alloc
1MiB strip_first 882us / 3170624 B / 8 allocs -> 548us / 1056936 B / 4
1MiB strip_last 841us / 3170624 B / 8 allocs -> 556us / 1056928 B / 4
8MiB strip_first 5.95ms / 25190720 B / 8 -> 4.30ms / 8396960 B / 4
So the no-op path stops allocating entirely and the rewriting path copies one
body instead of three.
Behaviour is unchanged for valid JSON: equivalence tests keep the previous
implementation as legacy* and compare output bytes, errors and whether the
input slice was returned untouched, across 36 bodies (duplicate keys, escaped
keys, nested namespace fields, non-object items, keep-tool-call mode, missing
or non-array input) plus 3000 randomized combinations and a fuzz target.
One deliberate difference, pinned by a test: on input that is not valid JSON,
gjson.GetBytes and gjson.Parse return different spans for the same key, and
the new implementation refuses to rewrite an unparseable fragment instead of
truncating it. The only caller forwards a body that the handler has already
validated, so this path is not reachable in production.
Same shape as the responses handler: the body is validated at the top of
ChatCompletions, the only later rewrite is
applyOpenAIReasoningEffortPolicyForRequest (sjson), and the parse error was
already being ignored. Nothing between the two points mutates the bytes:
parseOpenAICompatibleStream, checkSecurityAudit and tokenInflightEstimate only
read them.
The /v1/responses handler validates the request body with gjson.ValidBytes
before doing anything else, then hands the same bytes to ParseGatewayRequest,
which validates them a second time. After the single-root-walk change the
validation is the majority of what that call does: at 1MiB it is about 510us
of the remaining 730us.
Add ParseGatewayRequestValidated for callers that have already established the
body is valid JSON, and use it in the handler, where the only rewrite between
the two points is applyOpenAIReasoningEffortPolicyForRequest (sjson, which
preserves validity).
The validating entry point is unchanged, so invalid JSON keeps producing a
clean error everywhere else. ReplaceBody / CloneForBody keep validating as
well, because their bytes can differ from the ones a caller validated.
Equivalence tests assert the trusted variant produces identical results to the
validating one on valid JSON, and the fuzz target checks the same for every
input that parses.
Benchmark (Apple M5 Pro, 3 allocs unchanged):
responses 1MiB: 735us -> 239us
anthropic 1MiB: 723us -> 207us (not yet wired: that handler has no earlier
validation, so it keeps the validating path)
parseGatewayRequestCurrentBody looked up eight fields with separate
gjson.Get calls. A lookup for a key that is not present still has to scan the
whole body to prove absence, and for a typical Responses request six of those
keys are absent (metadata.user_id, thinking.type, output_config.effort,
max_tokens, system, messages). On a 1MiB body that is six full passes at about
142us each, while a single root walk over the same body costs about 220us.
Collect every field the parser needs in one ForEach over the root and derive
the raw ranges from the same results.
Nested paths keep gjson semantics: each path segment resolves to the first
duplicate key that actually yields the child, not simply the first key with
that name. {"metadata":"x","metadata":{"user_id":"u"}} resolves to "u", and the
walk reproduces that by retrying while the collected child does not exist.
Duplicate scalar keys keep first-occurrence-wins.
The Anthropic [1m] model normalization rewrites the body mid-parse, so the walk
is repeated after the rewrite. That path only runs when the client leaks the
suffix.
Benchmark (Apple M5 Pro, 3 allocs unchanged):
responses 128KiB: 208us -> 96us
responses 1MiB: 1.59ms -> 735us
anthropic 1MiB: 1.43ms -> 723us
Equivalence tests keep a verbatim copy of the previous implementation as
legacy* and compare every field (model, stream, metadata user id, thinking,
effort, speed, max tokens, system/messages/input ranges, protocol, body after
parsing) across 4 protocols and 44 bodies, plus 3000 deterministic random
combinations. A fuzz target does the same for arbitrary input.
openAIRequestBodyHasImageGenerationDeclaration and
openAIRequestBodyImageGenerationToolNeedsNormalization each validate the whole
body up front before looking at tools/input/tool_choice. Both branches only
match image_gen literals, so the same byte-level necessary condition applies
and lets them skip the validation for bodies that cannot match.
Refs #8865
The handler validates the request body at gateway_handler_responses.go:66 and
ParseGatewayRequest validates it again at gateway_request.go:240. For bodies
that do carry image declarations the byte-level precheck cannot fire, so the
intent classifier still ran gjson.ValidBytes over the same bytes a third time.
That is the dominant remaining cost for Codex traffic, because Codex
advertises the image_gen namespace on ordinary responses requests.
Add IsImageGenerationIntentForPlatformValidated for callers that have already
established the body is valid JSON, and use it at the two call sites where
that holds:
- gateway_handler_responses.go: the body is validated at the top of the
handler, and afterwards it is only rewritten through sjson
(applyOpenAIReasoningEffortPolicyForRequest), which preserves validity.
- openai_ws_forwarder_ingress.go: the payload is validated in
parseClientPayload, and every later rewrite is sjson, a decode/re-marshal
round trip, or a no-op.
Both call sites carry the reasoning in a comment. The validating entry points
are unchanged, so invalid-JSON semantics stay exactly as they were for every
other caller.
Benchmark (Apple M5 Pro, 1MiB Codex body, 0 allocs):
intent classifier: 562us -> 50us
Refs #8865
Every /v1/responses request runs IsImageGenerationIntentForPlatform to decide
whether to mark the context as image generation (capability routing and image
billing). After the two O(1) checks (dedicated image endpoint, image model) the
function unconditionally runs gjson.ValidBytes over the whole body and then
walks the root object with a ForEach.
Both steps are pure overhead for requests that cannot match. Every branch that
can set the intent requires one of two things in the body: the literal
"image_gen" (image_generation tools carry that prefix, and the namespace,
tool_choice and function-reference checks all use image_gen), or an image model
name (gpt-image-*, grok-imagine*) as the "model" value. The same body is also
validated by the handler and again by ParseGatewayRequest, so this pass is a
third redundant validation of the same bytes.
Add a byte-level necessary condition ahead of gjson.ValidBytes:
bytes.Contains(body, "image_gen")
|| containsASCIIFold(body, "imag") // image model names
|| bytes.Contains(body, "\\u") // unicode-escaped literal
All three are required:
- "image_gen" alone misses the model branch. {"model":"gpt-image-2"} returns
true today and does not contain "image_gen"; dropping it would let image
model requests bypass the group image-generation gate and image billing.
- isOpenAIImageGenerationModel lowercases its argument while bytes.Contains
does not, so the model token is matched case-insensitively.
- JSON strings may spell any byte as a unicode escape, so a body containing
"image_generation" only reveals the literal after decoding. Escaped
bodies therefore fall back to the full scan. None of the target literals
contain a character JSON escapes, so a "\u" probe is exhaustive.
containsASCIIFold had to be rewritten as well. It compared byte by byte, which
is a full body scan on its own, and a first-byte memchr variant that re-probes
both cases of the first byte per candidate degrades quadratically. The new
implementation keeps one cursor per case and advances only the cursor it just
consumed, so it stays linear. Without this the precheck would cost more than
the scan it replaces (~930us vs 783us on a 1MiB body).
The three scan bodies collapse into two root walkers plus one entry point; the
grok and explicit rules were byte-identical copies.
Codex clients advertise the image_gen namespace on ordinary requests, so those
bodies still take the full scan. Skipping the duplicate validation for callers
that already validated the same bytes is a separate change.
Benchmark (Apple M5 Pro, 1MiB body, 0 allocs):
no image declarations 783us -> 48us
codex namespace 560us -> 564us (gate cannot fire, unchanged)
Fixes#8865
A composite route that rewrites the request model left the client's thinking untouched, so a route from claude-sonnet-5 to claude-opus-5-5 forwarded thinking.type=enabled with budget_tokens and validateClaude55Request answered 400 before the request reached the upstream.
The route middleware now rewrites the model through RewriteCompositeRequestModel, which replaces a thinking mode that validateClaude55Request rejects for the new model with the nearest mode it accepts: enabled becomes adaptive without budget_tokens, and disabled becomes between_tools on Sonnet 5.5.
The mapping is shared with the Bedrock Sonnet 5.5 sanitizer, whose behavior is unchanged.
Modes the target still rejects stay with validateClaude55Request, and a request whose model the route does not rewrite keeps its thinking as sent.
The byte-level precheck added for #8668 still runs both cache_control walks
for any body containing a "thinking" literal, because the thinking-block
cleanup cannot be skipped by that check alone. Claude Code enables extended
thinking by default, so that is the dominant shape: the precheck pays its own
scan and then falls through to the unconditional
normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body)).
On the 32KB Claude Code benchmark body with thinking, this made the optimized
path slightly slower than the pre-fix code (112us vs 104us).
Skip the second collectCacheControlPaths pass when the body has no "1h"
literal. The walk is provably a no-op there: last1h stays -1 and nothing is
rewritten. Escaped bodies returned earlier, so the byte check is exact, and
the block-limit deletions only remove cache_control keys, which cannot
introduce a 1h breakpoint.
Benchmark (Apple M5 Pro, -benchtime 2s -count 3):
thinking, no 1h: 112us / 21 allocs -> 52us / 8 allocs
common, no 1h: 21.6us / 0 allocs -> 21.3us / 0 allocs
1h bodies: unchanged (within noise)
The benchmark gains two thinking cases so future work cannot regress this
shape unnoticed. Equivalence tests compare against the verbatim legacy
implementation.
Fixes#8861
Refs #8668
When a Grok response usage carries server_side_tool_usage_details, take SearchCount from web_search_calls, x_search_calls and document_search_calls instead of counting output items.
xAI documents server_side_tool_usage as the successful calls that determine billing, so failed calls and server-side tools that return nothing are no longer billed. Classes the item counter does not count and the x_posts_fetched / x_users_fetched item counts are not read.
Without server_side_tool_usage_details the existing item counting is unchanged. The usage is read from the JSON body, the SSE body and the terminal stream event, for /v1/responses, /v1/messages and /v1/chat/completions, streaming and not. ResponsesUsage keeps the raw object so the buffered paths, which count from a decoded response, can read it.
extractUpstreamErrorMessage and extractUpstreamErrorCode drive failover,
model-not-found cooldown and account-disable decisions on every platform.
Reading a top-level code there short-circuited the OpenAI-compatible
model-not-found failover for vLLM-style bodies such as
{"object":"error","message":"model not found","code":400}. It also
added top-level token_revoked as a new disable path.
Restore the shared helpers to main. Add Grok-only grokUpstreamErrorMessage
and grokUpstreamErrorCode for the media error path, the content-policy
message and the error passthrough rule, so the Grok media fix in this PR
is unchanged. Adds tests that the shared extractors ignore the xAI flat
shape and that model-not-found still fails over with a top-level code.
When additionalProperties is reopened to true, or a patternProperties entry
is dropped, any edit nested inside that span is moot. The edit merger
rejected such pairs as overlapping patches, so the sanitizer failed
locally and the gateway returned 502 instead of forwarding. On main the
same bodies reached upstream, which returned a 400. Order edits by start,
then insertions first, then widest span first, and skip spans fully
enclosed by an earlier edit. Every replacement in this sanitizer is a
constant, never derived from inner content. Partial overlaps still
error.
quota_refresh_failed only means the active probe could not refresh the
quota and the values come from an earlier observation. The probe is
throttled by openAIProbeCacheTTL, so only the read that triggered it
carries the code; treating it as a failure made the quota monitor flap
between error and operational roughly every 10 minutes. Exempt it like
grok's quota_unknown, so monitor status is derived from the cached
observation as before. Adds an end-to-end no-flap test.
Candidate filtering reads the compact scheduler snapshot, which only keeps
allowlisted extra keys. Without openai_passthrough_model_filter the opt-in
filter was always false at selection time, so a passthrough account still
accepted every model while /v1/models (full account) hid them. Keep the
key in the projection and lock it with a round-trip test.
Resolve conflicts with #8729, which caches the configured account pool
and checks time-based blocks (rate limit, overload, temp-unschedulable)
on every read:
- readSnapshotAccounts filters by IsSchedulable on both the
GetSnapshotValues path (in-place compaction of the caller-owned slice)
and the GetSnapshot path.
- The coalesced DB fallback still publishes the full configured pool.
Each caller's private copy contains only accounts that are
schedulable now.
- The fallback test stubs now implement ListModelAvailabilityCandidates,
which #8729 switched the DB fallback to. Values-reader fixtures are
marked schedulable. Adds tests for time-blocked filtering on both paths
and for publishing the full pool.
Group and channel prices are admin-configured final prices. The 1.1x
multi-region factor now applies only when the token cost comes from
default model pricing (LiteLLM/fallback). This matches account stats
cost, which already applied the factor only at the model-file pricing
tier. Adds a regression test for configured vs default pricing.
Keep the stable content session hash from this PR, but restore
ForceCacheBilling on the native v1beta entry. Dropping it changed
billing policy: a sticky session that failed over would be charged
full input price instead of cache-read price. That also hit
Antigravity accounts served by this handler, and made it inconsistent
with /v1/messages, which still forces cache billing. Billing on this
entry is now identical to main.