Repository navigation
gateway: stream-reliability layer (empty-turn retry, idle-timeout, tool-call repair) - #213
Conversation
…ol-call repair)
UltraCode-Shim-shaped production polish for the OpenAI-compat surface:
1. Empty-turn auto-retry. Some upstream models / proxies (Together
/ OpenRouter route hiccups, MoonShot K2 brownouts, DeepSeek R1
thinking-token overflow) return a perfectly-shaped 200 whose
Content is empty AND ToolCalls is empty AND finish_reason='stop'.
The model said nothing. The agent goes silent mid-turn.
ChatWithEmptyRetry catches the shape and retries up to N times
with exponential backoff before surfacing the empty response.
Wired into RunToolLoop's primary Provider.Chat call (so every
loop-driven path inherits it) and into the gateway's
HandleResponses passthrough Chat (which bypasses the loop).
2. Idle-timeout kill for hung streams. ChatStreamWithReliability
runs Provider.ChatStream on a worker thread and watches the
OnChunk timestamp from the calling thread; if no chunk arrives
within StreamIdleTimeoutMs the wrapper detaches the worker
(FreeOnTerminate flips True, worker drains in the background
until Indy's ReadTimeout retires the socket) and returns a
synthetic response with finish_reason='timeout'. No leaked
sockets, no leaked threads. Wired into StreamResponsesViaProvider
and surfaced to the client as a response.failed event.
3. Tool-call repair. Strict OpenAI-compat backends (DeepSeek,
MiniMax-class) reject requests where an assistant turn carries
N tool_calls but the follow-up message history has fewer matched
tool_result entries -- typically the parallel-tool-cancelled
scenario. RepairOrphanedToolCalls walks the incoming Msgs,
finds tool_call.Ids without paired mrTool, and synthesizes
stub mrTool entries inserted right after the assistant turn.
Runs at the gateway boundary on HandleChatCompletions,
HandleResponses passthrough, and HandleResponses legacy.
All three knobs live in TConfig.StreamReliability (persisted under
"stream_reliability" in config.json) and can be overridden per-run
via env vars: UC_EMPTY_RETRY_ATTEMPTS, UC_EMPTY_RETRY_BACKOFF_MS,
UC_STREAM_IDLE_TIMEOUT_SEC, UC_TOOL_CALL_REPAIR. Defaults match the
shipping UltraCode-Shim config: 2 attempts, 750ms base backoff,
150s idle timeout, repair on. Zero-init records (the legacy shape
on TToolLoopConfig) keep retry / timeout off, so channels and the
embedder default to pre-PR behaviour.
New unit: src/pkg/stream/PasClaw.Stream.Reliability.pas.
New tests: src/tests/stream_reliability_tests.pas -- scripted fake
provider exercises happy / exhaustion / disabled empty-retry paths,
happy + timeout stream paths, and three RepairOrphanedToolCalls
scenarios.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e04137dcb4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| begin | ||
| FExceptionMsg := E.ClassName + ': ' + E.Message; | ||
| FResp := Default(TLLMResponse); | ||
| FResp.StatusCode := -1; |
There was a problem hiding this comment.
Mark stream exceptions as failures
When the idle-timeout wrapper is enabled (the new default), any provider ChatStream exception is caught on the worker thread and converted only to StatusCode := -1; callers such as StreamResponsesViaProvider do not inspect that status and only mark failures for FinishReason='error' or 'timeout', so DNS/socket/provider exceptions can be reported to /v1/responses streaming clients as a successful empty response.completed instead of the existing error path. Set a failure finish reason or re-raise/propagate the exception signal from the worker.
Useful? React with 👍 / 👎.
| FLock.Enter; | ||
| try | ||
| FLastChunkAt := Now; | ||
| Inc(FChunkCount); |
There was a problem hiding this comment.
Ignore protocol-only chunks for empty retries
For streams that finish with only protocol events or empty deltas, this increments FChunkCount even though no user-visible content was delivered. ChatStreamWithReliability retries empty turns only when ChunkCount = 0, so providers that emit a terminal done chunk (or the OpenAI/Gemini fallback ChatStream that calls OnChunk with empty Result.Content) will skip the new empty-turn retry and still return a silent 200 response. Count only content/tool chunks that would make retrying unsafe, or track delivered output separately.
Useful? React with 👍 / 👎.
The previous InternalOnChunk locked just to read FCancelled + capture the user callback, then released the lock before calling the user callback. That left a window where: 1. Worker reads FCancelled=False, captures Cb, releases lock. 2. Watcher fires Cancel + Detach, wrapper returns synthetic timeout. 3. Gateway tears down TResponsesStreamState (Streamer freed). 4. Worker calls Cb -- now writing into freed Streamer memory. Holding the lock across the entire Cb call closes the gap: Cancel waits for any in-progress OnChunk to finish before flipping FCancelled, and subsequent chunks are gated by FCancelled at the top of InternalOnChunk. After Cancel returns the wrapper is guaranteed no further user callbacks can fire from this job, so the gateway can safely tear down its stream state. The held-lock window is bounded by one OnChunk's socket write (the gateway's SSE emit) -- typically sub-millisecond and well under the 500ms watcher poll cadence, so it doesn't delay the timeout detection. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
1. Mark provider exceptions as failures.
The worker thread's exception handler was setting only StatusCode := -1
on a caught ChatStream exception. StreamResponsesViaProvider checks
FinishReason for 'error' / 'timeout' to drive its response.failed path
-- so a DNS / socket / TLS exception was silently presenting to the
/v1/responses streaming client as a successful empty response.completed
instead of an error.
Fix: set FResp.FinishReason := 'error' (and surface the exception text
in FResp.Content so the existing StreamErr := Resp.Content branch picks
it up). Failed=True now fires on exception, response.failed reaches the
client.
2. Ignore protocol-only chunks for empty-turn retry.
InternalOnChunk was bumping FChunkCount on every chunk, including the
empty-text deltas and 'done' / 'usage' protocol events some providers
emit at end-of-stream. ChatStreamWithReliability skips empty-turn retry
when ChunkCount > 0, so a stream that produced only protocol events and
no user-visible content silently locked in the empty response -- exactly
the case the retry was meant to recover from.
Fix: bump FChunkCount only when the chunk delivered user-visible content
(non-empty 'text' or any 'tool_call'). FLastChunkAt still updates on
every chunk because any activity counts as "not idle" for the timeout
watcher.
Two new test cases cover both paths:
- TestChatStreamExceptionMarkedAsFailure: provider raises mid-stream,
asserts R.FinishReason='error' and exception text in Content.
- TestProtocolOnlyChunksDoNotSuppressRetry: first stream emits empty
text + 'done' chunks with empty response, second carries content;
asserts retry fires and recovers.
https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
… and dcc cfg (Codex P2 #222) Codex P2: PR #222 added pkg\checkpoints to the three RAD Studio .dproj files but the same samples/component-console directory has three OTHER search-path sources that drive the documented `make` and command-line `dcc64 SampleConsole.dpr` flows: - samples/component-console/Makefile (the $(ROOT)/src/pkg/<x> list) - samples/component-console/dcc32.cfg - samples/component-console/dcc64.cfg All three were stuck on the pre-stream-reliability lineup -- they had neither pkg/checkpoints (this PR's target) nor pkg/stream nor pkg/kb, even though PRs #213 / #214 etc. landed long ago. Anyone using the documented sample build path would F2613 at the FIRST missing unit dcc reached, not just on checkpoints. Fix: add pkg/stream, pkg/checkpoints, and pkg/kb to all three sources, slotted in the same canonical order PasClaw.dproj uses (providers -> stream -> tokenizer; skills -> checkpoints -> session; memory -> kb -> updater) so a future grep -A1 across these files stays comprehensible. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
PR FMXExpress#213 introduced src/pkg/stream/PasClaw.Stream.Reliability.pas but only wired src/pkg/stream into the FPC Makefile's UNIT_DIRS. The Delphi dcc64 builds (PasClaw.dproj plus the three component-console samples) didn't pick up the new directory, so they fail with: F2613 Unit 'PasClaw.Stream.Reliability' not found at PasClaw.Config.pas's uses clause -- the entry point of nearly every compilation unit in the project. Fix: add ..\pkg\stream to the DCC_UnitSearchPath in PasClaw.dproj and the three sample dprojs, and add the explicit DCCReference for the new unit in PasClaw.dproj so the IDE's project tree shows it next to PasClaw.Providers.*. https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Summary
UltraCode-Shim-shaped production polish for the OpenAI-compat surface (
/v1/chat,/v1/chat/completions,/v1/responses). Three pieces, one new unit, one new test program:Content+ no tool calls +finish_reason='stop'(Together / OpenRouter route hiccups, MoonShot K2 brownouts, DeepSeek R1 thinking-token overflow).ChatWithEmptyRetrycatches the shape and retries up to N times with exponential backoff. Wired intoRunToolLoop's primaryProvider.Chatcall (every loop-driven path inherits it) and into the gateway'sHandleResponsespassthroughChat(bypasses the loop).ChatStreamWithReliabilityrunsProvider.ChatStreamon a worker thread, watches theOnChunktimestamp from the calling thread, and on timeout detaches the worker (drains in background until Indy'sReadTimeoutretires the socket) while returning a syntheticfinish_reason='timeout'response. No leaked sockets, no leaked threads. Wired intoStreamResponsesViaProvider; surfaced to the client asresponse.failed.RepairOrphanedToolCallswalksMsgs, finds orphan ids, and inserts stubmrToolentries right after the assistant turn. Runs at the gateway boundary onHandleChatCompletions,HandleResponsespassthrough, andHandleResponseslegacy.Configuration
TConfig.StreamReliability(persisted under"stream_reliability": {...}inconfig.json), env-var overrides:UC_EMPTY_RETRY_ATTEMPTS(default 2)UC_EMPTY_RETRY_BACKOFF_MS(default 750)UC_STREAM_IDLE_TIMEOUT_SEC(default 150)UC_TOOL_CALL_REPAIR(default true)Cmd.ServeandCmd.GatewaycallLoadStreamReliabilityFromEnvat startup; env wins over config.Compatibility
Default-zero records on
TToolLoopConfig.StreamReliability(EmptyRetryAttempts=0) keep retry off, so channels and the embedder default to pre-PR behaviour. Only the gateway entry points andCmd.Agent/TPasClawAgent(which now forwardCfg.StreamReliabilityexplicitly) opt in.Files
src/pkg/stream/PasClaw.Stream.Reliability.passrc/tests/stream_reliability_tests.pasTConfig,TToolLoopConfig,RunToolLoop, the four gateway entry points,Cmd.Serve,Cmd.Gateway,Cmd.Agent.BuildLoopConfig,TPasClawAgent.RunInteractiveTest plan
make test— full suite green (smoke + 24 unit-test programs incl. newtest-stream-reliability)make all— main binary builds from clean stateIsEmptyTurnrejects every non-empty-turn shape it shouldn't fire onChatWithEmptyRetryhappy / exhaustion / disabled pathsChatStreamWithReliabilityhappy passthrough + idle-timeout detachRepairOrphanedToolCallsleaves matched pairs alone, fully repairs all-orphan, and handles partial-orphan mixLoadStreamReliabilityFromEnvdefaults pass through unchangedpasclaw servewithUC_STREAM_IDLE_TIMEOUT_SEC=5against a slow provider, confirmresponse.failedarrives at ~5s/v1/chat/completionsagainst a DeepSeek-class backend, confirm 200 instead of 400https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
Generated by Claude Code