Skip to content

fix(agents): land forced block-chunk breaks on real boundaries - #143702

Closed
ruel225 wants to merge 1 commit into
openclaw:mainfrom
ruel225:fix/issue-143641-block-chunker-forced-break
Closed

ruel225 wants to merge 1 commit into
openclaw:mainfrom
ruel225:fix/issue-143641-block-chunker-forced-break

Conversation

@ruel225

@ruel225 ruel225 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #143641.

What Problem This Solves

EmbeddedBlockChunker corrupted streamed block replies in two independent ways, both reproduced on main (15a781e3df2's parent 92888bf9fdc):

  1. Mid-sentence forced cuts. The drain that crosses minChars holds only a few characters past it, so paragraph/newline/sentence boundary searches at index ≥ minChars cannot succeed yet. The defer guard that waits for real boundaries was scoped to breakPreference: "newline" only; every other preference fell through to the whitespace scan and cut at whatever whitespace was already buffered. The cut was delta-dependent, which made the bug look intermittent.
  2. Unbalanced fences at the buffer boundary. A still-streaming fence has no closing marker, so its span ends at the buffer end. The forced-break path probed the cut directly, and the exclusive fence lookup (span.start < index < span.end) reported a cut at span.end as outside the fence. isSafeFenceBreak returned true, the close/reopen path was skipped, and the chunk was emitted with an odd number of ``` markers.

Solution

#pickBreakIndex, two changes:

  1. The defer guard now applies to every preference. It is only reachable once paragraph, newline, and sentence searches have all failed; more buffered text can only add candidates, and the whitespace fallback plus maxChars clamp still run once the buffer reaches maxChars. Force drains are unaffected (they reach this helper only when remainingLength > maxChars).
  2. When the forced cut lands at the end of the source, the fence lookup probes the last included character instead of the exclusive boundary. A span whose final line is a genuine closing marker (checked with the existing findFenceCloseLineStart) is still recognized as balanced, so a fence that ends exactly at the cut is emitted as-is without a synthetic close/reopen pair.

Why not the issue's suggested diff verbatim

The issue proposes probing maxChars - 1 whenever maxChars === buffer.length. That variant also treats a balanced fence whose closing marker is the buffer's final bytes as still-streaming and wraps it in a synthetic close/reopen pair, so the balanced fence is emitted twice-closed and the content after it is pulled into the reopened code block. The added test cuts cleanly after a balanced fence that ends exactly at the source boundary is red under that variant and green under this patch.

Evidence

All runs against this head (15a781e3df2), pre-fix runs against the same source before the two #pickBreakIndex hunks:

  • Pre-fix red (defect 1): waits for maxChars before a forced paragraph break so the cut lands on a line boundary (delta 1/3/10) — failed with the first chunk ending mid-line (bullets.charAt(firstChunk.length) was " ", not "\n").
  • Pre-fix red (defect 2): closes and reopens a still-streaming fence cut exactly at the buffer boundary (delta 1/50) — failed with chunks carrying an odd ``` count.
  • Boundary guard red under the issue's variant: cuts cleanly after a balanced fence that ends exactly at the source boundary — passes on main (43-test baseline), stays green with this patch, fails with the maxChars - 1 probe alone.
  • Post-fix: embedded-agent-block-chunker.test.ts 49/49 (43 pre-existing unchanged), packages/markdown-core 27 files / 382 tests, chunking-adjacent embedded-agent-subscribe.code-span-awareness + block-reply-rejections suites.
  • tsgo -p tsconfig.core.json --noEmit exit 0; oxlint --type-aware and oxfmt --check clean on both changed files.

Impact

Streamed embedded-agent replies (block reply chunking is user-configurable per channel via blockReplyChunking, default breakPreference: "paragraph") no longer split mid-sentence and no longer publish broken markdown when a forced chunk boundary lands on a streaming code fence. Non-streaming and force-flush output is unchanged apart from the two repaired cut positions.

EmbeddedBlockChunker forced breaks had two defects. A drain crossing
minChars fell through to the whitespace scan for every preference except
newline, cutting mid-sentence on whatever whitespace happened to be
buffered; the newline-only defer guard is now applied for every
preference, since more buffered text can only add candidate boundaries.

A forced cut landing exactly at the end of the source probed an open
fence's span.end, which the exclusive fence lookup treats as outside the
fence, so the chunk was emitted with an unbalanced marker. The cut now
probes the last included character, while a span whose final line is a
genuine closing marker is still recognized as balanced and emitted
without a synthetic close/reopen pair.

Co-Authored-By: Claude <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 10, 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 the agents Agent runtime and tooling label Sep 10, 2026
@ruel225
ruel225 marked this pull request as ready for review September 10, 2026 04:48
@openclaw-barnacle openclaw-barnacle Bot added size: S 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 Sep 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 10, 2026, 12:58 AM ET / 04:58 UTC.

ClawSweeper review

What this changes

The PR makes streamed reply chunks wait for suitable text boundaries and correctly close and reopen unfinished code fences at forced cuts.

Merge readiness

⛔ Blocked before merge - 2 items remain

This PR remains useful: current main and v2026.9.3 retain both reported defects. No introduced correctness defect was found, but the supplied validation does not satisfy the real-behavior proof gate.

Priority: P2
Reviewed head: 15a781e3df2930f8b7e04224c76543962a4cadae

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused repair with useful regression coverage remains limited by the missing production-flow demonstration.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The supplied tests exercise the chunker directly, but no after-fix real setup demonstrates streamed text passing through block reply delivery with intact content and balanced formatting. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The supplied tests exercise the chunker directly, but no after-fix real setup demonstrates streamed text passing through block reply delivery with intact content and balanced formatting. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 8 items Verified introduced scope: The complete pinned merge-base-to-head patch changes only the block chunker and its tests. Host-verified test-merge evidence preserves the unrelated base-branch changes.
Current main still needs the repair: Current main limits boundary deferral to newline preference and probes the exclusive fence endpoint directly, retaining both reported mechanisms.
Latest release retains the same behavior: The v2026.9.3 source contains the same newline-only guard and direct endpoint probe; this is not already-shipped cleanup.
Findings None None.
Security None None.

How this fits together

OpenClaw’s block chunker receives streamed assistant text and divides it into bounded Markdown messages. Its output flows through reply delivery to channel users.

flowchart TD
  A[Assistant text stream] --> B[Pending reply buffer]
  C[Chunk size and break preferences] --> D[Choose text boundary]
  B --> D
  D --> E[Preserve code fences]
  E --> F[Block reply delivery]
  F --> G[Channel messages]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The supplied tests exercise the chunker directly, but no after-fix real setup demonstrates streamed text passing through block reply delivery with intact content and balanced formatting. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step (P2) - Provide redacted after-fix real-behavior proof of streamed block replies before merge.
Agent review details

Security

None.

PR surface

Source +11, Tests +86. Total +97 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 39 28 +11
Tests 1 86 0 +86
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 125 28 +97

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #143641
Summary: This PR is the explicit implementation candidate for the linked open chunk-boundary bug.

Members:

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

Technical review

Best possible solution:

Keep boundary selection in the shared chunker, preserving message budgets, source content, and balanced fences through actual streamed delivery.

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

Yes, source inspection supports the reported small-delta reproduction with minChars 800 and maxChars 1200 for prose and unfinished fences; this review did not execute it.

Is this the best way to solve the issue?

Yes, the patch repairs the existing owner and improves on the suggested endpoint probe by preserving already-balanced fences.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This repairs reproducible formatting defects in optional streamed block replies with a bounded implementation.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The supplied tests exercise the chunker directly, but no after-fix real setup demonstrates streamed text passing through block reply delivery with intact content and balanced formatting. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. With Telegram block replies enabled, the changed chunk boundaries and code-fence formatting are visible in delivered messages.

Evidence

What I checked:

  • Verified introduced scope: The complete pinned merge-base-to-head patch changes only the block chunker and its tests. Host-verified test-merge evidence preserves the unrelated base-branch changes. (src/agents/embedded-agent-block-chunker.ts:489, 15a781e3df29)
  • Current main still needs the repair: Current main limits boundary deferral to newline preference and probes the exclusive fence endpoint directly, retaining both reported mechanisms. (src/agents/embedded-agent-block-chunker.ts:489, f4d1a1fdf84a)
  • Latest release retains the same behavior: The v2026.9.3 source contains the same newline-only guard and direct endpoint probe; this is not already-shipped cleanup. (src/agents/embedded-agent-block-chunker.ts:489, 1391f7cd2d40)
  • Owner-level repair and regression coverage: The implementation preserves UTF-16 slicing and fence-wrapper budgets, reuses closing-marker recognition, and adds streaming-delta cases plus a balanced-fence boundary case. The complete production file and test file were inspected; tests were not executed during this read-only review. (src/agents/embedded-agent-block-chunker.ts:515, 15a781e3df29)
  • Documented behavior and production entrypoint: The streaming documentation defines preferred text boundaries and synthetic fence closing/reopening. The message-update handler drains this chunker into block reply delivery at lines 596–597. The changed algorithm depends on OpenClaw’s own Markdown scanner, not a Codex implementation contract. Public docs: docs/concepts/streaming.md. (docs/concepts/streaming.md:109, 15a781e3df29)
  • Proof assessment: The complete supplied PR body reports before/after unit results, adjacent suites, typechecking, lint, and formatting. A live REST read confirmed the same head and body. Neither the body nor non-ClawSweeper comments supplies an after-fix channel delivery trace, recording, or runtime artifact. (15a781e3df29)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • mushuiyu886: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Add after-fix evidence from a real streamed block reply showing corrected prose boundaries and code-fence rendering; screenshots or recordings are preferred when visible, and delivery logs or terminal output also count.
  • Redact private details before posting and update the PR body to trigger review; if it does not rerun, ask a maintainer to comment @clawsweeper re-review.

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.

obviyus added a commit that referenced this pull request Sep 10, 2026
Closes #143641.

Related: #143702.

## What Problem This Solves

Fixes an issue where small streamed updates split a bullet line before its next natural boundary arrived or displayed code outside its fence. It also prevents the full final answer from repeating code already delivered with continuation fences.

## Why This Change Was Made

The chunker waits for a natural boundary before falling back to whitespace at the limit. It retains the Markdown scanner's open-fence state for sentence and forced breaks, so an unfinished buffer endpoint gets balanced continuation wrappers while a completed closing fence stays intact.

The chunker also carries the source represented by each block through private reply metadata. Coalescing retains that source, and final-reply accounting credits it only after successful delivery. Rejected or rewritten text keeps the existing fallback; this does not discard an unsent final answer merely because streaming started.

## User Impact

Streamed prose stays in complete lines when a nearby boundary fits. Forced code continuations keep their fences and message limits, and successfully streamed code does not repeat in a final reply.

## Evidence

The pinned baseline reproduced both defects through real Discord guild messages: the first prose message stopped after `Item 14:`, and the first code message contained an opening fence without a closer. Focused regressions also failed for those reasons.

Independent acceptance caught a full-final replay in the first candidate. The corrected candidate delivered exactly three balanced code messages; removing only synthetic wrappers reconstructed the complete source once. The failed candidate and all raw observations were preserved.

The correction passed 263 focused tests across the chunker, subscription, final-payload handling, rejection, supersession, coalescing, media and audio paths. Formatting, syntax checks and the native commit hook passed. Type-aware checks and the full suite run in CI.

Real Discord prose and principal fenced-code cases pass update sizes 1, 3, 5, 10, 20 and 64. Every principal code source reconstructs exactly once after removing only synthetic wrappers. Additional whitespace probes expose existing Discord normalization of CRLF and trailing spaces, also reproduced on the pinned baseline; this repair does not claim general byte preservation for those inputs.

Independent scoped acceptance is complete. Closed-at-limit and punctuation controls pass, including a real closed-fence message sent before provider completion. Draft edits, final handoff and draft deletion pass. Public cancellation closes the old provider connection, rejects its late write and delivers the replacement once. An existing misleading timeout notice after cancellation was reproduced on the pinned baseline; this does not establish a race involving an already-admitted stale callback on an open connection.

The final revision also passes all 24 final-tag streaming tests. It fixes a declaration-only type error using the existing payload type and updates one exact expected reply boundary; runtime behavior is unchanged from the live-tested revision. Hosted CI and the exact-head landing review remain required.

Thanks @rgregg for the report.

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

ruel225 commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #143722 (merged as 14d272d), which closed #143641 with superset coverage of this branch's fix — forced breaks land on real block boundaries, and I verified its repair surface covers the cases this PR added. Closing in favor of the landed work.

@ruel225 ruel225 closed this Sep 10, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 11, 2026
…law#143722)

Closes openclaw#143641.

Related: openclaw#143702.

## What Problem This Solves

Fixes an issue where small streamed updates split a bullet line before its next natural boundary arrived or displayed code outside its fence. It also prevents the full final answer from repeating code already delivered with continuation fences.

## Why This Change Was Made

The chunker waits for a natural boundary before falling back to whitespace at the limit. It retains the Markdown scanner's open-fence state for sentence and forced breaks, so an unfinished buffer endpoint gets balanced continuation wrappers while a completed closing fence stays intact.

The chunker also carries the source represented by each block through private reply metadata. Coalescing retains that source, and final-reply accounting credits it only after successful delivery. Rejected or rewritten text keeps the existing fallback; this does not discard an unsent final answer merely because streaming started.

## User Impact

Streamed prose stays in complete lines when a nearby boundary fits. Forced code continuations keep their fences and message limits, and successfully streamed code does not repeat in a final reply.

## Evidence

The pinned baseline reproduced both defects through real Discord guild messages: the first prose message stopped after `Item 14:`, and the first code message contained an opening fence without a closer. Focused regressions also failed for those reasons.

Independent acceptance caught a full-final replay in the first candidate. The corrected candidate delivered exactly three balanced code messages; removing only synthetic wrappers reconstructed the complete source once. The failed candidate and all raw observations were preserved.

The correction passed 263 focused tests across the chunker, subscription, final-payload handling, rejection, supersession, coalescing, media and audio paths. Formatting, syntax checks and the native commit hook passed. Type-aware checks and the full suite run in CI.

Real Discord prose and principal fenced-code cases pass update sizes 1, 3, 5, 10, 20 and 64. Every principal code source reconstructs exactly once after removing only synthetic wrappers. Additional whitespace probes expose existing Discord normalization of CRLF and trailing spaces, also reproduced on the pinned baseline; this repair does not claim general byte preservation for those inputs.

Independent scoped acceptance is complete. Closed-at-limit and punctuation controls pass, including a real closed-fence message sent before provider completion. Draft edits, final handoff and draft deletion pass. Public cancellation closes the old provider connection, rejects its late write and delivers the replacement once. An existing misleading timeout notice after cancellation was reproduced on the pinned baseline; this does not establish a race involving an already-admitted stale callback on an open connection.

The final revision also passes all 24 final-tag streaming tests. It fixes a declaration-only type error using the existing payload type and updates one exact expected reply boundary; runtime behavior is unchanged from the live-tested revision. Hosted CI and the exact-head landing review remain required.

Thanks @rgregg for the report.

Co-authored-by: Ayaan Zaidi <[email protected]>
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: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

EmbeddedBlockChunker: forced breaks cut mid-sentence and leave code fences unbalanced

1 participant