Skip to content

fix: reduce streaming CPU after reply and voice directives - #195145

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-reply-directives-per-stream-update-20260919
Nov 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-reply-directives-per-stream-update-20260919

Conversation

@steipete

@steipete steipete commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes repeated whole-answer directive parsing while a long reply with a reply or voice tag is streaming.

User Impact

Long tagged answers need less subscriber CPU and allocation while preserving streamed text, block replies, media extraction, and final output. No configuration change.

Why This Change Was Made

The raw directive accumulator and visible projection can differ only in edge whitespace. Compare their trimmed append text before rejecting the existing settled-directive append path. Output still uses the exact projected delta; Markdown ownership, new markers, media lines, and final snapshots retain their existing checks.

Evidence

Acceptance rule, set before baseline measurement: replay 32 KiB synthetic prose, media, reply-tag, voice-tag, and mixed replies through subscribeEmbeddedAgentSession in 32-character deltas, with block delivery on and off. Five interleaved A/A/B rounds, eight warm turns per sample, identical Node/runtime compilation. Require fewer parsed characters, lower CPU and allocated bytes for tagged replies, identical final/block output hashes, and no >20% regression in control workloads. Report wall/CPU/allocated bytes per complete reply, median/p95/spread, and A/A drift. Imports and provider/network/database/workspace I/O are outside this owner benchmark.

Measured medians per complete reply (five samples × eight turns; decimal MB). Node 26.12.1 on a shared 32-CPU host; one-minute load ranged 6.98–14.07. Imports are excluded from timing:

Workload Block delivery CPU ms before → after Allocated MB before → after Wall ms before → after
plain off 22.27 → 23.26 32.91 → 32.66 15.03 → 15.47
plain on 45.68 → 48.44 97.65 → 97.47 32.83 → 34.53
media off 29.41 → 23.37 37.06 → 37.05 23.72 → 17.32
media on 52.15 → 48.41 103.39 → 103.38 40.75 → 35.82
reply off 98.34 → 46.21 78.67 → 54.34 89.82 → 37.65
reply on 119.75 → 66.66 143.37 → 119.68 107.39 → 55.44
voice off 87.79 → 48.17 90.90 → 78.30 79.34 → 39.45
voice on 105.82 → 68.11 155.09 → 141.08 94.52 → 55.89
mixed off 194.51 → 189.21 103.30 → 96.81 185.06 → 177.39
mixed on 220.44 → 221.93 169.72 → 163.68 205.87 → 204.89

All final-text and block-payload hashes match across all arms. Plain CPU medians moved +4.4%/+6.0%, with overlapping A/A-control ranges; no plain-stream speedup is claimed. One mixed/block wall sample rose to 276.76 ms (base maximum 212.91 ms); a separate five-pair isolated recheck did not reproduce that tail: mixed/block wall median 206.12 → 193.59 ms, maxima 225.21 → 210.66 ms; CPU median 225.10 → 212.26 ms. The original outlier remains recorded. Mixed replies still retain full parsing after media changes the cleaned suffix.

The existing subscriber work-count test now includes reply and voice prefixes. On a 32 KiB reply in 3-character deltas, the base fails with 32,619,097 and 97,714,197 parsed characters; the candidate passes the existing <1,000,000 bound. A separate 32-character-delta probe reduces reply parsing from 311 calls / 5,109,669 characters to 1 call / 32 characters (4,985.04 → 0.031 parsed characters per delta). Voice drops from 311 / 5,129,509 to 1 / 32. Block consumers add two snapshot parses totaling 32 characters to each side; final snapshot/media parses remain required.

CPU profiles over the same reply workload show inclusive directive-parser time 975.91 → 36.30 ms, including splitMediaOutput 579.33 → 19.47 ms. These are profile-window totals, separate from uninstrumented timing samples.

Run the workload with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/reply-directives-stream-measure.ts; pass mixed to isolate the recheck. The fixture uses the real subscriber and delivery owners with a synthetic event source. It does not run a live model, Gateway, channel network, database or workspace. No whole-Gateway or production savings claim.

Runtime production delta: +1 line, for the existing-marker guard. No new cache/state/config/parser. Tooling adds a 147-line reproducible benchmark plus its Knip entry; regression growth is eight lines extending one existing table, with an exact eight-line allocation record. The first unguarded candidate was rejected for a measured media-only slowdown; the final guard avoids that wasted path. No changes to stream normalization or shared UI modules.

Validation: 117 focused tests passed (three wrapper shards, 54.22 s including cold compilation; work-count/lifecycle tests 48 cases, 2.24 s wrapper duration). Full-context Codex autoreview is scoped-clean at P0–P2 against base 64b382cf3d73 and the final five-file candidate, committed as cd9f34bd76ff. Both Knip unused-file scans passed with zero entries. pnpm check:changed --staged --base 64b382cf3d73 completed with failures; its changelog-attribution check has 20 inherited violations, reproduced exactly from the frozen main-parent sources. The current signature comes from 266a7aa0fe69 (#194364), which expanded the excluded handles without reconciling historical changelogs. Its parent has 26 different human-credit violations and none of these 20. This is a main regression to repair, not a passing check; this PR does not change its owner or changelog data. Two benchmark-only brace lint errors were fixed and the targeted script lint rerun passed. All typechecks, core lint, format and other selected guards passed. CI seconds are pending.

Timing distribution and unchanged-code controls

Values are median / p95 in milliseconds; with five eight-turn batch samples, p95 is the largest batch mean, not an estimate of individual production reply tails. A-control reruns unchanged base code. Raw final/block output hashes match for every arm.

Workload / blocks Base wall A-control wall Candidate wall Base CPU A-control CPU Candidate CPU
plain / off 15.03 / 15.23 15.26 / 15.86 15.47 / 15.92 22.27 / 22.82 22.93 / 23.99 23.26 / 24.14
plain / on 32.83 / 32.93 33.72 / 51.29 34.53 / 34.99 45.68 / 45.85 47.01 / 65.41 48.44 / 49.09
media / off 23.72 / 24.33 24.04 / 25.18 17.32 / 17.51 29.41 / 31.20 29.95 / 32.16 23.37 / 24.12
media / on 40.75 / 41.49 41.73 / 42.60 35.82 / 36.01 52.15 / 53.63 53.51 / 54.63 48.41 / 49.05
reply / off 89.82 / 90.08 90.97 / 93.31 37.65 / 38.03 98.34 / 98.92 98.98 / 102.03 46.21 / 46.86
reply / on 107.39 / 108.19 108.27 / 111.24 55.44 / 58.45 119.75 / 120.76 120.38 / 125.20 66.66 / 70.46
voice / off 79.34 / 79.59 78.75 / 80.10 39.45 / 39.93 87.79 / 88.16 87.61 / 88.74 48.17 / 48.87
voice / on 94.52 / 96.79 94.26 / 95.38 55.89 / 58.75 105.82 / 109.74 106.61 / 108.92 68.11 / 72.27
mixed / off 185.06 / 187.17 184.24 / 190.04 177.39 / 195.31 194.51 / 196.82 193.87 / 199.49 189.21 / 204.95
mixed / on 205.87 / 212.91 210.70 / 213.86 204.89 / 276.76 220.44 / 227.47 225.91 / 228.37 221.93 / 258.68

The dead-export check also fails identically on the exact main parent 64b382cf3d73, verified in an isolated checkout with the same workspace dependencies (no module-resolution errors):

Main regression Introduced by
scripts/plugin-npm-evidence-reuse.mjs: NPM_EVIDENCE_FILE c9e6370bb191 (#195099), which added the file/export
src/infra/path-containment.ts: canonicalizeForContainmentSync, UncanonicalReason ce840d8a8290 (#195061), which added the file/exports
src/test-utils/retention.ts: expectCollected, expectLiveObjects, forceFullGc 754b41c65df0 (#195064), which added these exports

These are outstanding main regressions, not ignored noise. No affected source, baseline, or guard is changed by this PR. The first baseline scan lacked nested workspace dependencies and was discarded; the qualified rerun reproduced the exact six-symbol set.

Reuse the existing settled-directive append path when raw and projected deltas differ only in edge whitespace. Gate the comparison with existing inline-marker state so media-only streams avoid unnecessary scans. Preserve exact emitted bytes and canonical parsing at syntax and terminal boundaries.

Extend the subscriber work-count regression and add a reproducible subscriber benchmark. Reply-tagged synthetic streams use 53% less CPU and 31% less allocation with block delivery off. Validation: 117 focused tests and clean Codex autoreview; changed checks retain attributed changelog and unused-export failures on the exact main parent.
@clawsweeper

clawsweeper Bot commented Nov 8, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T09:26:08.087698Z cd9f34b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: S labels Nov 8, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR avoids repeated whole-answer parsing when reply or voice directives leave raw and projected stream deltas differing only in edge whitespace.

Example: A 32 KiB answer beginning with [[reply_to_current]] streams in 32-character deltas.

  • Before: The supplied subscriber benchmark reports 5,109,669 characters passed through directive parsing.
  • After: The benchmark reports 32 parsed characters, with matching final-text and block-payload hashes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A narrow, source-supported optimization with useful subscriber measurements and regression coverage; running-Gateway evidence is absent and exact-head CI is unsettled.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored classification places this PR outside the ordinary contributor proof gate; its reported Node 26.12.1 benchmark exercises the real subscriber and delivery owners using synthetic events, rather than a shipped Gateway entry point.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long replies containing reply or voice directives spend unnecessary subscriber CPU repeatedly parsing accumulated text.
Reason: The maintainer-authored direction extends an established optimization with measured owner-level savings and no new runtime state, configuration, or public contract.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it makes a focused, worthwhile improvement to the existing streaming fast path, with no definite introduced correctness defect found.

Priority: P2
Reviewed head: cd9f34bd76ff8633e82f12c207bc393dfd19f608

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show this head streaming reply-tagged and voice-tagged answers through a running Gateway with preview/block output and final bytes preserved.
Agent review details

How this fits together

The embedded-agent subscriber receives provider text events, projects visible text, resolves reply directives, and forwards prepared text and metadata to preview and block-delivery consumers.

flowchart LR
  A[Provider text events] --> B[Embedded subscriber]
  B --> C[Directive accumulator]
  B --> D[Visible text projection]
  C --> E[Streaming reply resolver]
  D --> E
  E --> F[Preview callbacks]
  E --> G[Block delivery]
Loading

Technical review

Best possible solution:

Keep the fix in the existing streaming resolver, preserving exact emitted deltas and canonical parsing whenever append safety is uncertain.

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

Source inspection confirms that edge-whitespace differences reject the existing fast path; the supplied red-on-base work counts substantiate the resulting repeated parsing, but no target code was executed during this review.

Is this the best way to solve the issue?

This is the smallest complete runtime repair: normalize only the eligibility comparison, retain the exact projected append, and reuse the existing parser and invalidation checks.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Settled-directive append eligibility keeps the original intent (fix: keep the Gateway responsive during reply-tagged streams #166782: Avoid whole-document parsing after a settled directive while retaining canonical parsing for uncertain Markdown contexts; the later streaming refactor carried that contract forward.)
  • Subscriber work-count regression keeps the original intent (50bb9ed: Bound repeated parsing for streamed literal brackets while preserving canonical Markdown ownership behavior.)
  • Standalone benchmark registration keeps the original intent (fix: retain maintained command and preload roots #184233: Declare maintained commands invoked outside the import graph as executable audit roots.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e35bdeb adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:375 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e35bdeb087fa; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)
  • boeingchoco: Raw commit 3a2160c adds src/agents/embedded-agent-subscribe.handlers.messages.stream.ts:394 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3a2160c77f40; files: src/agents/embedded-agent-subscribe.handlers.messages.stream.ts)

PR surface

Source +1, Tests +8, Other +150. Total +159 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 9 1 +8
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 150 0 +150
Total 5 161 2 +159

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus regression growth Runtime net +1 line; regression tests net +8 lines The change reuses existing state and extends one established work-count table; the standalone measurement driver makes the bounded performance claim reproducible.

Labels

Label changes:

  • add P2: Reduces avoidable CPU and allocation during long directive-bearing replies without changing configuration or stored state.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Reduces avoidable CPU and allocation during long directive-bearing replies without changing configuration or stored state.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Add a running-Gateway comparison for reply and voice directives, preserving streamed output, block payloads, and final bytes.

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.

Reviewed November 8, 2026, 4:38 AM ET / 09:38 UTC.

@steipete
steipete merged commit 9496474 into main Nov 8, 2026
299 of 325 checks passed
@steipete
steipete deleted the steipete/perf-micro-reply-directives-per-stream-update-20260919 branch November 8, 2026 11:04
vincentkoc added a commit that referenced this pull request Nov 8, 2026
…tooling-lint-selection-20261108

* commit 'b0e90e6a4b359fff7756698067fdce4758b1907b': (38 commits)
  fix(android): Talk button demands a realtime provider on a native Talk setup (#191194)
  chore: trace first-run Gateway work and verify later replies (#195185)
  fix(knowledge): keep deleted messages out of reply previews (#195126)
  fix(agents): preserve streamed replies across Gateway restarts (#195164)
  perf(ci): reuse SDK transport path boundaries (#195180)
  fix(sandbox): avoid pauses for unchanged command checkpoints (#195120)
  fix(test): make retention checks portable across runtimes (#195091)
  fix(knowledge): clarify temporal kind filters (#194995)
  improve: reduce Gateway allocation while draining SQLite receipts (#195129)
  fix: reduce streaming CPU after reply and voice directives (#195145)
  fix: reduce Markdown reparsing during streamed tool-call checks (#195161)
  fix: restore the main dead-export gate (#195158)
  improve(ci): pack small UI selections into fewer jobs (#195107)
  fix(muse): quota and sign-in failures end with no reply (#195148)
  fix: allow first release push with shipped patch bytes (#195174)
  fix(ci): narrow single-config tooling selections (#195147)
  fix(packaging): reject incompatible prepublish plugin cohorts (#195152)
  fix(ci): prepare verified Bun before parity checks (#195155)
  fix: Incognito agent turns stall before execution (#195005)
  fix: credentialed search and speech providers work without picking a provider (#195169)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…195145)

Reuse the existing settled-directive append path when raw and projected deltas differ only in edge whitespace. Gate the comparison with existing inline-marker state so media-only streams avoid unnecessary scans. Preserve exact emitted bytes and canonical parsing at syntax and terminal boundaries.

Extend the subscriber work-count regression and add a reproducible subscriber benchmark. Reply-tagged synthetic streams use 53% less CPU and 31% less allocation with block delivery off. Validation: 117 focused tests and clean Codex autoreview; changed checks retain attributed changelog and unused-export failures on the exact main parent.
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant