Skip to content

fix: keep the Gateway responsive during reply-tagged streams - #166782

Merged
obviyus merged 9 commits into
openclaw:mainfrom
boeingchoco:perf/markdown-ownership-settled-blocks
Oct 13, 2026
Merged

obviyus merged 9 commits into
openclaw:mainfrom
boeingchoco:perf/markdown-ownership-settled-blocks

Conversation

@boeingchoco

@boeingchoco boeingchoco commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Closes #166781

What Problem This Solves

Fixes: a long streamed reply containing a reply directive repeatedly parses the entire Markdown document, keeping the Gateway busy and potentially timing out delivery.

User Impact

Long replies whose already-consumed directives cannot change on append keep streaming without repeated whole-document parsing. Final text, reply targets, code examples, and existing silent/audio behavior are preserved. No configuration or migration is needed.

Why This Change Was Made

The repeated work originates in handleMessageUpdate: resolveStreamingReply re-parses the accumulated reply, then previous/next block snapshots parse it again. The caller already owns the previous rendered text and the exact append.

Reuse those facts when the previous directive has a settled visible suffix, no code opener precedes it, and the append introduces neither a new marker nor a reference definition or media directive. All other cases retain the canonical full-context parser. The block chunker also consumes an already-proven append instead of reconstructing identical snapshots.

This replaces the proposed Markdown ownership cache entirely: no new cache module, global retained text, JSON comparisons, or ownership copies. The original contributor commits remain credited. Production delta against the merge base is +34/-3 (net +31); tests +19/-0.

Evidence

Built, isolated Gateway with QA channel and a scripted Responses provider. Baseline d6b01a200752e8f121bc21263c6563bee058b1b4; candidate 437aaf724d38b57bd0987619f6b5226fac6cef9a. Same 8,180-character body in 20-character SSE deltas; health RPC sampled every 50 ms.

Case Base delivery Candidate delivery Base health median / p95 / max Candidate health median / p95 / max
Reply directive 13,973 ms 1,230 ms 41 / 105 / 242 ms 11 / 289 / 289 ms
Untagged 313 ms 549 ms 9 / 23 / 23 ms 18 / 28 / 28 ms
Literal directive inside a code fence 6,775 ms 6,088 ms 19 / 68 / 252 ms 19 / 51 / 246 ms

These are individual observations, not a tail-latency guarantee. To check the apparently slower untagged pair, three alternating fresh-Gateway runs measured two untagged deliveries each:

  • Base: 747, 479, 707, 533, 1,150, 503 ms; median 620 ms.
  • Caller-only fix: 676, 405, 827, 400, 588, 387 ms; median 496.5 ms.

The initial 313-to-549/656 ms comparison was not a reproducible common-path regression. The existing untagged fast path remains first and does not enter the new directive work. The caller-only experiment also matched the discarded cache's tagged delivery time: 1,278 ms versus 1,253 ms, with identical output.

All final text hashes match baseline, including the fenced control, and every observed reply targets its inbound message. Tagged and untagged SHA-256: 25c686744f794a630a822e7a6f6ccdcc2ae6067712bdd6f0ae9baa57ce0c1aae. Fenced control: 513fc12d020013efe1b6a0fb589cf7f92dbe91f10d6f682eea5c2451e6a14e19; the literal tag survives.

With the original token-sized fixture, the baseline saturated a CPU for about 89 seconds and its Responses request timed out without the expected final answer. The bounded-delta comparison above permits completed-output equivalence checks.

  • oxfmt and oxlint pass on changed files.
  • The retained delivery suite passes all 16 tests in 19.38 s; the Markdown code-span suite also passes. The long-stream regression fails on the baseline at 11,391 ms against its 1,000 ms bound and passes on the candidate in 5 ms. Redundant final-only oracle rows were removed; existing distinct code, reference, and reply-boundary tests are retained.
  • Production build and both Gateway scenarios pass on the candidate.
  • Real-provider CLI smoke with openai/gpt-5.4-mini returns OPENCLAW_STREAM_DIRECTIVE_LIVE_OK on the candidate.
  • Checked Pash's a2bbcbf4068: commentary final-message handling and quiet Slack preview policy are untouched.

Thanks to @boeingchoco for reporting the issue and the original fix and proof.

Merge danger: two-way door; a revert restores previous processing with no persisted-state changes. Blast radius: streaming directive projection and block replies; uncertain Markdown contexts continue using the existing parser.

…ies stream

Once a streamed reply contains a reply directive tag such as
[[reply_to_current]], reply directive parsing and block-reply snapshots
re-parse the whole reply's Markdown code ownership about ten times per
delta, so a tagged reply costs O(n^2) CPU: 8,000 characters streamed as
token-sized deltas took about 70 s.

Cache parseMarkdownOwnership for calls without options. Ownership before
a settled top-level block is reused and parsing resumes at that block,
and the last results are reused for repeated texts. A settled block
starts with a visible character at column 0 after a blank line that
follows a paragraph, heading, thematic break, or fenced code block,
where micromark's container, lazy-line, and interrupt state is reset,
and parsing from it must reproduce the whole parse. Text that may hold
a link reference definition is never resumed.
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 7, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses settled directive text and prepared appends to avoid repeatedly parsing complete streamed replies.

Example: An 8,180-character answer containing [[reply_to_current]] arrives in 20-character SSE deltas.

  • Before: The supplied baseline Gateway run delivered the answer in 13,973 ms.
  • After: The candidate delivered it in 1,230 ms with matching final text and the same inbound reply target.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, useful optimization with shipped Gateway proof, a discriminating subscriber regression, and no open findings or low-value added tests.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied exact-candidate built Gateway proof exercises production Responses streaming and QA-channel delivery with tagged, untagged, and fenced controls, recording faster tagged delivery, matching final hashes, preserved reply targets, and bounded health observations.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: A long answer carrying a reply directive streams slowly and can time out while consuming shared Gateway CPU.
Reason: The patch addresses a demonstrated common-path slowdown while preserving intended output, configuration, and persisted state.

Merge readiness

✅ Ready for maintainer review

This PR fixes a demonstrated Gateway streaming slowdown that remains on current main; the focused patch has relevant Gateway proof and no actionable review findings.

Priority: P1
Reviewed head: 437aaf724d38b57bd0987619f6b5226fac6cef9a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded-agent subscriber converts provider text events into visible partial replies and block replies, interpreting delivery directives before channel delivery.

flowchart LR
  A[Provider text events] --> B[Message update owner]
  B --> C[Streaming directive projection]
  C --> D[Canonical parser fallback]
  C --> E[Partial reply output]
  B --> F[Block reply chunker]
  F --> G[Channel delivery]
Loading

Technical review

Best possible solution:

Land the focused stream-owner optimization once the required checks pass.

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

Current-main source exposes repeated complete directive parsing and block snapshots, supported by supplied before/after Gateway observations; this read-only review ran no target code.

Is this the best way to solve the issue?

Reusing the stream owner's prepared append addresses the demonstrated cause while preserving canonical parsing for uncertain contexts and avoiding a separate Markdown ownership cache.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 6c1dde5 adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:382 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6c1dde5291ad; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)
  • lzhan011: Raw commit cdea681 adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:375 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: cdea681b1c2b; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)

PR surface

Source +31, Tests +19. Total +50 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 34 3 +31
Tests 1 19 0 +19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 53 3 +50

Review metrics

Metric Value Why it matters
Production versus test LOC Production +34/-3; tests +19/-0 The production growth reuses existing caller facts without introducing a cache or competing parser, and the retained test protects the demonstrated slowdown.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #166781
Summary: This PR provides the focused fix for the paired open report about repeated whole-reply parsing.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Long reply-tagged streams occupy synchronous Gateway processing, and the supplied baseline timed out before delivering the expected answer.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (6 earlier review cycles)
  • reviewed 2026-10-07T22:43:30.006Z sha 72b1dbc :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-07T22:50:42.766Z sha 72b1dbc :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-08T01:25:01.993Z sha 72b1dbc :: needs changes before merge. :: none
  • reviewed 2026-10-08T03:26:45.224Z sha 72b1dbc :: needs maintainer review before merge. :: none
  • reviewed 2026-10-13T02:41:10.013Z sha 72b1dbc :: needs maintainer review before merge. :: none
  • reviewed 2026-10-13T03:00:58.782Z sha 00a891a :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 11:14 PM ET / October 13, 2026, 03:14 UTC (Revision 7).

@boeingchoco

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added the requested running-Gateway proof to the PR body ("Running Gateway (QA Lab, isolated state)" under Evidence): a long [[reply_to_current]] answer streamed through a real Gateway child with qa-channel and the mock OpenAI Responses provider, 3 runs on main and 3 with this PR, with Gateway health round trips, the delivered text, replyToId, and the model requests the provider received.

@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 8, 2026
@boeingchoco
boeingchoco marked this pull request as ready for review October 8, 2026 03:22
Copilot AI balanced review requested due to automatic review settings October 8, 2026 03:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@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 Oct 8, 2026
@obviyus obviyus changed the title perf(markdown): stream reply-tagged answers without re-parsing the whole reply on every delta fix: keep the Gateway responsive during reply-tagged streams Oct 13, 2026
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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 Oct 13, 2026
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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 Oct 13, 2026
@obviyus
obviyus merged commit 3a2160c into openclaw:main Oct 13, 2026
115 of 116 checks passed
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

Landed in 3a2160c. Thanks @boeingchoco! Verified on a built Gateway: a long reply-tagged stream now delivers in about 1.2 s instead of 14 s, with identical final text and reply targets. We replaced the Markdown cache with an append fast path in the existing stream owner, so production went from +257 to +31 lines.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…w#166782)

fix(agents): reuse settled directive text while streaming long tagged replies

Long streamed replies containing reply directives re-parsed the whole Markdown document on every delta, holding the Gateway event loop and delaying delivery by many seconds. When a delta is a proven append after a settled directive (no code openers before the marker, no new markers and no reference definitions), the stream owner now reuses the previous cleaned text and appends the delta. Anything uncertain still takes the full parse.

Proof: built Gateway, QA channel, scripted Responses stream with an 8,180-character tagged reply: delivery took 13,973 ms on main and 1,230 ms on the candidate; health median went from 41 ms to 11 ms. Final text hashes and reply targets are identical for the tagged, untagged and fenced-directive controls. Untagged delivery median: 620 ms on main, 497 ms on the candidate.

Fixes openclaw#166781. Thanks @boeingchoco.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 15, 2026
fix(agents): reuse settled directive text while streaming long tagged replies

Long streamed replies containing reply directives re-parsed the whole Markdown document on every delta, holding the Gateway event loop and delaying delivery by many seconds. When a delta is a proven append after a settled directive (no code openers before the marker, no new markers and no reference definitions), the stream owner now reuses the previous cleaned text and appends the delta. Anything uncertain still takes the full parse.

Proof: built Gateway, QA channel, scripted Responses stream with an 8,180-character tagged reply: delivery took 13,973 ms on main and 1,230 ms on the candidate; health median went from 41 ms to 11 ms. Final text hashes and reply targets are identical for the tagged, untagged and fenced-directive controls. Untagged delivery median: 620 ms on main, 497 ms on the candidate.

Fixes #166781. Thanks @boeingchoco.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 3a2160c)

Backport note: the release branch wraps the block-reply plain-append check in an
isPhasePendingText guard; the widened plainAppend condition is applied inside it.
resolveStreamingReply is byte-identical to main after the port.
RomneyDa pushed a commit that referenced this pull request Oct 15, 2026
fix(agents): reuse settled directive text while streaming long tagged replies

Long streamed replies containing reply directives re-parsed the whole Markdown document on every delta, holding the Gateway event loop and delaying delivery by many seconds. When a delta is a proven append after a settled directive (no code openers before the marker, no new markers and no reference definitions), the stream owner now reuses the previous cleaned text and appends the delta. Anything uncertain still takes the full parse.

Proof: built Gateway, QA channel, scripted Responses stream with an 8,180-character tagged reply: delivery took 13,973 ms on main and 1,230 ms on the candidate; health median went from 41 ms to 11 ms. Final text hashes and reply targets are identical for the tagged, untagged and fenced-directive controls. Untagged delivery median: 620 ms on main, 497 ms on the candidate.

Fixes #166781. Thanks @boeingchoco.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 3a2160c)

Backport adaptation: applied the plainAppend condition change inside the release branch's phase-pending guard block.
RomneyDa added a commit that referenced this pull request Oct 15, 2026
#172710)

fix(agents): reuse settled directive text while streaming long tagged replies

Long streamed replies containing reply directives re-parsed the whole Markdown document on every delta, holding the Gateway event loop and delaying delivery by many seconds. When a delta is a proven append after a settled directive (no code openers before the marker, no new markers and no reference definitions), the stream owner now reuses the previous cleaned text and appends the delta. Anything uncertain still takes the full parse.

Proof: built Gateway, QA channel, scripted Responses stream with an 8,180-character tagged reply: delivery took 13,973 ms on main and 1,230 ms on the candidate; health median went from 41 ms to 11 ms. Final text hashes and reply targets are identical for the tagged, untagged and fenced-directive controls. Untagged delivery median: 620 ms on main, 497 ms on the candidate.

Fixes #166781. Thanks @boeingchoco.

Backport note: on 2026.9.33 the block-chunker plainAppend check sits inside the
phase-pending guard; the widened append condition is applied there unchanged.


(cherry picked from commit 3a2160c)

Co-authored-by: boeingchoco <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
LibraHo added a commit to LibraHo/openclaw that referenced this pull request Oct 20, 2026
…reset for 8.35-C

Backport OpenClaw PRs openclaw#168400, openclaw#169728, openclaw#166782 and openclaw#135653 onto the existing 2026.8.35 custom release. Preserve the 8.35 UI, locked dependencies, schema versions, bundled Codex and previous A/B maintenance repairs.

Canonical build source: 06aadf04949b9aaa0d2665c952124df700ccc191
Verified complete source tree: 4d9e205
Upstream base: 713ba57

Runtime checks run inside the single resource-bounded Docker build. Memory reset is an explicit operator command and is not executed during build or deployment.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

[Bug]: Streaming a reply that contains [[reply_to_current]] re-parses the whole reply on every delta

3 participants