Skip to content

fix(ollama): stop oversized stream records from growing memory - #107473

Merged
vincentkoc merged 6 commits into
openclaw:mainfrom
wahaha1223:fix/ollama-bound-ndjson-records
Jul 31, 2026
Merged

vincentkoc merged 6 commits into
openclaw:mainfrom
wahaha1223:fix/ollama-bound-ndjson-records

Conversation

@wahaha1223

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where users connected to a malfunctioning or hostile Ollama endpoint could see OpenClaw memory keep growing when the endpoint streamed an arbitrarily large NDJSON record without a newline.

Why This Change Was Made

The native Ollama parser now caps each pending NDJSON record at 16 MiB using the original response bytes, resets the count at every newline, and cancels the reader before reporting an overflow. The risk is bounded to individual records larger than 16 MiB; long streams made of valid smaller records remain supported, and this does not change request timeout behavior addressed by #96635.

User Impact

OpenClaw now stops an oversized Ollama stream record with an actionable error instead of retaining unbounded response data in memory. Normal multi-record Ollama responses continue to stream as before.

Evidence

AI-assisted.

Premise: Ollama documents streamed REST responses as newline-delimited JSON with the application/x-ndjson content type: https://docs.ollama.com/api/streaming. A request timeout does not bound a continuously arriving record that never reaches its newline delimiter.

Real machine / production-path proof used Linux 6.8.0-134-generic x86_64, Node v24.18.0, a real localhost node:http server exposing /api/chat, and the exported production createOllamaStreamFn. The server sent one 20 MiB JSON record in 1 MiB writes. The same temporary harness was run with:

node --import tsx /tmp/ollama-ndjson-real-proof.mts

Negative control / before, latest upstream/main (d6fc3d34e2010997d4f67807b30c336347808f31) in a detached worktree: the client accepted the complete 20,971,644-byte record and returned its ok content.

{"node":"v24.18.0","recordBytes":20971644,"bytesWritten":20971645,"responseClosed":true,"terminal":{"type":"done","content":[{"type":"text","text":"ok"}]}}

After, commit 296d1e03: the same production path stopped at the 16 MiB record cap, surfaced the overflow, and closed the live HTTP response before the server finished its payload.

{"node":"v24.18.0","recordBytes":20971644,"bytesWritten":19923066,"responseClosed":true,"terminal":{"type":"error","errorMessage":"Ollama NDJSON record exceeds 16777216 bytes"}}

Focused regression and controls:

node scripts/run-vitest.mjs extensions/ollama/src/stream-runtime.test.ts
Test Files  1 passed (1)
Tests  106 passed (106)

The focused tests prove overflow cancels the reader and that two separate 9 MiB newline-delimited records do not trip a total-stream cap. Targeted oxfmt, oxlint, and git diff --check also passed. autoreview --mode local --stream-engine-output reported no accepted/actionable findings (patch correct, confidence 0.96).

Not tested: a live Ollama daemon/model or remote host; the real HTTP proof uses an Ollama-compatible localhost endpoint so it can deterministically exercise the malformed-record condition without model credentials.

@wahaha1223
wahaha1223 force-pushed the fix/ollama-bound-ndjson-records branch from 296d1e0 to 0baca03 Compare July 14, 2026 15:14
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels Jul 14, 2026
@clawsweeper

clawsweeper Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 31, 2026, 5:54 AM ET / 09:54 UTC.

ClawSweeper review

What this changes

This PR adds a shared 16 MiB cap for each individual Ollama NDJSON stream record, cancelling newline-free oversized responses in native chat streaming and onboarding model pulls.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

This remains a useful, narrowly scoped Ollama safety fix. The branch has maintainer-confirmed acceptance of the intentional 16 MiB compatibility boundary and strong exact-head localhost proof, but it is behind current main and should receive a refreshed merge/check pass before landing rather than being closed or sent to an automated repair lane.

Priority: P2
Reviewed head: 93cdbe319e4797c2ea123cbe756cc216df0942a0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real-path proof and focused regression coverage support a bounded patch; a current-main refresh remains the material merge-readiness step.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body and final maintainer update provide exact-head, production-function localhost HTTP evidence that a 20 MiB newline-free response is cancelled early and returns the expected overflow error; no private data is shown.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body and final maintainer update provide exact-head, production-function localhost HTTP evidence that a 20 MiB newline-free response is cancelled early and returns the expected overflow error; no private data is shown.
Evidence reviewed 5 items Shared byte-level record cap: The branch introduces a shared helper that counts bytes only until each LF delimiter and throws once one pending record exceeds 16 MiB; it resets after a completed record rather than imposing a total-stream cap.
Both affected Ollama consumers use the same invariant: The changed native chat parser and onboarding pull reader each pass raw response chunks through the shared cap before decoding and buffering text, covering both user-facing streaming paths named by the PR.
Exact-head maintainer acceptance and real-path proof: The assigned member explicitly accepted 16 MiB as the maximum supported individual record and reported exact-head localhost HTTP proof that the production stream aborts, closes the response, and surfaces the overflow error after the cap is exceeded.
Findings None None.
Security None None.

How this fits together

The bundled Ollama extension consumes newline-delimited JSON from Ollama endpoints for model chat responses and onboarding download progress. Incoming byte chunks are accumulated into records, then parsed into agent output or setup progress; this patch rejects one oversized record before that accumulation can grow without a delimiter.

flowchart LR
  A[Ollama endpoint] --> B[NDJSON response bytes]
  B --> C[Per-record byte cap]
  C -->|within 16 MiB| D[NDJSON record parser]
  C -->|oversized| E[Cancel response reader]
  D --> F[Chat response stream]
  D --> G[Onboarding pull progress]
  E --> H[Actionable error]
Loading

Before merge

  • Resolve merge risk (P1) - The branch is cleanly mergeable but behind current main; rebase or merge-result validation must confirm the exact landing head still retains the cancellation and reader-release behavior.
  • Resolve merge risk (P1) - The accepted cap deliberately changes behavior for otherwise parseable Ollama-compatible streams containing a single record over 16 MiB; those endpoints now receive an actionable stream error instead of continued buffering.
  • Complete next step (P2) - No discrete automated repair is indicated; the remaining work is a normal current-main merge/check refresh for an otherwise reviewed patch.
Agent review details

Security

None.

PR surface

Source +31, Tests +71. Total +102 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 47 16 +31
Tests 2 71 0 +71
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 118 16 +102

Review metrics

Metric Value Why it matters
Protected streaming consumers 2 consumers share 1 per-record limit Native chat streaming and onboarding model pulls now apply the same byte-level boundary, reducing drift between two Ollama response readers.

Merge-risk options

Maintainer options:

  1. Land the accepted bounded-record behavior (recommended)
    Refresh the branch against current main and merge once exact-head validation confirms the 16 MiB per-record boundary and cancellation behavior remain intact.
  2. Pause if broader compatibility is required
    Do not merge if maintainers need to support individual Ollama NDJSON records above 16 MiB; choose and document a different bounded protocol limit instead.

Technical review

Best possible solution:

Rebase onto current main, preserve the shared raw-byte cap and awaited cancellation behavior in both consumers, then land after the refreshed exact-head checks confirm normal multi-record streams remain unaffected.

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

Yes for the proposed fix path: the PR documents a deterministic real localhost HTTP reproduction using the production stream function and reports an exact-head overflow result. This review did not independently execute that harness in the read-only checkout.

Is this the best way to solve the issue?

Yes. A shared raw-byte check before text decoding is the narrowest maintainable way to bound the undelimited-record buffer across both Ollama consumers, and the maintainer has explicitly accepted the compatibility limit.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f943a94a3303.

Labels

Label justifications:

  • P2: This is a bounded provider-stream memory-safety repair without evidence of a current broad runtime outage.
  • merge-risk: 🚨 compatibility: A previously accepted oversized individual Ollama NDJSON record now terminates with an error at the explicitly accepted 16 MiB limit.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body and final maintainer update provide exact-head, production-function localhost HTTP evidence that a 20 MiB newline-free response is cancelled early and returns the expected overflow error; no private data is shown.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and final maintainer update provide exact-head, production-function localhost HTTP evidence that a 20 MiB newline-free response is cancelled early and returns the expected overflow error; no private data is shown.

Evidence

What I checked:

  • Shared byte-level record cap: The branch introduces a shared helper that counts bytes only until each LF delimiter and throws once one pending record exceeds 16 MiB; it resets after a completed record rather than imposing a total-stream cap. (extensions/ollama/src/stream-ndjson-cap.ts:3, 93cdbe319e47)
  • Both affected Ollama consumers use the same invariant: The changed native chat parser and onboarding pull reader each pass raw response chunks through the shared cap before decoding and buffering text, covering both user-facing streaming paths named by the PR. (extensions/ollama/src/stream.ts:1090, 93cdbe319e47)
  • Exact-head maintainer acceptance and real-path proof: The assigned member explicitly accepted 16 MiB as the maximum supported individual record and reported exact-head localhost HTTP proof that the production stream aborts, closes the response, and surfaces the overflow error after the cap is exceeded. (93cdbe319e47)
  • Focused regression coverage: The PR adds tests for cancellation of an oversized unterminated chat record, reset after newline-delimited records, and cancellation during an oversized onboarding pull record. (extensions/ollama/src/stream-runtime.test.ts:1303, 93cdbe319e47)
  • Related timeout proposal is distinct: The referenced closed PR addressed refreshing an idle timeout on slow remote streams; this branch addresses a continuously arriving, newline-free record that can evade an idle timeout, so it is adjacent rather than a replacement. (extensions/ollama/src/stream.ts:1090, 93cdbe319e47)

Likely related people:

  • vincentkoc: Assigned this PR, rebased the final head onto main twice, and documented the accepted 16 MiB behavioral tradeoff with exact-head proof. (role: recent area contributor and decision owner; confidence: high; commits: ae3d3eca4b09, 93cdbe319e47; files: extensions/ollama/src/stream.ts, extensions/ollama/src/setup-pull.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase or validate the actual merge result against current main and complete the remaining exact-head check before landing.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • 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.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-07-14T16:04:41.986Z sha 0baca03897d7f6fae17ef1afa30abceb79f08c4c :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T16:30:01.645Z sha 0baca03897d7f6fae17ef1afa30abceb79f08c4c :: needs maintainer review before merge. :: none
  • reviewed 2026-07-16T02:08:52.570Z sha b959065 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-31T09:17:42.947Z sha ae3d3ec :: needs maintainer review before merge. :: none
  • reviewed 2026-07-31T09:45:46.202Z sha 93cdbe3 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Jul 14, 2026
@wahaha1223
wahaha1223 force-pushed the fix/ollama-bound-ndjson-records branch 2 times, most recently from 59c2bb2 to 04db57a Compare July 15, 2026 00:35
@wahaha1223
wahaha1223 force-pushed the fix/ollama-bound-ndjson-records branch from 04db57a to b959065 Compare July 15, 2026 00:40
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 31, 2026
@vincentkoc vincentkoc self-assigned this Jul 31, 2026
* preserve/pr-107473-ollama-stream-ndjson-cap: (5598 commits)
  chore(changelog): remove release-owned entry
  fix(agents): resume interrupted turns past progress commentary (openclaw#116725)
  fix(gateway): sign device proofs with challenge time (openclaw#116679)
  fix(testing): load relay smoke through UI Vite config
  test(testing): guard realtime relay smoke module path
  fix(testing): repair realtime relay live smoke import
  test: type session request parameters (openclaw#116713)
  fix: retain event invalidation for pagination
  docs: note queued session refresh fix
  fix: preserve queued session refresh options
  fix(exec): require approval for abbreviated inline eval flags [AI] (openclaw#116529)
  fix: keep owner-only tools out of non-owner skill commands [AI] (openclaw#116532)
  fix(ui): bound Talk relay microphone uplink
  fix(tui): require a fresh agent roster (openclaw#116715)
  fix(memory-wiki): preserve user edits when rolling back ChatGPT imports (openclaw#116517)
  fix(agents): cron failures preserve timeout and cancellation reasons (openclaw#116566)
  fix(release): unblock beta validation workflows (openclaw#116708)
  fix(ci): discover frozen target startup benchmark cases (openclaw#116711)
  fix(session): preserve reset message payloads (openclaw#116195)
  fix(qa): tolerate loaded-runner bus delivery stalls (openclaw#116448)
  ...
* origin/main:
  fix(googlechat): record canonical receipt thread (openclaw#116717)
  fix(edit): restore UTF-16 difference offsets
  fix(openai): share GPT-Live browser broker ownership
  fix(voice-call): cancel consults on bridge replacement
  fix(voice-call): recheck consult owner after await
  fix(voice-call): cancel pending replacement consults
  fix(voice-call): isolate replacement consult handoff
  test(voice-call): cover late forced consult teardown
  fix(voice-call): cancel forced consults on teardown
  fix(edit): prefer-for-of loop in firstDifferenceIndex
  fix(openai): return undefined from cleanup on non-disable reasons
  fix(openai): restrict GPT-Live broker cleanup to plugin disable only
@vincentkoc

Copy link
Copy Markdown
Member

Maintainer decision: accept 16 MiB as the maximum supported individual Ollama NDJSON record. This keeps more than 2x headroom over the current Ollama Go client scanner cap while bounding hostile newline-free responses. On exact head ae3d3ec, a real localhost HTTP server sent a 20,971,631-byte record; the production stream aborted after 18,874,368 bytes, closed the response, and emitted Ollama NDJSON record exceeds 16777216 bytes. Focused proof: 119 tests passed; fresh autoreview clean at 0.94.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 31, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Rebased/merged current main into the contributor branch at 93cdbe319e4797c2ea123cbe756cc216df0942a0, resolving the overlap with the landed setup response-body cleanup. The combined path now awaits reader cancellation before releasing the lock. Exact-head proof: 150 focused Ollama tests passed; targeted format/lint and git diff --check passed; fresh branch autoreview is clean (0.97); localhost production createOllamaStreamFn proof closed the response after 17,498,112 bytes with terminal error Ollama NDJSON record exceeds 16777216 bytes. The temporary proof file was removed and the worktree is clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Jul 31, 2026
@vincentkoc
vincentkoc merged commit a28219b into openclaw:main Jul 31, 2026
131 of 135 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 31, 2026
* commit 'refs/frozen/talk-pcm-output-main-refresh':
  fix(skills): allow autonomous sweep sync (#116755)
  fix(irc): recognize punctuation in nickname mentions (#116758)
  fix(plugins): require explicit source external startup (#116759)
  fix(whatsapp): keep sends running when typing presence fails (#116739)
  fix(cli): reject dangling config path escapes (#116738)
  fix(qa): authenticate summaries and bound native scenario commands (#116748)
  fix(bedrock): reject truncated streams and preserve audio results (#116743)
  docs(skill): isolate autonomous issue sweep worktrees
  fix(ci): retire Kova runtime deps coverage (#116760)
  chore(i18n): refresh native locales (#116640)
  fix(ollama): resolve web search secret refs (#104829)
  fix(ollama): honor stop sequences and async payload hooks (#116737)
  fix(ollama): stop oversized stream records from growing memory (#107473)
  fix(agents): preserve thinking for runtime-selected Ollama models (#116584)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
…law#107473)

* fix(ollama): bound pending NDJSON stream records

* chore(changelog): remove release-owned entry

---------

Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 1, 2026
* commit 'refs/frozen/talk-pcm-output-main-refresh':
  fix(skills): allow autonomous sweep sync (openclaw#116755)
  fix(irc): recognize punctuation in nickname mentions (openclaw#116758)
  fix(plugins): require explicit source external startup (openclaw#116759)
  fix(whatsapp): keep sends running when typing presence fails (openclaw#116739)
  fix(cli): reject dangling config path escapes (openclaw#116738)
  fix(qa): authenticate summaries and bound native scenario commands (openclaw#116748)
  fix(bedrock): reject truncated streams and preserve audio results (openclaw#116743)
  docs(skill): isolate autonomous issue sweep worktrees
  fix(ci): retire Kova runtime deps coverage (openclaw#116760)
  chore(i18n): refresh native locales (openclaw#116640)
  fix(ollama): resolve web search secret refs (openclaw#104829)
  fix(ollama): honor stop sequences and async payload hooks (openclaw#116737)
  fix(ollama): stop oversized stream records from growing memory (openclaw#107473)
  fix(agents): preserve thinking for runtime-selected Ollama models (openclaw#116584)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: ollama merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants