Skip to content

fix: preserve streamed reply boundaries without replaying code - #143722

Merged
obviyus merged 3 commits into
mainfrom
codex/fix-streamed-block-boundaries-143641
Sep 10, 2026
Merged

obviyus merged 3 commits into
mainfrom
codex/fix-streamed-block-boundaries-143641

Conversation

@obviyus

@obviyus obviyus commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #143641. Related: #143702. Thanks @rgregg for the report.

What Problem This Solves

Small streamed updates could split a bullet line too early or display code outside its fence. The final answer could then repeat code already delivered in continuation blocks.

Why This Change Was Made

The chunker waits for a natural boundary before splitting at whitespace and preserves open-fence state across forced breaks. Private reply metadata carries each block's original source through coalescing; final accounting credits it after successful delivery. Rejected or rewritten text retains final-answer recovery.

User Impact

Prose keeps complete lines when they fit. Code continuations stay fenced within message limits, and delivered code is not repeated in the final answer.

Consumers: streamed chunks, coalesced blocks, and final-reply accounting now preserve source coverage across continuation wrappers.

Evidence

Real guild messages reproduced premature prose splitting and an unclosed fence. Corrected messages reconstructed the full code exactly once for six update sizes. All 263 focused tests and 24 final-tag streaming tests passed. Draft edits, handoff, deletion, cancellation, and replacement checks passed. Existing platform normalization of line endings and trailing spaces remains; general byte preservation is not claimed. A misleading cancellation timeout notice also reproduced before the change.

@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 agents Agent runtime and tooling size: M maintainer Maintainer-authored PR 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: 🐚 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. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 10, 2026, 1:54 AM ET / 05:54 UTC (Revision 3).

ClawSweeper review

What this changes

The PR preserves natural streamed reply boundaries, balances continued code fences, and tracks successfully delivered source text so the final answer does not replay that code.

Merge readiness

✅ Ready for maintainer review

This remains a useful fix for defects still present on current main. The updated acceptance evidence resolves the previous review’s outstanding request, and no blocking introduced defect was found.

Priority: P2
Reviewed head: b324151e26ceadf66d2df91cc25cf7530ed2a544

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent repair with useful behavioral coverage and concrete real-channel acceptance; the previous evidence follow-up is resolved.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured Discord observations exercise chunking through real channel delivery and final accounting, reporting balanced code delivered exactly once across six update sizes plus completed boundary and lifecycle acceptance; GitHub confirms the final revision changes only typing and a test expectation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Discord observations exercise chunking through real channel delivery and final accounting, reporting balanced code delivered exactly once across six update sizes plus completed boundary and lifecycle acceptance; GitHub confirms the final revision changes only typing and a test expectation.
Evidence reviewed 10 items Current main still contains both reported mechanisms: The inspected main revision still defers whitespace fallback only for newline preference and treats an unfinished fence's exclusive endpoint as a safe forced break.
Latest release also retains the defective guards: The supplied latest release, v2026.9.3, retains the newline-only deferral and exclusive fence-end lookup. No released resolution was established.
Existing Markdown owner supplies open-fence state: The chunker uses the repository's Markdown scanner, whose returned state distinguishes an unfinished fence from a genuine closing marker. This is an OpenClaw-owned Markdown contract; the changed behavior does not depend on the Codex harness.
Findings None None.
Security None None.

How this fits together

OpenClaw turns streamed assistant text into channel-sized reply blocks. The delivery pipeline combines those blocks and records successful sends to decide which final text and attachments still need delivery.

flowchart LR
  A[Assistant text updates] --> B[Markdown boundary chunker]
  B --> C[Balanced blocks and source text]
  C --> D[Reply normalization and coalescing]
  D --> E[Channel delivery]
  E --> F[Successful source accounting]
  F --> G[Suppress delivered final text]
  F --> H[Preserve unsent content]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +91, Tests +268. Total +359 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 8 140 49 +91
Tests 4 276 8 +268
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 416 57 +359

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #143641
Summary: This PR is an implementation candidate for the reported chunk-boundary defects and also addresses final replay exposed during acceptance.

Members:

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

Technical review

Best possible solution:

Keep Markdown boundary handling in the shared chunker and suppress final text only when successful delivery accounts for its complete source.

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

Yes: current-main source exposes both reported triggers when small updates cross the minimum length or an unfinished fence reaches the maximum length. This review inspected that path without executing it.

Is this the best way to solve the issue?

Yes: the patch uses the existing Markdown scanner and delivery-accounting owners, preserving fallback delivery when complete successful coverage cannot be established.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured Discord observations exercise chunking through real channel delivery and final accounting, reporting balanced code delivered exactly once across six update sizes plus completed boundary and lifecycle acceptance; GitHub confirms the final revision changes only typing and a test expectation.

Label justifications:

  • P2: This repairs malformed and repeated streamed replies with a bounded impact on block-streaming delivery.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 captured Discord observations exercise chunking through real channel delivery and final accounting, reporting balanced code delivered exactly once across six update sizes plus completed boundary and lifecycle acceptance; GitHub confirms the final revision changes only typing and a test expectation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Discord observations exercise chunking through real channel delivery and final accounting, reporting balanced code delivered exactly once across six update sizes plus completed boundary and lifecycle acceptance; GitHub confirms the final revision changes only typing and a test expectation.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The shared chunker changes visible Telegram block-reply boundaries, code formatting, and final replay behavior.

Evidence

What I checked:

  • Current main still contains both reported mechanisms: The inspected main revision still defers whitespace fallback only for newline preference and treats an unfinished fence's exclusive endpoint as a safe forced break. (src/agents/embedded-agent-block-chunker.ts:489, fe6556b643e3)
  • Latest release also retains the defective guards: The supplied latest release, v2026.9.3, retains the newline-only deferral and exclusive fence-end lookup. No released resolution was established. (src/agents/embedded-agent-block-chunker.ts, 1391f7cd2d40)
  • Existing Markdown owner supplies open-fence state: The chunker uses the repository's Markdown scanner, whose returned state distinguishes an unfinished fence from a genuine closing marker. This is an OpenClaw-owned Markdown contract; the changed behavior does not depend on the Codex harness. (packages/markdown-core/src/fences.ts:27, b324151e26ce)
  • Source credit follows successful delivery: The pipeline records original block source only after the channel callback succeeds. Final suppression compares assembled coverage, while rejected sends retain the final fallback. Coalescing preserves source separately from transport joiners. (src/auto-reply/reply/block-reply-pipeline.ts:197, b324151e26ce)
  • Rewritten and superseded text loses source credit: Rendering retains source metadata only when visible text is unchanged; delivery normalization clears it on rewriting, and deferred supersession clears it alongside withdrawn text. The metadata lives in an existing WeakMap, without adding persistence or channel payload fields. (src/auto-reply/reply/reply-delivery.ts:163, b324151e26ce)
  • Updated acceptance resolves the previous request: The captured body at sourceRevision b1c5be2b60bf95326758c1341e0b4349f7ffec90aa447e86f6fd45db8c537cde reports completed independent Discord acceptance: six update sizes, exactly-once code reconstruction, closed-at-limit and punctuation controls, draft handoff/deletion, and cancellation with replacement delivery. This supplies the outcome requested in the previous review. The body explicitly excludes an already-admitted stale-callback race from its cancellation claim; no raw media files were available in the supplied scratch directory. (b324151e26ce)

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)

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 (2 earlier review cycles)
  • reviewed 2026-09-10T05:24:30.031Z sha 8c9b5e3 :: blocked before merge. :: none
  • reviewed 2026-09-10T05:46:43.460Z sha b324151 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 10, 2026
@obviyus
obviyus merged commit 14d272d into main Sep 10, 2026
185 checks passed
@obviyus
obviyus deleted the codex/fix-streamed-block-boundaries-143641 branch September 10, 2026 06:00
@obviyus

obviyus commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @rgregg for the report.

Proof: Real Discord guild requests through an isolated Gateway pass prose and fenced-code update sizes 1, 3, 5, 10, 20 and 64. The principal code source reconstructs exactly once after removing only synthetic fence wrappers. Independent acceptance also covers closed-fence/punctuation boundaries, draft edits and finalization, and matched cancellation/replacement behavior. Focused validation passed 263 tests plus 24 final-tag tests.

Before After
The first prose block stopped inside a bullet line. Nearby natural boundaries keep complete lines together.
A forced code block reached the buffer end without a closing fence. The scanner's open-fence state preserves balanced continuations.
Wrapped code could be followed by a repeated full final answer. Only successfully delivered source counts toward final suppression; rejected delivery retains its fallback.

The final revision also fixes the payload's declaration type and keeps the exact literal final-tag test aligned with the intended boundary behavior. Its runtime matches the live-tested revision.

Existing Discord whitespace losses and the misleading cancellation timeout notice were reproduced on the pinned baseline and remain separate limitations. The late-write cancellation probe used an already-closed connection; it does not establish an open-transport internal race result.

Exact-head CI · Related contributor work: #143702, left unchanged.

Exact-head CI and the required independent landing review passed.

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]>
karmafeast pushed a commit to karmaterminal/openclaw that referenced this pull request Sep 26, 2026
Put back upstream b1c68b9 content that the continuation line had
silently reverted in shared files. Every row has a keep/restore
disposition recorded in the round journal. Feature hunks are preserved.

Production:
- announce deps: use callSubagentLifecycleGateway for the wake and
  cleanup deps (openclaw#146369 inherited Gateway binding).
- reply-delivery: clear blockSourceText on superseded deferred replies
  (openclaw#143722).
- stream-rendering: record a block reply as delivered only when it has
  text (openclaw#135751).
- gateway runtime handles: carry hotReloadStatus through the managed
  reload.
- sweep-kill and sweeper: honor retired cancellations
  (reconcileRetiredSubagentCancellation), and pass the run's Gateway
  context resolver into sweep session deletes.
- registry read: per-child snapshot reads (openclaw#154727), so the Gateway
  event loop is not blocked.
- session delivery queue: read the post-enqueue status inside the SQLite
  worker instead of on the main thread, restoring the openclaw#147887 invariant.

Tests restored to upstream's coverage:
- task-registry kernel test: back to upstream's kernel functions.
- double-announce: real outbound adapter retry outcomes (openclaw#131419).
- side-question: listener-failure hooks case (openclaw#144828).
- session-delivery storage: main-thread-SQL idle assertion (openclaw#157458).
- media-only: the re-resolved auth selection assertion.
- resume persistence: activation uses the real recovery-runtime shape.

The resume "steered requester turn" test was adapted for upstream's
async task lookup (openclaw#157634). Its stub now settles like the real waker,
and the test waits for settle before an exact count, with a
no-pending-wake assertion added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Fq5EX9ESA3CG9cuZxVoKAK
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

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

1 participant