Two issues in the voice/STT WebSocket proxy:
1. The established proxy never watched c.Request.Context().Done(), so
server.requestTimeout had no effect on a quiet, already-admitted
session: the account lease, concurrency slot, and upstream connection
stayed open past the configured deadline until a transport error
occurred on either side. Added a watcher that closes the session once
the request context is canceled, extracted as watchRequestTimeout so
it is unit-testable without a real WebSocket upgrade.
2. STT billing was gated on the downstream client closing cleanly
(successful == ErrorCode == ""), even though the cost is already
incurred the moment the upstream sends a confirmed transcript.done
duration. A client that received a complete transcription and then
disconnected abnormally left EstimatedCostInUSDTicks at zero,
understating usage against the key's billing limit. Billing is now
keyed on having a confirmed duration, not on how the transport ended.
Every other account-selection path (text chat, image generation, voice,
voice websocket) threads the requesting client key's AccountScope through
to beginSelectionSessionForKey. The video job's background retry/recovery
worker (runVideoJob) used the unscoped beginSelectionSession instead, so
once the job's originally pinned account failed, the fallback search for a
replacement ignored the client key's provider/tier restrictions entirely.
A client key restricted to e.g. Super-tier accounts could end up consuming
a Free-tier (or wrong-provider) account's quota purely because its pinned
account hit a transient failure, silently widening access beyond what the
key was configured to allow.
media.Job already stores ClientKeyID, so the fix looks up that key and
passes its AccountScope into beginSelectionSessionForKey, matching every
other selection path. Added a regression test
(TestVideoRetryDoesNotEscapeClientKeyAccountScope) that fails against the
prior code (confirmed: the out-of-scope account was used) and passes with
the fix.
requestRetry still leaked grok-4.6 dumps after the short-usage patch:
fake-enc/burst required visible >= minOutput, plaintext thinking vetoed
the dump detectors, and chat usage.completion inflated visible tokens.
Withhold when reasoning>=80 or ciphertext meets the floor and the visible
flush is <2s. Plaintext thinking still withholds if flush<2s and
reasoning/output >= 0.8. Cipher-only HasThinking waits until visible text
has streamed for 2s, or the stream ends. Visible tokens come from
streamed content only.
Does not enable requestRetry and does not change lab Docker/VERSION
defaults.
Free Web accounts 429 when duration exceeds 6s, which then rotates
accounts without changing the payload. Add a Grok Web setting
(freeVideoDurationCap, default 6) and clamp duration for free-tier
accounts at the Web adapter so retries are not wasted.
Codex/OpenAI Responses tools often send a root oneOf/anyOf whose
branches are $ref or nested unions. xAI/Build grammar requires a
root object or a root union of inline objects. Lift only the root
union, keep property $ref/$defs, and fail locally if the result is
still illegal.
Also treat streamed 400 JSON as ClassifyUpstreamHTTPError instead of
copyStream, so invalid-argument is request-scoped and does not rotate
accounts. Compatibility warning is function_parameters_root_normalized.
Doom-loop aborts were wrapped as a generic stream read failure, so audits
and SSE trailers reported upstream_stream_interrupted. Keep the sentinel
distinct so a model repeating the same delta is not mixed with a transport
cut.
After a 2xx SSE handoff, a client hangup is client_stream_interrupted and keeps the upstream status. upstream_stream_interrupted is only for an upstream cut. Pre-header 499 request_canceled is unchanged.
A timeout or lock on GetCredentialMaterial used to abort the whole
selector as no available accounts. Treat those per-account failures
like a stale claim so the rest of the pool can still be used. Request
cancellation still stops selection. Missing credentials still invalidate
the routing snapshot.
Compaction-blob 400s recovered inside the Build adapter were returned as
200 with no audit attempts. Record each hidden upstream call (stage +
what the retry did) on the successful response.
Pinned conversation acquire treated a missing/disabled owning account as
an empty pool (upstream_unavailable) even when other accounts existed.
Return upstream_pinned_account_unavailable, skip bot-flag scheduling
exclusion for pinned acquire, and persist the selection failure plus
owning account id on the audit row.
When the first account returns 429 and the next account's 2xx stream
later fails, diagnostics previously kept only the 429 row. Always
append a response_stream attempt for the handed-off account unless
one is already present.
Encrypted_content can clear the byte floor while usage still bills hundreds
of reasoning tokens against a few visible tokens. Treat that fast dump as
missing thinking even before the hold deadline.
A reasoning item start plus visible tokens at the deadline is not late
ciphertext. Treat it as missing thinking and rotate, matching the TUI
dump after 30s.
Do not skip missing-thinking intercept on previous_response_id or hosted
tools. TUI always declares those. First attempt stays pinned; withhold
unpins and rotates. Compaction with no reasoning is held unless the
gateway set skipQualityHold.
Non-empty ciphertext is not proof of reasoning. HasThinking now requires
encrypted_content / Anthropic signature to meet max(256B, 4 bytes per
usage reasoning token). A hold-expired short greeting billed as heavy
thinking, or a barely-over-floor flush in under a second, is withheld.
Recommended requestRetry values stay 30s / minOutput 8 / 6 attempts /
fail_closed / 12h / 15m idle, plus the new floor knobs. enabled remains
false so stock installs do not intercept.
Same-account recovery now strips ciphertext while rewriting readable
summaries as developer messages, continues to session reset when the
stripped retry still returns 400, and only rotates accounts after
reasoning_recovery_failed. Drop Diagnostic substring matching so
unrelated 400s do not scan the account pool.
In multi-account pools, server-side encrypted compaction blobs and reasoning states can fail to decode when a session drifts across accounts or upstream nodes, causing xAI to return HTTP 400 ("Could not decode the compaction blob").
Previously, isRetryable(400) evaluated to false in the gateway service, treating all 400 responses as non-retryable client errors. When provider reasoning recovery failed on the active account, the gateway immediately propagated the 400 to the client instead of attempting other healthy accounts in the candidate pool.
Fixes:
1. Gateway failover: Recognize reasoning_recovery_failed in isRetryableResponse so the gateway excludes the failing account and attempts the next candidate within the request attempt loop.
2. Reasoning recovery: Completely strip all reasoning items and convert compaction items to compatibility boundary messages during downgrade retries.
3. History normalization: Convert unencrypted reasoning items without portable content to developer boundary messages.
4. Error markers: Add compaction decode patterns to reasoningDecodeFailureMarkers.
Tested:
- Added TestRecoverReasoningDecodeFailureCompactionBlob
- Updated TestReasoningWithoutEncryptedContentBecomesBoundary
- All backend packages pass (go test ./...)