Skip to content

perf(channels): defer partial-reply sanitization to consumption - #118349

Merged
steipete merged 1 commit into
mainfrom
perf/partial-sanitize-118027
Aug 3, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/partial-sanitize-118027

Conversation

@steipete

@steipete steipete commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Final piece of the #118027 hot-path series (deferred from #118192, see its "Not changed" note). Every streaming partial ran stripHeartbeatToken + silent-token checks + sanitizeUserFacingText over the full cumulative text — even for partials the channel draft throttle never delivers. Draft-streaming channels paid O(turn length) sanitize CPU per token on the gateway main loop.

Why This Change Was Made

Sanitize cost now follows consumption instead of emission:

  • createAgentTurnPresentation splits eager classifyStreamingPartial (silent-expected, heartbeat strip decision, silent-prefix checks — cheap, keeps today's skip semantics at the same point) from deferred sanitizeStreamingText (the expensive sanitizeUserFacingText + empty→skip rule).
  • The embedded candidate emits a PartialReplyPayload whose text is an enumerable memoized getter: first read sanitizes and caches. Direct-delivery channels (MS Teams, Feishu, QQ, QA) read every partial and keep byte-identical behavior and cost; the Telegram draft stream stores the lazy payload and materializes only at flush (updateLazy), paying O(flushes). All four direct consumers already guard falsy text, so the one new observable state (text materializing to undefined on rare sanitize-to-empty) is a no-op everywhere.
  • Typing signals receive the classified raw text — they are activity-only and never render content. CLI, block-reply, tool-result, and final delivery paths stay eager and unchanged.
  • A flush whose newest value sanitizes to empty consumes its slot without sending or mutating the last delivered draft (invariant comment at the seam).

User Impact

No change to delivered channel output (randomized equivalence tests over heartbeat/silent/empty-sanitize/media sequences assert identical delivered edit sequences). Draft-streaming turns stop paying per-token sanitize CPU, removing the last known O(n²)-per-turn pattern from the streaming fanout.

Evidence

  • 154 focused tests across 6 files: randomized old-vs-new equivalence, direct-vs-throttled sanitizer-count (O(partials) vs O(flushes)), JSON-serialization materialization, empty-sanitize flush no-op, media-only, retry, and Telegram draft-rotation coverage.
  • Full local changed gate (format, 4 typecheck lanes, lint, boundaries, API baseline, dead exports, cycles, guards) passed; remote backend unavailable on this host per AGENTS.md fallback.
  • Autoreview (Codex gpt-5.6-sol, high): clean, "patch is correct (0.96)".
  • Production delta +89 (the explicit lazy-ownership contract + Telegram flush seam), tests +434.

Part of the #118027 follow-up track. Siblings landed: #118192, #118207, #118193, #118334.

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: L maintainer Maintainer-authored PR labels Aug 3, 2026
@steipete
steipete marked this pull request as ready for review August 3, 2026 01:09
@steipete steipete self-assigned this Aug 3, 2026
@clawsweeper clawsweeper Bot added 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. mantis: telegram-visible-proof Mantis should capture Telegram visible proof. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Aug 3, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 2, 2026, 9:14 PM ET / August 3, 2026, 01:14 UTC.

ClawSweeper review

What this changes

The PR defers sanitizing cumulative streaming partial replies until a throttled Telegram draft stream consumes the newest pending update, while direct-delivery consumers still materialize each partial immediately.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 4 items remain

Keep this PR open for maintainer review. The source change preserves the existing eager path for direct consumers while moving Telegram draft-stream sanitization to flush-time, and the focused tests cover the lazy ownership seam; however, the repository’s Telegram review policy calls for real Telegram streaming proof, which is not present in the PR body or supplied review context.

Priority: P3
Reviewed head: bde183586a5f7e7c7d71342ee5987090e2d383b4
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation and targeted regressions are solidly structured, but merge confidence is capped by missing real Telegram behavior proof.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR body reports focused tests and CI-style checks, but the supplied evidence contains no after-fix live Telegram run, runtime log, recording, or terminal artifact demonstrating the changed streaming behavior; redact private data in any proof posted. 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 PR body reports focused tests and CI-style checks, but the supplied evidence contains no after-fix live Telegram run, runtime log, recording, or terminal artifact demonstrating the changed streaming behavior; redact private data in any proof posted. 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 6 items Current-main comparison: The PR base and current main have no changes in the four core and Telegram owner files relevant to this patch, so the review compared the proposed lazy flow against the current eager behavior rather than an outdated implementation.
Lazy owner boundary: The branch keeps heartbeat and silent-token classification eager, then memoizes sanitization behind the partial payload’s enumerable text getter so a consumer decides when sanitization occurs.
Telegram consumption seam: The Telegram draft controller stores the lazy update and resolves it only from the draft stream’s flush path; the proposed branch explicitly leaves rotation handling eager where a new draft lane must be prepared.
Findings None None.
Security None None.

How this fits together

Agent streaming emits cumulative assistant partials through the auto-reply presentation layer to channel callbacks. Telegram’s draft controller coalesces those updates before editing its visible preview message, while direct channels consume a partial as soon as they receive it.

flowchart LR
  A[Provider streaming partials] --> B[Reply presentation]
  B --> C[Classify heartbeat and silent tokens]
  C --> D[Lazy sanitized partial payload]
  D --> E[Direct channel consumer]
  D --> F[Telegram draft throttle]
  E --> G[Immediate channel update]
  F --> H[Flush newest preview edit]
Loading

Decision needed

Question Recommendation
Should this Telegram streaming hot-path change receive the repository-required live Telegram proof before merge, or should maintainers explicitly accept the focused synthetic coverage as an exception? Request live Telegram proof: Ask for a redacted bot-to-bot or Telegram Desktop run showing a throttled multi-part reply, preview update, and final message behavior after this change.

Why: The patch is source-consistent and test-covered, but the applicable Telegram policy explicitly prefers real streaming proof and the available PR evidence contains only test and CI claims.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR body reports focused tests and CI-style checks, but the supplied evidence contains no after-fix live Telegram run, runtime log, recording, or terminal artifact demonstrating the changed streaming behavior; redact private data in any proof posted. 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.
  • Resolve merge risk (P1) - This changes where Telegram streaming partials become user-facing text; unit and mock-stream tests exercise the seam, but no supplied real Telegram run demonstrates that throttling, preview edits, and finalization still produce the intended visible sequence.
  • Complete next step (P2) - No mechanical repair is indicated; a maintainer must decide whether to require the policy-preferred live Telegram proof before merge.
Agent review details

Security

None.

PR surface

Source +104, Tests +419. Total +523 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 7 163 59 +104
Tests 5 420 1 +419
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 583 60 +523

Review metrics

None.

Mantis proof suggestion

A Telegram Desktop proof would materially validate that deferred materialization preserves visible preview edits and finalization; it complements, rather than replaces, the focused tests. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis telegram desktop proof: verify a throttled multi-part streamed reply keeps the correct latest preview and finalizes as one visible message.

Merge-risk options

Maintainer options:

  1. Prove the Telegram delivery path (recommended)
    Add a redacted live Telegram streaming run that shows the preview and finalized message remain correct when partials are throttled.
  2. Accept the test-only proof
    Maintainers can explicitly accept the focused mock and unit coverage if a live Telegram run is not proportionate to this no-output-change performance optimization.

Technical review

Best possible solution:

Retain the single lazy ownership path, add redacted after-fix Telegram streaming evidence for a throttled multi-part reply and finalization, then merge only after the remaining required checks complete.

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

Yes, from source: current main sanitizes every streaming partial before invoking the channel callback, while the proposed branch defers that work behind a memoized callback payload for the throttled Telegram consumer. No local execution was performed because this review is read-only.

Is this the best way to solve the issue?

Yes, conditionally: splitting cheap classification from deferred sanitization keeps direct consumers eager and places coalescing optimization at the Telegram draft-stream owner boundary. A live Telegram proof is the remaining evidence needed to confirm this is the safest implementation.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P3: This is a bounded performance improvement for high-rate streaming rather than a demonstrated current user-facing regression.
  • add merge-risk: 🚨 message-delivery: The patch changes when Telegram draft-stream partials are materialized and could alter visible preview update behavior if the consumer boundary is incorrect.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports focused tests and CI-style checks, but the supplied evidence contains no after-fix live Telegram run, runtime log, recording, or terminal artifact demonstrating the changed streaming behavior; redact private data in any proof posted. 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.
  • add mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The change affects Telegram’s user-visible streaming preview path and can be demonstrated in a short Telegram Desktop run.

Label justifications:

  • P3: This is a bounded performance improvement for high-rate streaming rather than a demonstrated current user-facing regression.
  • merge-risk: 🚨 message-delivery: The patch changes when Telegram draft-stream partials are materialized and could alter visible preview update behavior if the consumer boundary is incorrect.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; 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 PR body reports focused tests and CI-style checks, but the supplied evidence contains no after-fix live Telegram run, runtime log, recording, or terminal artifact demonstrating the changed streaming behavior; redact private data in any proof posted. 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.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The change affects Telegram’s user-visible streaming preview path and can be demonstrated in a short Telegram Desktop run.

Evidence

What I checked:

Likely related people:

  • steipete: Current presentation and Telegram draft-stream code attributes to Peter Steinberger, who also authored the focused performance follow-up and the proposed branch. (role: recent area contributor and proposed owner; confidence: high; commits: 15560382a2ad, bde183586a5f; files: src/auto-reply/reply/agent-runner-presentation.ts, extensions/telegram/src/bot-message-dispatch-draft.ts, extensions/telegram/src/draft-stream.ts)

Rank-up moves

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

  • Post a redacted live Telegram streaming transcript or recording that shows throttled preview updates and finalization after the change.
  • Let the in-progress required checks complete on the reviewed head.

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.

@steipete

steipete commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up moves handled:

  • The required exact-head CI is complete and green on bde183586a5f7e7c7d71342ee5987090e2d383b4.
  • Live Telegram proof is skipped for this landing because Crabbox/Blacksmith is unavailable on this host. Under the repository's trusted-source fallback policy, the maintainer explicitly accepts the focused synthetic coverage as proportionate for this behavior-neutral hot-path optimization: 154 focused tests across 6 files cover old-vs-new delivered-sequence equivalence, sanitizer counts, JSON materialization, sanitize-to-empty flushes, media/retry behavior, and Telegram draft rotation. The full local changed gate also passed (format, all 4 typecheck lanes, lint, boundaries, API baseline, dead exports, cycles, and guards). The required post-rebase focused rerun passed 121 tests across the 4 requested shards, and fresh autoreview was clean at 0.98.

There are no unresolved implementation findings; this is an explicit maintainer acceptance of test-only proof for the unavailable live-proof lane.

@steipete
steipete merged commit c965909 into main Aug 3, 2026
189 of 199 checks passed
@steipete
steipete deleted the perf/partial-sanitize-118027 branch August 3, 2026 01:19
@steipete

steipete commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
steipete added a commit that referenced this pull request Oct 14, 2026
…delta after a preview is visible (#171417)

* fix(reply): stop re-sanitizing streamed Telegram replies on every delta

#118349 made partial reply text a lazy getter so Telegram sanitizes it
only when its draft stream flushes a preview. The visible-partial checks
from #117603 read that text after every visible partial, which runs
sanitizeUserFacingText over the whole cumulative reply on every model
delta once a preview is visible (progress mode after any tool call, and
partial mode).

The checks only set a flag that never resets and that only failure
handling reads, so stop reading once it is set. Both checks need this:
the getter is memoized per payload, so either one reading it runs the
sanitizer.

On the Telegram dispatch path a 24k-character reply drops from about
1.0 s to 0.1 s of Gateway CPU, and from about 48 s to 1 s when a line
starts with a Markdown link; Telegram sends are unchanged.

* test(reply): bound lazy preview sanitization regressions

Extend the Telegram-style visibility regressions to hundreds of deltas,
including initially hidden or sanitizer-empty content and entity/markup
boundaries. Preserve canonical whole-snapshot sanitization at consumption
and the existing terminal failure recovery contract. Remove a duplicate
comment without expanding production code.

Original fix by @boeingchoco for #171416.
Co-authored-by: boeingchoco <[email protected]>

* test(reply): prepare session facts for recovery authorization

CI exposed a recovery fixture calling the synchronous authorization
consumer without preparing its session facts. Use the existing async
owner and release the retained authorization after the test. Preserve
the live authority assertion and every recovery assertion.

---------

Co-authored-by: boeingchoco <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 15, 2026
…delta after a preview is visible (openclaw#171417)

* fix(reply): stop re-sanitizing streamed Telegram replies on every delta

openclaw#118349 made partial reply text a lazy getter so Telegram sanitizes it
only when its draft stream flushes a preview. The visible-partial checks
from openclaw#117603 read that text after every visible partial, which runs
sanitizeUserFacingText over the whole cumulative reply on every model
delta once a preview is visible (progress mode after any tool call, and
partial mode).

The checks only set a flag that never resets and that only failure
handling reads, so stop reading once it is set. Both checks need this:
the getter is memoized per payload, so either one reading it runs the
sanitizer.

On the Telegram dispatch path a 24k-character reply drops from about
1.0 s to 0.1 s of Gateway CPU, and from about 48 s to 1 s when a line
starts with a Markdown link; Telegram sends are unchanged.

* test(reply): bound lazy preview sanitization regressions

Extend the Telegram-style visibility regressions to hundreds of deltas,
including initially hidden or sanitizer-empty content and entity/markup
boundaries. Preserve canonical whole-snapshot sanitization at consumption
and the existing terminal failure recovery contract. Remove a duplicate
comment without expanding production code.

Original fix by @boeingchoco for openclaw#171416.
Co-authored-by: boeingchoco <[email protected]>

* test(reply): prepare session facts for recovery authorization

CI exposed a recovery fixture calling the synchronous authorization
consumer without preparing its session facts. Use the existing async
owner and release the retained authorization after the test. Preserve
the live authority assertion and every recovery assertion.

---------

Co-authored-by: boeingchoco <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram maintainer Maintainer-authored PR mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L 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.

1 participant