Skip to content

fix: reduce repeated parsing in streamed final answers - #175328

Merged
steipete merged 7 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/issue-175264
Oct 23, 2026
Merged

steipete merged 7 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/issue-175264

Conversation

@sunlit-deng

@sunlit-deng sunlit-deng commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes streamed final answers exposing tool-call text when a supported inline-link title closes across chunks, including titles after balanced or multiline destinations.

Fixes #175264

Why This Change Was Made

The stream reuses parsed Markdown ownership across appended chunks and refreshes it when link titles, image descriptions, reference definitions, GFM table delimiters, or indentation can change code ownership. HTML invalidation was removed because the canonical parser disables HTML flow and text nodes.

User Impact

Tool-call syntax stays hidden as Markdown syntax completes, while literal examples in indented, list, and fenced code remain visible.

Evidence

  • Exact base 2c5b726 and head 2d394cf: the same openclaw agent exec loopback Responses SSE proof matched canonical output, hid resolved tool calls, and preserved literal code. It recorded 351 ms on the base and 49 ms on the head for one run.
  • The 4,143-character open-call work-budget regression uses four-character appends and matches visible output: the merge base scans 4,297,278 characters against a 66,288-character budget; the head scans 16. It fails on the base and passes on the head. The focused streaming suite passed 16/16 cases.
$ OPENCLAW_VITEST_RUNTIME=node npm_config_manage_package_manager_versions=false node --import ./scripts/tsx.mjs scripts/proof-final-answer-stream.mts
entrypoint: openclaw agent exec via src/entry.ts
provider: one local OpenAI Responses SSE request
phase: final_answer
pending-call workload: 4,096 payload characters in 256-character deltas; measured 351 ms on base `2c5b726` and 49 ms on head `2d394cf`
response events: 84; tool-call deltas: 17
quoted-title transitions after balanced and multiline destinations: tool-call hidden
result: resolved link/image/reference calls hidden; list, indented, and fenced code calls preserved
status: ok

AI-assisted: built with Codex

Maintainer follow-up

The open-table checkpoint returned before applying canonical Markdown retention. An earlier image description could therefore be settled as literal code before a later reference definition revoked that code ownership, leaving a tool marker visible. The follow-up takes the earliest of the table boundary, canonical image/title retention, and long-label retention. This keeps the mutable-image/reference intent of #172832 (a8a67b01) intact instead of weakening literal-code preservation. Contributor commits and @sunlit-deng's ownership are preserved.

The added eight-case table-driven regression checks every two-chunk split, one-character and four-character chunkings, canonical output at each prefix, and delta reconstruction. It fails on the original production code in the three image/table cases and passes with the fix. The broader lane-only deterministic sweep covers escaped brackets and backslash runs, nested labels, one-to-three-backtick spans, reference titles, images, angle destinations, tables, ordinary/list/tilde/four-backtick fences, CRLF, tool markers, model control tokens, and long normalized labels: 439 documents, 37,836 chunkings, 119,743 prefix checks, zero divergences, 88.484 seconds. The original contributor head produced 418 divergences on that corpus.

Validation on macOS:

  • Five focused suites: 149 tests passed, 112.19 seconds wall. The changed streaming test file used 3.365 seconds of test execution; CI timing is pending.
  • Core types, scoped lint/format, max-lines, line-cap, assertion-safety, timeout-race, mock-export, config-docs, and plugin-inventory checks passed. Merging current main cleared a reproduced inherited max-lines baseline failure; the reviewed projection patch is byte-identical after that merge.
  • Full pnpm build passed in 49m33s on the shared Mac.
  • Built-CLI fixture: pnpm openclaw --profile projection-table agent exec sent one streaming Responses request (seven SSE events), produced the exact expected sanitized final output, and preserved fenced tool/model-control examples (103.584s, including startup). This checks transport/final rendering; the production-projector differential sweep checks prefix/delta parity.
  • Real local-model control: built openclaw agent exec with native Ollama llama3.2:latest returned the exact requested text in 106.530s, including startup. The first control with minimal tools instead returned a tool error; the recorded passing control uses the documented deny-all tool policy and exact-text assertion. Ollama is an unphased control, not a reproduction of Responses final_answer phase handling.
  • Isolated Codex autoreview: clean through P2, with no actionable findings.
  • A single 4,140-character pending-call sample through the production projector took 919 ms on main and 94 ms with this branch; ordinary prose controls took 4 ms and 7 ms. These are observations, not a statistical benchmark.

Follow-up LOC: production +2/-5 (net -3), tests +37. Full PR relative to current main: runtime production +615/-22, tests +499/-48, existing proof script/inventory +762. The contributor's cache machinery accounts for the production growth and avoids repeatedly parsing settled Markdown while retaining canonical invalidation.

Remote check follow-up

CI run 39892893645 passed the text checks and baseline ratchets, but checks-ui-e2e (6/9) failed chat-image-lightbox.e2e.test.ts:402: navigating back to after.png recorded a duplicate 1920px rendition request. The aggregate openclaw/ci-gate remains red. The entire UI and media-core source trees are unchanged from merged main 87aada17522b; the test routes all media requests (Playwright documents that routing disables HTTP cache), while the gallery retains the loaded URL through this navigation. The focused local scenario passed (10.423s test, 173.22s Vitest duration), which does not prove a CI repair. CI’s automatic pre-existing label names a main run with a different failure, so it is not matching-signature evidence; this remains an inherited-source UI/harness limitation for maintainer review. No retry or test weakening was used.

ClawSweeper re-review was requested after the push. After the requested 15-minute polling window, its published review still names the prior 2d394cf75428 head; no exact-head ClawSweeper verdict is available yet.

Maintainer follow-up: main merge

Merged main through e7c1640eed231b250c43166840a2ed6615f3704d without rebasing or replacing @sunlit-deng's commits. The conflict resolution keeps textSpans, unsettledDefinitionStarts, and unresolvedImageCodeStart. The semantic audit confirms that the model-token filter obtains fresh text spans; the ownership caches remain private to their checkpoint and tool-call consumers.

The required mixed-corpus proof exposed an additional defect already present on that main: an unfinished table delimiter could split a paragraph containing multiline code, then an ordinary appended character invalidated the table without restoring the literal control token. The canonical Markdown owner now retains that preceding paragraph until the delimiter settles. The checkpoint consumes that boundary directly, removing its duplicate table scanner. The small table-retention helper keeps the parser within its existing line cap. Three regression cases covering LF, CRLF, and CR failed before the fix and pass afterward, including full final-answer delivery and replacement deltas.

Validation on macOS, Node 26.12.1:

  • Projection sweep: 439 documents, 37,836 chunkings, 119,743 prefix checks, zero divergences, 26.195s.
  • Control-token sweep: 1,495 sources, 58,682 chunkings, 366,860 comparisons, zero divergences, 7.386s.
  • Mixed tables/images/reference definitions with both token families: 102 sources, 17,132 chunkings, 111,852 comparisons, zero divergences, 10.317s. The merged tree before the owner fix had 42 divergences on this corpus.
  • 449 focused tests passed in 88.28s wall, including all shared-text suites, both streaming-work suites, embedded-agent utilities, Markdown code spans, and tool-call payloads. Core types, scoped core/script lint, formatting, and required ratchets passed.
  • Isolated Codex autoreview on the final branch: scoped-clean through P2, no actionable findings.
  • The same 4,140-character open-call production-projector sample took 468ms on main and 78ms on the final branch; the ordinary-prose control remained 4ms. These are single-run observations; the bounded-work regressions also passed.

Fresh pnpm build runtime passed in 537.883s wall. Built pnpm openclaw --profile projection-merge agent exec sent one streaming loopback Responses request with eight SSE events, matched the exact expected final output, stripped image-alt controls, restored literal controls after table invalidation, and preserved fenced examples (37.977s). Native Ollama llama3.2:latest returned exactly LOCAL_MODEL_CONTROL_OK through the same real CLI (22.491s). The CLI checks transport/final rendering; prefix and delta parity are established by the sweeps. Ollama is an unphased local-model control. Local proof is macOS-only; no operator Gateway or shared model state was changed.

Owner follow-up: production +24/-61 (net -37), tests +15. Full PR against merged main: production +579/-22, tests +514/-48, existing proof script/inventory +762. The retained production growth is the contributor's stream-local ownership reuse and invalidation machinery; this follow-up removes duplicate table policy. Contributor history and credit are preserved. No new configuration, dependency, or public contract is introduced.

CI follow-up: wrapper inventory

CI run 39900038625 on f447065f0c4 failed the two PR-wrapper import-closure scenarios because the newly extracted table-code-retention.ts was omitted from the wrapper's source inventory. Both failures reproduced locally. Commit 010a449ef62e66b3e9f288f5709d2bb82fb077ef adds that one inventory entry; the same two tests then passed in 93.65s wall. This also addresses ClawSweeper's sole P2 finding on f447065f0c4.

No runtime code or test expectation changed in this follow-up. The semantic sweeps, 449 focused tests, build, and built-CLI/Ollama proof above remain applicable to the identical runtime tree. Full PR totals are production +579/-22, tests +514/-48, and proof/inventory +763. The inventory-only commit also passed focused Codex autoreview through P2 with no findings.

Final main-merge verification

Head 010a449ef62e66b3e9f288f5709d2bb82fb077ef: CI run 39901607679 passed, including openclaw/ci-gate (52 successful jobs). The broader check rollup is green, including security and dependency reviews. ClawSweeper's exact-head review reports no findings, no before-merge items, and sufficient proof. Its earlier pending-CI note is superseded by the completed successful run. Ready for maintainer review; not merged.

@clawsweeper

clawsweeper Bot commented Oct 17, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses Markdown ownership across streamed chunks and refreshes it when appended syntax can change code protection.

Example: A final answer streams an unfinished [tool:write] JSON payload containing 4,096 characters in four-character chunks.

  • Before: The recorded regression scans 4,297,278 characters while repeatedly parsing accumulated Markdown.
  • After: The recorded regression scans 16 characters while preserving the same provisional visible output.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Useful repair with shipped-CLI evidence, base-failing work-budget coverage, broad ownership-transition checks, and no remaining actionable finding; ordinary exact-head CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied evidence exercises built openclaw agent exec on macOS through a real loopback Responses SSE transport, verifies exact sanitized final output after image and table ownership changes, and includes a native Ollama control; production-projector sweeps separately verify prefix and replacement-delta parity, and the final inventory-only commit leaves that runtime tree unchanged.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long phased final answers can occupy the Gateway thread with repeated Markdown parsing and delay visible reply progress.
Reason: The linked report, work-budget regression, and recorded CLI run establish a concrete performance problem while the implementation preserves existing output contracts without adding configuration or public APIs.

Merge readiness

✅ Ready for maintainer review

This PR addresses a verified streaming-performance defect that remains on current main. The previous wrapper-inventory finding is fixed, and this review found no remaining actionable defect; exact-head CI is still pending.

Priority: P2
Reviewed head: 010a449ef62e66b3e9f288f5709d2bb82fb077ef

Before merge

None.

Findings

None.

Agent review details

How this fits together

Assistant response deltas enter the shared text projector, which uses canonical Markdown ownership to hide tool-call syntax while preserving literal code and emitting append or replacement deltas.

flowchart TD
  A[Provider response deltas] --> B[Assistant stream subscriber]
  B --> C[Shared text projection]
  C --> D[Markdown ownership parser]
  D --> E[Stream-local ownership reuse]
  E --> F[Tool-call filtering]
  F --> G[Visible text and replacement deltas]
Loading

Technical review

Best possible solution:

Land the stream-local ownership reuse with canonical invalidation after the required exact-head checks pass.

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

Current-main checkpoint code confirms the repeated whole-buffer parsing path described in #175264, and the supplied base-versus-head work regression demonstrates it; this read-only review ran no target code.

Is this the best way to solve the issue?

The change addresses the repeated parsing at the existing owners, preserves canonical output and replacement behavior, and keeps the model-token consumer on fresh ownership rather than sharing incompatible cached text spans.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main defect remains: Current main still calls findCodeOwnership directly from the conservative checkpoint branch; the proposed ownership reuse is absent. The linked report identifies this branch as the repeated whole-reply parsing hotspot. (src/shared/text/text-projection.ts:78, ac9e4bc784d6)
  • Stream-local cache and canonical refresh: Checkpoint ownership is retained within each projector and refreshed through canReuseMarkdownOwnership; replacement deltas recreate downstream projectors. The tool-call consumer separately extends proven code ranges while retaining canonical reparsing for mutable syntax. (src/shared/text/text-projection.ts:126, 010a449ef62e)
  • Previous finding resolved: The only change since the previously reviewed head adds table-code-retention.ts to the existing wrapper inventory, matching the parser's runtime import; the runtime tree is unchanged. (scripts/pr-lib/wrapper-components.txt:2358, 010a449ef62e)
  • Behavior and regression evidence: The PR body records a built openclaw agent exec run through a loopback Responses SSE provider, exact sanitized output after table invalidation, a native Ollama control, and differential prefix/delta sweeps. It also records the work-budget regression failing on the base and passing on the branch. (src/shared/text/assistant-visible-text.streaming-work.test.ts:88, 010a449ef62e)
  • Original ownership contract preserved: Merged fix: keep long replies streaming after tool traces and code fences #172832 deliberately retained unresolved images, reference definitions, and titles because later syntax can revoke code protection; this PR retains that contract and removes duplicate table policy from the checkpoint. (packages/markdown-core/src/reasoning-tag-parser.ts:491, a8a67b01e4ff)
  • Exact-head checks: The refreshed check census reports no failed checks, with CI execution still active and openclaw/ci-gate pending. Dependency and security-sensitive review statuses pass; cancelled entries are ancillary dispatch, response, and context jobs. (010a449ef62e)

Likely related people:

  • Peter Steinberger: Raw commit a8a67b0 adds src/shared/text/text-projection.ts:70 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a8a67b01e4ff; files: src/shared/text/text-projection.ts)

PR surface

Source +557, Tests +466, Other +763. Total +1786 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 579 22 +557
Tests 4 514 48 +466
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 763 0 +763
Total 13 1856 70 +1786

Review metrics

Metric Value Why it matters
Runtime production versus tests Production +579/-22; tests +514/-48 Production growth implements stream-local reuse and syntax invalidation within the existing projection and Markdown owners; tests cover bounded parsing work and distinct ownership transitions.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repeated Markdown parsing delays final-answer streaming for specific tool-call and citation shapes; the focused repair has clear user value without an established urgent release regression.
  • 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 (13 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-22T09:15:29.557Z sha 6ed99daa285e45a32a7767ac5baa0bcee7bf5fad :: needs changes before merge. :: [P2] Invalidate cached ownership for list-owned reference destinations
  • reviewed 2026-10-22T09:53:49.257Z sha d962168e84bca497f265b349ef9994062693bb38 :: needs changes before merge. :: [P2] Invalidate ownership when an ordinary multiline link title closes
  • reviewed 2026-10-22T14:04:16.922Z sha c3a24b7f95713d93676800ef4fefee8d4a3bad37 :: needs changes before merge. :: [P2] Invalidate ownership when a parenthesized inline-link title closes
  • reviewed 2026-10-22T15:35:33.309Z sha 4191f0a41f93fe6e9242bc2c18d3fda7269de523 :: needs changes before merge. :: [P2] Invalidate quoted titles with supported destination syntax
  • reviewed 2026-10-23T00:04:12.727Z sha abed4918f7e1b94e93577baba1433f93769f9857 :: needs changes before merge. :: [P2] Remove HTML invalidation from the Markdown ownership cache
  • reviewed 2026-10-23T00:51:42.724Z sha 2d394cf :: needs changes before merge. :: [P2] Preserve earlier ownership retention before the table checkpoint
  • reviewed 2026-10-23T03:12:02.026Z sha 8f3c32b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-23T04:31:20.952Z sha f447065 :: needs changes before merge. :: [P2] [P2] Include the table-retention helper in the wrapper inventory

Reviewed October 23, 2026, 12:49 AM ET / 04:49 UTC (Revision 14).

@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 17, 2026
@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling labels Oct 17, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Oct 22, 2026
@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants