Skip to content

fix(agents): refresh provider stream timeouts on chunks - #76633

Merged
steipete merged 3 commits into
openclaw:mainfrom
mkdev5:fix/issue-76307-stream-timeout-heartbeat
May 3, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
mkdev5:fix/issue-76307-stream-timeout-heartbeat

Conversation

@mkdev5

@mkdev5 mkdev5 commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Describe the problem and fix in 2-5 bullets:

  • Problem: Long OpenAI-compatible streamed agent replies could be aborted by the provider fetch timeout even while response-body chunks were still arriving, leaving users with a short truncated assistant fragment.
  • Why it matters: Issue [Bug]: long-output agent turns truncate at ~25–80 chars; deterministic, channel-agnostic; direct OpenAI API call with same model/prompt works fine #76307 reports deterministic long-output truncation across channels, while the same model and prompt work through the direct OpenAI API.
  • What changed: Refresh the guarded provider fetch timeout whenever streaming response-body progress is observed, including SSE keepalive/event-only chunks before sanitization.
  • What did NOT change (scope boundary): No model defaults, channel delivery logic, compaction behavior, provider API shape, dependencies, or broader timeout policy were changed.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write N/A. If the cause is unclear, write Unknown.

  • Root cause: buildTimeoutAbortSignal used a one-shot timeout around provider fetches, so an active long-running stream could be aborted after the original deadline even when chunks were still arriving.
  • Missing detection / guardrail: Existing tests covered initial timeout behavior but did not assert that streaming body progress refreshes the guarded fetch timeout.
  • Contributing context (if known): When the inner guarded fetch aborts, the OpenAI stream path can leave partial assistant text available to downstream run finalization.

Regression Test Plan (if applicable)

For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write N/A.

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • src/utils/fetch-timeout.test.ts
    • src/agents/provider-transport-fetch.test.ts
    • src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts
  • Scenario the test should lock in: Active response-body chunks refresh the timeout, sanitized SSE chunks still count as progress, and a stream timeout produces an explicit timeout payload instead of a partial assistant fragment.
  • Why this is the smallest reliable guardrail: It covers the timeout utility, the provider transport stream wrapper, and the run finalization behavior without requiring a live provider call.
  • Existing test that already covers this (if any): None before this PR.
  • If no new test is added, why not: N/A.

User-visible / Behavior Changes

Long streamed assistant replies should no longer truncate solely because the original provider fetch timeout elapsed while chunks were still arriving. If a prompt stream truly times out, users should see an explicit timeout error instead of a short partial assistant fragment.

Diagram (if applicable)

Before:
provider stream starts -> original fetch timeout fires -> stream aborts -> partial assistant text may be surfaced

After:
provider stream starts -> each body chunk refreshes timeout -> active stream continues
true stream timeout -> explicit timeout error instead of partial fragment

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: Linux local checkout; issue reporter used Ubuntu WSL2
  • Runtime/container: Node/pnpm local test environment; issue reporter used Node 22.22.0
  • Model/provider: OpenAI-compatible streamed provider transport; issue reporter used api: openai-completions with gpt-5.5
  • Integration/channel (if any): Transport-level fix; reporter observed Discord and Telegram truncation
  • Relevant config (redacted): Heavy prompt/bootstrap context with long assistant output

Steps

  1. Trigger a long streamed OpenAI-compatible agent response where chunks continue arriving beyond the original guarded fetch timeout window.
  2. Observe provider transport consumption and embedded runner finalization.
  3. Run the focused regression tests listed below.

Expected

  • Streaming response-body progress refreshes the provider fetch timeout.
  • Long active streams are not aborted solely because the original timeout deadline elapsed.
  • If a prompt stream does time out, the user receives an explicit timeout error instead of a partial assistant fragment.

Actual

  • Before this fix, the guarded fetch timeout could abort an active long stream and downstream finalization could expose the partial assistant text.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Regression evidence:

  • Before the production fix, the provider transport regression test failed because refreshTimeout was called 0 times instead of 2.
  • After the fix:
    • pnpm test src/utils/fetch-timeout.test.ts src/agents/provider-transport-fetch.test.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts
    • pnpm test src/agents/pi-embedded-runner/run.timeout-triggered-compaction.test.ts src/agents/provider-transport-fetch.test.ts
    • pnpm test src/utils/fetch-timeout.test.ts src/agents/provider-transport-fetch.test.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts src/agents/pi-embedded-runner/run.timeout-triggered-compaction.test.ts
    • pnpm check:changed
    • pnpm test src/agents/openai-transport-stream.test.ts

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
    • Timeout utility refresh extends the active deadline when progress occurs.
    • Provider transport refreshes the guarded timeout for streamed response chunks before SSE sanitization.
    • Embedded runner returns a timeout payload instead of a partial assistant fragment after a prompt stream timeout.
  • Edge cases checked:
    • No-timeout and parent-signal paths retain no-op refresh behavior.
    • Event-only/keepalive SSE chunks still refresh timeout even if later removed by the sanitizer.
    • Tool-media timeout behavior is preserved unless the only output is a partial assistant fragment after prompt timeout.
  • What you did not verify:
    • A live OpenAI API reproduction with the reporter's exact prompt/model/context size.

AI Assistance

  • AI-assisted? Yes, Codex was used for issue analysis, implementation, focused regression coverage, and self-review.
  • Testing level: Focused regression tests and changed-file checks passed locally.
  • Understanding: I reviewed the provider fetch timeout path, streaming response wrapper, and embedded runner timeout finalization path; the fix refreshes the guarded provider timeout on response-body progress and avoids surfacing partial assistant fragments after prompt stream timeout.
  • Prompts/session logs: Not attached; the PR body includes the root-cause summary, regression evidence, commands run, and scope boundary.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps: N/A

Risks and Mitigations

  • Risk: Refreshing the timeout on every chunk could allow very slow but active streams to run longer than the previous fixed deadline.
    • Mitigation: The timeout still aborts when no progress arrives for the configured interval; this matches the intended liveness behavior for streaming responses.
  • Risk: A stream timeout with some partial assistant text now returns an explicit timeout error instead of surfacing that fragment.
    • Mitigation: This is scoped to prompt stream timeouts without tool execution or delivered tool output, which matches the reported failure mode.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels May 3, 2026
@clawsweeper

clawsweeper Bot commented May 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

Summary
The branch refreshes guarded provider fetch timeouts on streaming body chunks, converts prompt-stream timeout fragments into explicit errors, and adds regression tests plus a changelog/config schema fixture refresh.

Reproducibility: yes. source-level reproduction is high confidence: current main uses a one-shot guarded fetch timer with no chunk refresh, and #76307 includes matching cross-channel timeout logs. I did not run the reporter's live OpenAI prompt in this read-only review.

Next step before merge
No repair job is needed because no discrete PR-introduced defect was found; the remaining action is exact-head CI completion and maintainer merge handling.

Security
Cleared: The diff changes timeout/response wrapping, runner finalization, tests, generated config schema, and changelog only; it adds no dependencies, workflows, permissions, secret handling, or new network destinations.

Review details

Best possible solution:

Land the narrow timeout-refresh patch once exact-head checks are green, preserving the linked issue closure on merge.

Do we have a high-confidence way to reproduce the issue?

Yes, source-level reproduction is high confidence: current main uses a one-shot guarded fetch timer with no chunk refresh, and #76307 includes matching cross-channel timeout logs. I did not run the reporter's live OpenAI prompt in this read-only review.

Is this the best way to solve the issue?

Yes. Refreshing the guarded timeout at the raw provider response wrapper is the narrow shared fix, and the explicit timeout payload path prevents partial assistant fragments from being finalized as successful replies.

What I checked:

  • Current main has one-shot timeout state: buildTimeoutAbortSignal on current main returns only signal and cleanup, schedules one timer, and has no progress-refresh hook. (src/utils/fetch-timeout.ts:93, 0f66ad4243c0)
  • Current provider stream wrapper does not refresh liveness: buildManagedResponse currently enqueues provider body chunks without notifying the timeout guard, and buildGuardedModelFetch sanitizes SSE before wrapping the response. (src/agents/provider-transport-fetch.ts:175, 0f66ad4243c0)
  • Patch refreshes on raw response chunks: The PR threads refreshTimeout from the guarded fetch result and calls it before enqueueing each raw response-body chunk, so event-only SSE keepalives count before sanitizer removal. (src/agents/provider-transport-fetch.ts:203, ea5bce6ac389)
  • Patch preserves timeout errors for OpenAI stream consumers: The PR changes timeout aborts to use an Error named TimeoutError; OpenAI SDK 6.35.0 source only swallows errors named AbortError in Stream.fromSSEResponse, so this keeps fetch timeouts visible. (src/utils/fetch-timeout.ts:90, ea5bce6ac389)
  • Patch covers the partial-fragment runner path: Current main only synthesizes a timeout payload when no payloads exist; the PR adds a guard for prompt timeouts that produced only partial assistant text and adds the matching regression test. (src/agents/pi-embedded-runner/run.ts:2084, ea5bce6ac389)
  • Linked report matches this seam: The linked issue discussion identifies fetch timeout reached; aborting operation in the OpenAI-compatible streamed provider path and traces it through buildGuardedModelFetch, fetchWithSsrFGuard, and buildTimeoutAbortSignal.

Likely related people:

  • steipete: Recent current-main history on provider-transport-fetch.ts includes OpenAI SDK timeout threading and malformed SSE-frame handling, which are central to this PR's seam. (role: recent maintainer and adjacent owner; confidence: high; commits: 74211128983a, c2e3b6e6f819, f7ed29e11812; files: src/agents/provider-transport-fetch.ts, src/agents/pi-embedded-runner/run.ts)
  • kevinslin: Recent history on fetch-timeout.ts and fetch-guard.ts added the fetch timeout logging/redaction behavior that this PR extends with refreshable timeout state. (role: timeout helper contributor; confidence: medium; commits: f35196117331; files: src/utils/fetch-timeout.ts, src/infra/net/fetch-guard.ts)
  • simonusa: Recent embedded-runner history added tool-timeout classification and timeout payload behavior near the same runner decision surface this PR adjusts. (role: runner timeout behavior contributor; confidence: medium; commits: 2605490dbd30, 8996161e992a, fbad17bf4f33; files: src/agents/pi-embedded-runner/run.ts)

Remaining risk / open question:

  • Exact-head CI completion should still gate merge; several check runs were still in progress when inspected.
  • This read-only review did not run the reporter's exact live OpenAI prompt, so confidence comes from source inspection, dependency source, issue logs, and the PR's focused regression coverage.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 0f66ad4243c0.

@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label May 3, 2026
@steipete
steipete merged commit 4fff254 into openclaw:main May 3, 2026
102 of 103 checks passed
@steipete

steipete commented May 3, 2026

Copy link
Copy Markdown
Contributor

Merged via rebase at 4fff254.

Validation:

  • pnpm test src/config/schema.base.generated.test.ts src/cli/config-cli.test.ts src/utils/fetch-timeout.test.ts src/agents/provider-transport-fetch.test.ts src/agents/pi-embedded-runner/run.overflow-compaction.loop.test.ts src/agents/pi-embedded-runner/run.timeout-triggered-compaction.test.ts src/agents/pi-embedded-runner/run/assistant-failover.test.ts src/agents/openai-transport-stream.test.ts src/tui/commands.test.ts
  • pnpm config:schema:check
  • Testbox OPENCLAW_TESTBOX=1 pnpm check:changed
  • GitHub CI clean on final head ea5bce6

Thanks @MKDev11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: long-output agent turns truncate at ~25–80 chars; deterministic, channel-agnostic; direct OpenAI API call with same model/prompt works fine

3 participants