Skip to content

[Bug]: Embedded runner "Network connection lost" when LLM generates a tool call with large parameters (param generation latency > underlying request timeout) #53540

Closed as not planned

Description

@yilunzhang

Bug type

Behavior bug (incorrect output/state without crash)

Summary

The embedded runner fails with "Network connection lost." when the LLM generates a tool call whose parameters are large enough that producing them takes longer than the underlying request timeout. This is not specific to any one tool — it happens for any tool call where time-to-produce-params > underlying timeout. The Write tool with a large content argument is just the easiest reproducer.

Note on history. I originally filed this as a "large accumulated context (~100K tokens) via repeated web_fetch" bug and hypothesized it was Undici bodyTimeout. After more investigation that framing turned out to be a symptom; the title, summary, and steps below have been rewritten with the more accurate picture. Earlier comments and the Codex review reference the older framing.

Steps to reproduce

The easiest reproducer is asking a slow model to write a large file in one tool call inside a subagent:

  1. On OpenClaw 2026.3.13+, configured with OpenRouter (any API key), in a session run:
    Use sessions_spawn to create one subagent with model openrouter/anthropic/claude-opus-4.6 and runTimeoutSeconds: 0. Task: "Use the Write tool to create a single ~50KB markdown file at notes.md with a detailed history of the Roman Empire."
    
  2. The subagent's LLM call to emit the Write tool invocation fails with stopReason: "error", errorMessage: "Network connection lost.", and input_tokens: 0, output_tokens: 0.

The original reproducer (subagent doing ~32 sequential web_fetch calls and then summarizing ~130K tokens of accumulated context) also fails, but it is harder to isolate — large input pushes the model toward generating a large output, which is what actually triggers the failure.

Expected behavior

The LLM call should succeed (or at minimum, OpenClaw should retry with appropriate backoff and surface a clearer error than a generic network failure).

Actual behavior

The call returns zero tokens with errorMessage: "Network connection lost.". OpenClaw retries (default retry budget) but retries also fail until the run gives up. No output file is produced.

Why it happens (current understanding)

  • A tool call's parameters (e.g. the content field of a Write invocation) are part of the LLM response payload.
  • On the OpenRouter → Anthropic path I tested, tool-call parameters are not streamed incrementally on the wire — the model generates the full parameter JSON server-side and the call is emitted to the client only after generation finishes.
  • End-to-end response latency is therefore roughly param_size / model_throughput. For a slow model (Opus) generating a large content arg (tens of KB), this can exceed the underlying socket/idle timeout. The connection is dropped and the failure surfaces as "Network connection lost." (classified by the is-network-error package).

I have only verified this with OpenRouter. I don't know whether other providers exhibit the same behavior — providers that genuinely stream tool-call argument deltas should not, since the chunks would keep the connection alive.

Workaround

Instruct the model to never write more than ~X KB in one tool call and to use multiple tool calls for large files (e.g. Write then Append). This is fragile because models don't reliably follow the instruction, especially when the request implies a single large output.

Possible fixes

  1. Increase the idle timeout for LLM calls in subagents so slow tool-call generation doesn't trip it. (Trivial; just makes the failure window wider.)
  2. Enable tool-use streaming where supported (e.g. Anthropic's fine-grained-tool-streaming-2025-05-14 beta or equivalent). When the upstream emits partial tool-call arguments as deltas, those chunks keep the connection alive and openclaw's existing per-chunk idle timer resets cleanly. This is the better fix but only applies to providers/models that support it.

OpenClaw version

2026.3.13 (61d171a)

Operating system

Ubuntu 22.04 (DigitalOcean droplet, 2GB RAM)

Install method

pnpm global

Model

openrouter/anthropic/claude-opus-4.6

Provider / routing chain

openclaw → openrouter → anthropic

Additional provider/model setup details

Default OpenRouter provider with API key in auth-profiles.json. No proxy, no Cloudflare AI Gateway, no custom middleware. Gateway running as systemd user service on loopback (port 18789). contextTokens: 200000, compaction.mode: "safeguard".

Logs, screenshots, and evidence

The original report's curl/SDK replay still isolates the failure to inside openclaw rather than the upstream provider:

# Curl replay of an equivalent payload (same machine, same API key, same endpoint):
Run 1: HTTP=200 TTFB=8564ms TTLB=29469ms (385 chunks)
Run 2: HTTP=200 TTFB=4620ms TTLB=26856ms (404 chunks)
Run 3: HTTP=200 TTFB=7465ms TTLB=28809ms (399 chunks)
Run 4: HTTP=200 TTFB=8587ms TTLB=30926ms (382 chunks)
Run 5: HTTP=200 TTFB=4561ms TTLB=25669ms (397 chunks)
# 5/5 success — proves the issue is NOT in OpenRouter/Anthropic API.

# OpenAI Node.js SDK replay (same payload, same machine): also 5/5 success.

Impact and severity

  • Affected: any user whose model generates large tool-call parameters (large Write content, large structured payloads, etc.).
  • Severity: High — the call fails completely, all work in the subagent is lost, retries also fail.
  • Frequency: reliably reproducible with slow model + single large Write.

Additional information

Earlier hypotheses corrected:

  • Not bodyTimeout. OpenClaw already sets bodyTimeout/headersTimeout to 30 min via ensureGlobalUndiciStreamTimeouts(); an A/B test with bodyTimeout: 0 showed no change in failure rate.
  • Not "large accumulated context". Large context was a symptom, not the cause: large inputs prompt the model to generate large outputs, and large output is what triggers the bug.

Related: #43113, #49919, #48213.

Activity

  1. Hollychou924 commented on Mar 24, 2026

    @Hollychou924
  2. yilunzhang commented on Mar 24, 2026

    @yilunzhang
    Author

    Additional findings

    1. Reproduces on main agent (not subagent-specific)

    Tested by setting agents.defaults.model.primary to openrouter/anthropic/claude-opus-4.6 and running the same task directly (no sessions_spawn):

    direct-main-opus-1774347324.jsonl: 49L 905KB network_errors=1
    chapter_summaries_direct.md: NOT FOUND
    

    Same failure pattern — confirms this is an embedded runner issue, not subagent-specific.

    2. bodyTimeout is NOT the cause

    The commenter's hypothesis about undici bodyTimeout being too short was a reasonable guess, but doesn't match the evidence.

    Timing between last successful tool result and the error:

    2026-03-23T17:08:27.392Z | toolResult   (last successful)
    2026-03-23T17:10:44.839Z | assistant    in=0 out=0 err="Network connection lost."
    

    Gap: 137 seconds — well under both the default 300s bodyTimeout and OpenClaw's configured 30-minute bodyTimeout.

    A/B test (3 runs each): Patching bodyTimeout: 0 (disabled) vs original bodyTimeout: timeoutMs (30 min) showed no difference in failure rate. Both fail ~50% of the time with identical error patterns.

    Direct API replay succeeds 5/5: The same ~104K token payload, sent via both curl and the OpenAI Node.js SDK from the same machine to the same endpoint, succeeds every time with TTFB of 4.5-8.5s. This rules out any timeout-based hypothesis.

    Summary

    The error occurs 137 seconds into the request cycle (compaction + serialization + fetch). Something in the embedded runner's request pipeline causes the fetch to fail in a way classified as "Network connection lost" by is-network-error. It's not bodyTimeout, not headersTimeout, and not an upstream provider issue. The root cause is inside the embedded runner itself.

  3. clawsweeper commented on Apr 27, 2026

    @clawsweeper
    Contributor

    Codex review: this still needs some work.

    Summary
    This issue preserves concrete failures reported on an official OpenClaw release; current timeout and SSE keepalive improvements do not establish that the large-tool-argument failure is fixed.

    Reproducibility: no. high-confidence current-main reproduction is available: source establishes finite silence deadlines, while the reporter's historical evidence does not identify which deadline or transport produced the network error.

    Next step
    Establish a current large-argument OpenRouter reproduction with sanitized wire timings, effective provider and run budgets, and the raw error cause before specifying a repair.

    Review details

    Best possible solution:

    Use the existing provider timeout for measured silent generations, then repair the responsible transport boundary if current traces show an unexpected abort.

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

    No high-confidence current-main reproduction is available: source establishes finite silence deadlines, while the reporter's historical evidence does not identify which deadline or transport produced the network error.

    Is this the best way to solve the issue?

    A broad default-timeout increase is premature; the existing provider override and recent keepalive repair should be evaluated against a current timed reproduction before specifying another change.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • No current OpenRouter trace distinguishes genuine wire silence, comment-only keepalives, an OpenClaw deadline, and an upstream transport disconnect.
    • The reported generic network error has not been connected to a specific current-source failure.

    Codex review notes: model internal, reasoning medium; reviewed against aec6e7a56eb0.

    Label changes

    Label changes:

    No label changes.

    Label justifications:

    • P2: Large generated tool arguments can prevent an agent task from completing, but current-version frequency and the responsible boundary remain unverified.
    • impact:session-state: The reported run terminates before generated work becomes an executed tool call or output file.
    Evidence reviewed

    What I checked:

    Likely related people:

    • Peter Steinberger: Raw commit 5554f7c adds src/agents/embedded-agent-runner/run/llm-idle-timeout.ts:270 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5554f7c81ff6; files: src/agents/embedded-agent-runner/run/llm-idle-timeout.ts)
    How this review workflow works
    • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
    • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
    • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
    • Maintainers can also comment @clawsweeper review to request a fresh review only.
    • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge; those execution lanes are retired.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

    Reviewed October 10, 2026, 2:36 PM ET / 18:36 UTC.

  4. changed the title [-][Bug]: Embedded runner "Network connection lost" on LLM call after accumulating large context (~100K+ tokens) via tool results[/-] [+][Bug]: Embedded runner "Network connection lost" when LLM generates a tool call with large parameters (param generation latency > underlying request timeout)[/+] on Apr 27, 2026
  5. yilunzhang commented on Apr 27, 2026

    @yilunzhang
    Author

    Edited the title and body of this issue to reflect a sharper understanding of the bug.

    The earlier framing ("Network connection lost on LLM call after accumulating ~100K+ tokens of context via tool results") was the symptom I first noticed; the actual cause is the size of the tool-call parameters the LLM is generating, not the size of the input context. The easiest reproducer is now Write with a large file in one tool call from a slow model in a subagent — Write is just an example, any tool call where time-to-produce-params > underlying timeout will hit this.

    Earlier comments above (including the Codex automated review) are based on the older framing. Likely fixes from my side are listed in the rewritten body: increase the idle timeout for subagent LLM calls, and/or enable tool-use streaming (e.g. Anthropic fine-grained-tool-streaming-2025-05-14) where supported.

  6. clawsweeper commented on Apr 29, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.

    Keep open. Current main has timeout plumbing that can mitigate configured setups, but it does not prove a complete fix for the default OpenRouter to Anthropic large tool-parameter path: OpenRouter still uses the OpenAI-compatible transport, native Anthropic fine-grained tool streaming is not applied to that route, and there is no regression covering a silent OpenAI-compatible stream while large tool-call arguments are generated.

    Required change / next step:

    The report is valid enough to keep open, but a fix needs maintainer/provider-policy choice before automation: increasing default timeouts, adding OpenRouter-specific Anthropic streaming, or changing large tool-payload behavior each has different compatibility and latency tradeoffs.

    Review details

    Best possible solution:

    Keep this as the canonical tracker for OpenRouter/Anthropic large tool-parameter generation failures. The durable fix should add a synthetic OpenAI-compatible streaming regression that withholds tool-call argument chunks, then implement the chosen provider/runtime policy: supported provider-side tool-argument streaming, a safe timeout policy for silent tool-argument generation, or a tool-loop strategy that avoids requiring one huge Write payload.

    Acceptance criteria:

    • pnpm test src/agents/pi-embedded-runner/run/llm-idle-timeout.test.ts src/agents/openai-transport-stream.test.ts
    • pnpm test extensions/openrouter/index.test.ts extensions/openrouter/provider-runtime.contract.test.ts
    • pnpm check:changed in Testbox if runtime/provider behavior changes

    What I checked:

    Likely related people:

    • Peter Steinberger: Available current-main history and blame for the embedded-runner timeout, OpenAI transport, and OpenRouter provider paths point to Peter-authored commits, including recent OpenRouter params and embedded-runner logging work near this surface. (role: recent maintainer / adjacent owner; confidence: medium; commits: a972c9ec4547, 46171d7848d0, 66cdbccc8a2a; files: src/agents/pi-embedded-runner/run/llm-idle-timeout.ts, src/agents/pi-embedded-runner/run/attempt.ts, src/agents/openai-transport-stream.ts)

    Remaining risk / open question:

    • No live OpenRouter replay was run in this read-only review, so the exact current failure threshold still needs to be measured against OpenRouter and the affected Anthropic model.
    • Recent timeout plumbing may help users who explicitly set models.providers.openrouter.timeoutSeconds or use no-timeout subagent runs, but the default direct-agent OpenRouter path still lacks source or test proof for this report.

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

  7. added
    issue-rating: 🦞 diamond lobster
    clawsweeper:source-repro
    clawsweeper:no-new-fix-pr
    clawsweeper:fix-shape-clear
    clawsweeper:needs-maintainer-review
    clawsweeper:needs-product-decision
    P1
    impact:message-loss
    impact:session-state
    on May 19, 2026
  8. 31 remaining items

  9. added
    P2
    issue-rating: 🐚 platinum hermit
    clawsweeper:needs-live-repro
    and removed
    P1
    clawsweeper:source-repro
    issue-rating: 🦞 diamond lobster
    on Sep 21, 2026
  10. added
    issue-rating: 🦪 silver shellfish
    and removed
    clawsweeper:needs-product-decision
    clawsweeper:needs-live-repro
    issue-rating: 🐚 platinum hermit
    on Oct 10, 2026
  11. steipete commented on Oct 22, 2026

    @steipete
    Contributor

    Thanks for filing this. We're closing issues opened before April 2026 that no longer look actionable on current main.

    Transport timeouts and streaming for this path have been reworked since April, and we couldn't confirm the 'Network connection lost' failure on large tool-call arguments on current main; there has been no confirmation on a recent release. If it still happens, please open a fresh issue with your version, provider route, and logs.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:needs-maintainer-reviewclawsweeper:no-new-fix-primpact:session-stateissue-rating: 🦪 silver shellfish

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions