Skip to content

improve: reduce CPU work for long CLI reasoning streams - #152191

Merged
steipete merged 1 commit into
mainfrom
codex/perf-cli-reasoning-scan-dc66
Sep 18, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf-cli-reasoning-scan-dc66

Conversation

@steipete

@steipete steipete commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long Claude CLI reasoning streams spend increasing CPU time reparsing buffered text before the answer becomes visible.

User Impact

Long tagged reasoning streams require less parser work while preserving visible text, reasoning callbacks and their delivery boundaries. No configuration or transcript-format changes are required.

Why This Change Was Made

The existing lexical parser records whether reasoning is open with no unfinished tag. In that state, an appended chunk without < cannot change the pending decision. The router retains every raw chunk and skips that redundant scan; chunks containing < and finalization still use the original parser. Partial tags, malformed recovery, Markdown code ownership, consecutive blocks, native-thinking deduplication and later literal tags retain their existing behavior.

Evidence

  • 77 focused tests across four files passed. Syntax lint (230 rules), canonical oxfmt and diff checks passed. Fresh canonical P0-P2 autoreview passed with no findings and unchanged reviewed sources. Full exact-head CI passed for a85fe70bed9a8e851c0e080b7d28ee1628576031. ClawSweeper also completed with no findings.
  • Real createCliJsonlStreamingParser boundary with synthetic Claude JSONL records: 19 correctness cases and eight workload scenarios preserve complete callback payloads, per-push output/error/terminal state and final output against separate same-runtime baseline captures.
  • Linux/WSL2, Node 24.19.0 and 26.8.2: 24 fresh timed processes, six adjacent balanced BC/CB pairs per runtime, three blocks per scenario; two additional baseline-oracle processes. All 576 blocks and 193,752 timed calls are retained, with no zero CPU blocks. Counts were fixed using only the two baseline pilots.

The table shows median paired percentage changes, after taking each process's three-block median. Negative is faster. Sizes are UTF-16 code units; chunks contain 64 or 128 units.

Scenario Node 24 wall Node 24 CPU Node 26 wall Node 26 CPU
Tagged reasoning, 512 units -3.54% -6.71% -0.10% -0.97%
Tagged reasoning, 16 Ki units -16.28% -14.99% -16.44% -14.89%
Tagged reasoning, 64 Ki units -20.89% -21.22% -36.11% -55.21%
Tagged reasoning, 256 Ki units -82.16% -82.03% -72.24% -58.07%
Multiline tagged reasoning, 16 Ki units -5.26% -4.40% -4.80% +1.69%
Invalid-tag-bearing control, 16 Ki units -0.04% -0.24% +3.28% +3.83%
Plain-text control, 4 Ki units +2.70% +3.01% -3.55% +3.41%
Native-thinking control, 16 Ki units +1.49% +2.79% -2.03% -0.85%

All 36 pairs for the 16/64/256 Ki tagged streams improved both wall time and CPU. Median paired CPU savings per stream were approximately 278 microseconds, 1.51–6.83 milliseconds and 93.8–99.8 milliseconds, respectively.

Small and control cases are mixed: all six Node 24 plain-text CPU pairs regressed (median approximately 1.92 microseconds), and Node 26 multiline pair 3 regressed 30.26% wall/54.45% CPU. These results are retained, not retried or excluded. Mean process peak RSS fell 18.66 MiB on Node 24 and 41.68 MiB on Node 26, but those peaks include all scenarios and proof retention; they do not measure per-case heap or allocation savings.

This measures JSONL decoding, fresh parser construction, pushes, callbacks and finish/getOutput, excluding provider latency, process spawning and downstream delivery. Oracle work is outside the timed interval but can affect later GC. The result supports the long tagged-prefix path, not a universal, end-to-end, cold-start or statistical-significance claim. Production workload frequency was not measured.

Independent saved-data recomputation matched all 96 scenario pairs and 16 summaries, verified raw hashes/order/full parity/checksums, and recomputed baseline-only sizing. Retained audit SHA-256: ef4f6f82612ae4b5f15ad4c5f3c514db5e4b376456e8bbf28b1b00bb365a7c94.

@clawsweeper

clawsweeper Bot commented Sep 18, 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.

@steipete
steipete marked this pull request as ready for review September 18, 2026 22:05
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS maintainer Maintainer-authored PR labels Sep 18, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 18, 2026
@clawsweeper

clawsweeper Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 18, 2026, 6:11 PM ET / 22:11 UTC.

ClawSweeper review

What this changes

The PR reduces repeated parsing during long Claude CLI reasoning streams while preserving buffered text and callback delivery.

Merge readiness

✅ Ready for maintainer review

Keep open: the optimization remains useful, is absent from fetched main and the latest release, and introduces no identified correctness defect.

Priority: P2
Reviewed head: a85fe70bed9a8e851c0e080b7d28ee1628576031

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with a sound lexical invariant, meaningful boundary coverage, and appropriately scoped performance evidence.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.
Evidence reviewed 8 items Introduced optimization: The pinned introduced diff retains incoming text before skipping redundant scans; unfinished tags and finalization continue through the existing parser. The complete diff contains only the router change and focused parser tests.
Lexical invariant: The scanner discovers tags through '<' and reports unfinished candidates explicitly. With no pending candidate, appending text without '<' cannot alter the completed tag sequence or lexical depth. Markdown ownership is evaluated later by the unchanged partitioner.
Production caller and lifecycle: Claude text deltas enter the changed router; message boundaries, terminal results, and finish flush it. New messages create a fresh router. Native thinking deduplication and visible-text projection remain unchanged. This path uses OpenClaw’s local parser and establishes no Codex dependency requirement.
Findings None None.
Security None None.

How this fits together

OpenClaw’s CLI output parser receives structured records from external CLI backends and separates reasoning from visible answers. The changed router buffers leading reasoning tags before forwarding the resulting text to agent callbacks.

flowchart TD
  A[Claude CLI records] --> B[JSONL parser]
  B --> C[Leading reasoning buffer]
  C --> D{Open block and no unfinished tag?}
  D -->|Chunk has no opening bracket| C
  D -->|Possible tag or finalization| E[Existing tag parser]
  E --> F[Reasoning callbacks]
  E --> G[Visible answer callbacks]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +10, Tests +12. Total +22 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 14 4 +10
Tests 1 17 5 +12
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 31 9 +22

Review metrics

Metric Value Why it matters
Long-stream benchmark 36/36 reported pairs improved wall time and CPU The measured benefit covers 16/64/256 Ki-unit tagged streams across two Node runtimes; control cases remain mixed.

Technical review

Best possible solution:

Keep the existing parser authoritative and bypass only scans whose pending result cannot change.

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

Yes, from source: a long unclosed leading reasoning block makes current main scan the growing buffer on every text chunk. The PR supplies measured parser-boundary results; this review did not execute benchmarks.

Is this the best way to solve the issue?

Yes. The shortcut reuses an existing lexical fact without replacing parsing policy, changing callback boundaries, or adding configuration.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded runtime performance improvement for long CLI reasoning streams.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.

Label justifications:

  • P2: This is a bounded runtime performance improvement for long CLI reasoning streams.
  • 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 supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied before/after measurements exercise the changed production JSONL parser with synthetic Claude records on two Node runtimes, reporting callback/output parity and lower long-stream CPU cost; they support the parser optimization without claiming end-to-end provider improvements.

Evidence

What I checked:

  • Introduced optimization: The pinned introduced diff retains incoming text before skipping redundant scans; unfinished tags and finalization continue through the existing parser. The complete diff contains only the router change and focused parser tests. (src/agents/cli-output-events.ts:698, a85fe70bed9a)
  • Lexical invariant: The scanner discovers tags through '<' and reports unfinished candidates explicitly. With no pending candidate, appending text without '<' cannot alter the completed tag sequence or lexical depth. Markdown ownership is evaluated later by the unchanged partitioner. (packages/markdown-core/src/reasoning-tag-parser.ts:46, a85fe70bed9a)
  • Production caller and lifecycle: Claude text deltas enter the changed router; message boundaries, terminal results, and finish flush it. New messages create a fresh router. Native thinking deduplication and visible-text projection remain unchanged. This path uses OpenClaw’s local parser and establishes no Codex dependency requirement. (src/agents/cli-output-stream.ts:169, a85fe70bed9a)
  • Behavioral coverage: The tests exercise split tag names, quoted attributes, and rejected prefixes through the JSONL parser and assert callback timing and final output. Existing cases cover consecutive blocks, native thinking, incomplete input, and message resets. Tests were inspected, not executed during this read-only review. (src/agents/cli-output-reasoning.test.ts:121, a85fe70bed9a)
  • Still needed on main: Fetched main still reparses the entire pending prefix on every chunk and lacks the new lexical-state shortcut. (src/agents/cli-output-events.ts:694, 52e409a739b1)
  • Latest release comparison: The v2026.9.4 source also contains the unconditional scan. GitHub’s contents endpoint supplied the release source after the local release-blob read failed. (src/agents/cli-output-events.ts, 3a9d69db306c)

Likely related people:

  • steipete: 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.

@steipete
steipete merged commit 89c1884 into main Sep 18, 2026
284 checks passed
@steipete
steipete deleted the codex/perf-cli-reasoning-scan-dc66 branch September 18, 2026 22:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 18, 2026
…pr-149099-main-20260918

* commit '795e460278d4f8f41545dc8b4a66da1d12defd90': (1902 commits)
  refactor(slack): share Markdown preparation (#149129)
  fix(tooling): release completed PR operations with exited loaders (#152209)
  fix(release): allow stable npm bootstrap under an operator soak waiver (#152206)
  fix(daemon): avoid false restart timeouts during slow startup (#151387)
  feat: read agent documents from a host-owned workspace (#150584)
  improve(startup): skip redundant single-agent directory checks (#152192)
  test(ui): await board widget readiness before size reports (#152198)
  perf(browser): move dashboard event discovery to SQLite worker (#151952)
  improve(auth): reduce pauses during concurrent credential reads (#152140)
  improve(ui): load older chat history in smaller pages (#152093)
  fix(release): reject incomplete legacy npm install trees (#152186)
  refactor: share current-conversation binding row serialization (#152134)
  test(tooling): preserve Node and terminal fixture ownership under Bun (#152187)
  fix(sqlite): service worker admission through retained path aliases (#152190)
  improve: reduce CPU work for long CLI reasoning streams (#152191)
  chore(ui): refresh control ui locales (#152196)
  test(subagents): align lifecycle retries with durable completion owners (#152184)
  perf(gateway): defer participant maps for owned sessions (#152097)
  refactor(stream): share auxiliary queue overflow handling (#149282)
  fix(test): execute CLI fixture preloads on Node and Bun (#152076)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 19, 2026
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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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