Skip to content

fix(ai): prevent crash from circular references in provider error handlers - #108687

Closed
LiuwqGit wants to merge 4 commits into
openclaw:mainfrom
LiuwqGit:fix/circular-serialize-crash-106568-106570
Closed

LiuwqGit wants to merge 4 commits into
openclaw:mainfrom
LiuwqGit:fix/circular-serialize-crash-106568-106570

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves a problem where users streaming responses from Google, OpenAI Completions, or Anthropic providers would encounter unhandled process crashes and silent stream hangs when network errors occurred. The crash was caused by circular references in the underlying error objects (common for fetch/socket errors), which made JSON.stringify throw inside the catch block, preventing the stream from being properly closed.

Also applies the same fix to the Anthropic provider, which had the identical vulnerability at anthropic.ts:939.

Why This Change Was Made

Three provider error handlers (google-shared.ts, openai-completions.ts, anthropic.ts) used the unsafe pattern:

output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);

When error is a non-Error object with circular references (e.g., a fetch error with a socket property), JSON.stringify throws, bypassing stream.push() and stream.end().

The fix extracts a shared safeStringifyError() utility that handles circular references gracefully, mirroring the existing safe pattern already used in openai-responses.ts and azure-openai-responses.ts.

User Impact

  • Prevents process crashes and unhandled promise rejections during network errors in Google, OpenAI Completions, and Anthropic provider streams
  • Ensures stream.end() is always called in error handlers, preventing resource leaks (open file descriptors, hung stream consumers)
  • No behavior change for normal (non-circular) errors — Error.message is still used for Error instances, JSON.stringify for serializable objects

Evidence

Before fix: When a circular-reference error occurred in a provider stream catch block, JSON.stringify(error) threw TypeError: Converting circular structure to JSON, crashing the process and leaving the stream open (no stream.end() call). This caused unhandled rejections and resource leaks.

After fix: safeStringifyError() catches the circular-reference case and returns a fallback string ([Circular: <type>]) instead of throwing. stream.push() and stream.end() always execute in the catch block, properly closing the stream.

Tests:

  • Type check: pnpm tsgo:core passes
  • 119 existing tests pass across all three affected provider test suites
  • 6 new tests added for safeStringifyError covering: Error instances, subclassed errors, plain objects, primitives, circular references, and objects that throw on stringify

LiuwqGit added 4 commits July 11, 2026 10:05
Fixes openclaw#103956

The load-time stale-entry pruning in `loadSessionStore()` was gated by
entry count exceeding `maxEntries`, causing `pruneAfter` to be silently
ignored when the store was under the limit. Remove the entry-count gate so
that `pruneStaleEntries` runs whenever mode is `"enforce"`, matching the
pattern already established in `applyEnforcedMaintenance()`.

Changes:
- Remove `&& beforeCount > maintenance.maxEntries` condition from pruning block
- Keep capping step gated by `shouldRunSessionEntryMaintenance` as before
- No behavioral change to capping logic
Fixes openclaw#103956

The load-time stale-entry pruning in `loadSessionStore()` was gated by
entry count exceeding `maxEntries`, causing `pruneAfter` to be silently
ignored when the store was under the limit. Remove the entry-count gate so
that `pruneStaleEntries` runs whenever mode is `"enforce"`, matching the
pattern already established in `applyEnforcedMaintenance()`.

This fix is applied on top of the model-run pruning feature, preserving
the entry-count gate for model-run pruning while removing it for regular
session pruning.
…dlers

JSON.stringify(error) throws TypeError when the error object contains
circular references (common for network/fetch errors with socket
properties), which crashes the catch block and prevents stream.push()
and stream.end() from executing, causing unhandled rejections and
resource leaks.

Introduce safeStringifyError() that falls back to String() when
JSON.stringify fails, and apply it to google-shared, openai-completions,
and anthropic providers.

Fixes openclaw#106568
Fixes openclaw#106570
@openclaw-barnacle openclaw-barnacle Bot added size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 16, 2026
@clawsweeper

clawsweeper Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 16, 2026, 4:39 AM ET / 08:39 UTC.

Summary
Adds a shared error-stringification helper to Anthropic, Google, and OpenAI Completions stream handlers with unit tests, while also adding local agent automation configuration and changing session-store pruning.

PR surface: Source +10, Tests +43, Other +185. Total +238 across 7 files.

Reproducibility: yes. at source level: throwing a circular non-Error value through any of the three current-main catch handlers makes JSON.stringify throw before stream.push and stream.end. No live provider reproduction was established in the PR evidence.

Review metrics: 1 noteworthy metric.

  • Unrelated change surfaces: 2 additional surfaces. The branch mixes contributor-local automation configuration and session-state maintenance into a provider error-handling fix.

Stored data model
Persistent data-model change detected: serialized state: packages/ai/src/providers/anthropic.ts, serialized state: packages/ai/src/providers/error-utils.ts, serialized state: packages/ai/src/providers/google-shared.ts, serialized state: packages/ai/src/providers/openai-completions.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦪 silver shellfish
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Remove .agents/fix-pr-config.yaml and all unrelated session-pruning commits.
  • [P1] Make safeStringifyError total and add provider-level stream-closure regression tests.
  • [P1] Attach redacted after-fix terminal output or runtime logs from a real provider path.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR reports unit tests and typechecking but no after-fix provider run or runtime log; add redacted terminal or live-output evidence showing a circular non-Error failure emits an error event and closes the stream, then update the PR body to trigger re-review or ask a maintainer for @clawsweeper re-review.

Risk before merge

  • [P1] The unrelated session-store change could prune persisted session entries under conditions not reviewed or validated by this provider-focused PR.
  • [P2] The new helper can still throw during fallback conversion or produce undefined, leaving a residual path to the same stream-handling failure it intends to eliminate.
  • [P1] The committed .agents configuration exposes contributor-local infrastructure details and introduces unrelated repository automation commands.

Maintainer options:

  1. Narrow and harden before merge (recommended)
    Drop the local automation file and session commits, make the formatter unconditionally non-throwing and string-valued, add provider-level regression coverage, and attach redacted live proof.
  2. Replace with a clean provider-only PR
    Close this branch and submit a fresh PR containing only the provider helper, affected handlers, focused tests, and real behavior evidence.

Next step before merge

  • [P1] The contributor should narrow and harden the branch and supply real runtime proof; automation cannot provide the contributor-owned environment evidence required for merge.

Security
Needs attention: The provider fix itself does not weaken a security boundary, but the unrelated committed agent configuration exposes contributor-local infrastructure details and defines executable automation commands.

Review findings

  • [P1] Remove the contributor-local agent configuration — .agents/fix-pr-config.yaml:1
  • [P1] Drop the unrelated session-pruning change — src/config/sessions/store-load.ts:459
  • [P2] Make the error formatter truly non-throwing — packages/ai/src/providers/error-utils.ts:6-8
Review details

Best possible solution:

Land a narrow provider-only patch with a total non-throwing formatter that always returns a string, provider-level regression coverage confirming error emission and stream closure, and redacted live runtime proof; exclude all session and contributor-local automation changes.

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

Yes at source level: throwing a circular non-Error value through any of the three current-main catch handlers makes JSON.stringify throw before stream.push and stream.end. No live provider reproduction was established in the PR evidence.

Is this the best way to solve the issue?

No. Centralizing error formatting is the correct boundary, but this implementation must guarantee a non-throwing string result and the branch must exclude unrelated automation and session-maintenance changes.

Full review comments:

  • [P1] Remove the contributor-local agent configuration — .agents/fix-pr-config.yaml:1
    This file is unrelated to provider error handling and commits workstation paths, identity metadata, an internal proxy, and executable automation commands. Remove it from the branch; local .agents files belong in .git/info/exclude, not the repository.
    Confidence: 0.99
  • [P1] Drop the unrelated session-pruning change — src/config/sessions/store-load.ts:459
    This PR also changes persisted session maintenance so stale pruning runs independently of the entry cap. That behavior belongs to a separate reviewed fix with its own session-state tests; retaining it here gives this provider PR an unrelated data-removal risk.
    Confidence: 0.99
  • [P2] Make the error formatter truly non-throwing — packages/ai/src/providers/error-utils.ts:6-8
    JSON.stringify can return undefined, and the fallback String(error) can throw for objects whose primitive coercion fails. Handle an undefined JSON result and guard the fallback conversion so every input produces a safe string instead of reopening the stream-crash path.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add P1: The intended fix addresses provider stream crashes and hangs affecting active agent workflows, but the current patch has merge-blocking correctness and scope defects.
  • add merge-risk: 🚨 session-state: The branch independently changes when persisted session entries are pruned, which could alter or remove session state after merge.
  • add merge-risk: 🚨 availability: The formatter can still throw during fallback conversion, allowing the provider catch handler to fail before emitting and ending the stream.
  • add merge-risk: 🚨 automation: The PR adds a repository-local agent configuration with executable commands and contributor-specific environment settings unrelated to the stated fix.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.

Label justifications:

  • P1: The intended fix addresses provider stream crashes and hangs affecting active agent workflows, but the current patch has merge-blocking correctness and scope defects.
  • merge-risk: 🚨 session-state: The branch independently changes when persisted session entries are pruned, which could alter or remove session state after merge.
  • merge-risk: 🚨 availability: The formatter can still throw during fallback conversion, allowing the provider catch handler to fail before emitting and ending the stream.
  • merge-risk: 🚨 automation: The PR adds a repository-local agent configuration with executable commands and contributor-specific environment settings unrelated to the stated fix.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
Evidence reviewed

PR surface:

Source +10, Tests +43, Other +185. Total +238 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 5 16 6 +10
Tests 1 43 0 +43
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 185 0 +185
Total 7 244 6 +238

Security concerns:

  • [medium] Remove contributor-local automation metadata — .agents/fix-pr-config.yaml:1
    The added .agents configuration publishes personal and internal environment metadata and includes command definitions that are unrelated to this PR; remove the entire file before merge.
    Confidence: 0.99

What I checked:

  • Current-main bug path: Current main still calls JSON.stringify directly for non-Error values in the Google, OpenAI Completions, and Anthropic stream catch handlers, so a circular thrown object can interrupt error delivery and stream closure. (packages/ai/src/providers/google-shared.ts:468, aaf5d23883a1)
  • Proposed shared fix: The PR replaces the three unsafe call sites with safeStringifyError and adds focused utility tests, directly addressing the two linked reports and the matching Anthropic path. (packages/ai/src/providers/error-utils.ts:1, fd36d336b72b)
  • Incomplete safety guarantee: JSON.stringify may return undefined, while the fallback String conversion can itself throw for hostile or non-coercible objects; the helper therefore does not guarantee the declared string result or non-throwing error handling. (packages/ai/src/providers/error-utils.ts:6, fd36d336b72b)
  • Unrelated session behavior: The branch also removes the maxEntries gate from session-store pruning through separate commits referencing another issue, changing persisted session maintenance outside the provider-error fix. (src/config/sessions/store-load.ts:459, ec8deaa1f504)
  • Contributor-local configuration: The branch adds a large user-specific agent configuration containing absolute workstation paths, identity metadata, an internal proxy, and executable command definitions unrelated to provider error handling. (.agents/fix-pr-config.yaml:1, fd36d336b72b)
  • Repository policy: The full root AGENTS.md was read and applied; it requires focused ownership-aligned changes, repository test wrappers rather than raw Vitest, no committed live configuration, and local-only .agents exclusions through .git/info/exclude. (AGENTS.md:1, aaf5d23883a1)

Likely related people:

  • steipete: Merged the major runtime internalization that brought packages/ai into the OpenClaw-owned tree and is the strongest current-main routing candidate for provider-runtime changes. (role: internalization merger and recent area contributor; confidence: high; commits: bb46b79; files: packages/ai/src/providers/google-shared.ts, packages/ai/src/providers/openai-completions.ts, packages/ai/src/providers/anthropic.ts)
  • Mario Zechner: Authored the upstream Pi provider layer from which these OpenClaw provider implementations descend, including the OpenAI Completions error-handler surface. (role: upstream provider-source author; confidence: medium; commits: 1eee081e29c1; files: packages/ai/src/providers/openai-completions.ts, packages/ai/src/providers/anthropic.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

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.
  • 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.
Review history (1 earlier review cycle)
  • reviewed 2026-07-16T07:42:55.120Z sha fd36d33 :: needs real behavior proof before merge. :: [P1] Remove the contributor-local automation configuration | [P1] Drop the unrelated session-maintenance behavior change

@steipete

Copy link
Copy Markdown
Contributor

Closing per ClawSweeper review verdict low_signal_unmergeable_pr (decision packet 2026-07-16T09:23:18.580Z). This item was part of the audited close backlog (openclaw/clawsweeper#920) stranded by an apply-lane defect, drained manually after re-verification. If this is wrong, reopen and ClawSweeper will re-review.

@steipete steipete closed this Jul 29, 2026
@LiuwqGit
LiuwqGit deleted the fix/circular-serialize-crash-106568-106570 branch September 22, 2026 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants