Skip to content

perf(agents): reuse assistant and reply payload preparation - #133264

Merged
steipete merged 1 commit into
mainfrom
codex/perf50-payload-preparation
Aug 30, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf50-payload-preparation

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Assistant text extraction projected unphased replies twice, while terminal payload preparation eagerly parsed streamed text, normalized error strings and assembled comparisons that could not affect the selected reply. This repeated work sits between completed provider output and channel delivery.

Why This Change Was Made

Two measured changes simplify the existing owners:

  • Select the requested assistant phase before collecting text. Preserve explicit empty final answers, block-phase precedence, signed unphased text, legacy string sanitization and fresh reads of mutable transport blocks. Collect thinking summaries directly; signature-only blocks remain intact for API replay.
  • Remove the unreachable raw-error filter and its eager preparation, admit media comparison work only when the raw answer has media, and reuse parsed directives for the exact selected fallback answer. Canonical delivery/TTS facts, error/abort suppression, timeout recovery and message-tool duplicate handling remain authoritative.

Remove newly orphaned helper-barrel exports and keep the billing copy private to its owner. Existing integration tests use the canonical billing formatter; direct copy tests still assert the literal. No compatibility alias or parallel processing path is added.

Production +110/−197 = net −87; existing tests +16/−15 = net +1, with no test case added or removed. No dependency, config, schema, protocol, authorization or public API change.

Measurements and Tradeoffs

Four complete source compositions were measured in fresh Node 26.8.1 processes with opposite starting orders, balanced warmups and all samples retained. Instrumentation and correctness checks were excluded from timed loops. The combined change improved all 28 terminal-payload workloads in both orders:

Complete payload workload Before → combined, two process medians
Ordinary current final 8.545/8.638 → 4.610/4.580 µs
One streamed text 6.137/6.263 → 2.988/2.957 µs
Matching media answer 63.968/63.749 → 25.063/25.421 µs
Code-rich answer 3.669/3.636 → 1.232/1.244 ms

Isolated variants show payload preparation supplies most of these gains. Extraction alone improves the complete 64-block native-thinking subscriber workload from 74.365/73.121 to 66.364/67.568 µs. The combined short-final subscriber costs another 0.912/0.752 µs; the 64-block, 100-delta subscriber costs another 12.462/8.132 µs (about 1.2/0.8%). Final-at-last utility controls add 0.188/0.168 µs, and commentary/one-delta results are mixed. These costs are retained and accepted against the broader simplification and terminal preparation gains. No universal, provider/network, whole-turn or memory speedup is claimed.

Contracts and Verification

The final composition is compared against unchanged main with four variants: baseline, extraction only, payload preparation only and both changes. All 73 source/dependency bindings match. Differential proofs cover 11,458 leaf inputs, 708 subscriber scenarios (including 36 with raw diagnostics enabled), 672 payload cases and 55 controls. The separate payload-owner matrix covers 9,655 cases, 28,965 comparisons and 27 controls; these are distinct proof units, not an aggregate canonical-test total. Coverage includes explicit and inherited phases, empty/malformed final blocks, signed text, in-place transport mutation, complete subscriber events, canonical finals, media directives, streamed text, stored delivery/TTS, billing/provider errors, timeouts, aborts and suppression metadata. Output bytes and relevant object identity remain unchanged.

All 1,236 canonical tests across 48 files pass. The complete changed-file gate passes types, lint, import boundaries, dead exports and all other guards in 211.50 seconds. The initial gate exposed orphaned exports; removing them revealed four downstream test imports, which were migrated and rerun. Both failed receipts are retained. Fresh automated Codex review across P0–P3 and independent complete-owner review are clean.

The lead personally inspected the native Codex contracts in codex-rs/protocol/src/models.rs and codex-rs/protocol/src/protocol.rs in the sibling Codex checkout, alongside the OpenClaw extraction, subscriber and terminal owners. Optional message phases and separate reasoning/signature ownership remain unchanged. This is not a claim of live native Codex execution.

This is an internal performance refactor. Release-note context is recorded here; the release workflow owns the changelog. The separately recorded pre-existing literal-final-tag delivery defect remains outside this semantics-preserving scope.

At the published head 2c4ad2593df2f46f593900a95b72d9ea66700bc9, a fresh build passed in 155.92 seconds and another P0–P3 automated review is clean. An isolated real OpenAI Gateway completed three turns and two actual web_fetch calls, passing 51 assertions over 18 RPCs. The new-connection reader recovered in-flight tool progress; final conversation/history/list/status and cleanup checks passed. Raw diagnostics were enabled, with 93 records correlated to the three exact run IDs, including text, thinking and terminal events. The owned Gateway stopped cleanly and both Node CPU profiles were retained. These are behavior proofs, not controlled network-latency measurements. Exact-head hosted CI remains the final landing gate.

Landing Review

The completed ClawSweeper review found no introduced correctness or security defect. Its rank-up request for direct native-contract inspection is addressed: the lead personally inspected the sibling Codex checkout at 6478a751fde8884b2fdc76486fe23175a8e795d4, including codex-rs/protocol/src/models.rs:850–1060 (text content, optional message phase, and separate reasoning summary/encrypted content), codex-rs/protocol/src/protocol.rs:2448–2538 (message/reasoning events), and codex-rs/app-server-protocol/src/protocol/v2/item.rs:249–253,878–900 (app-server message projection). Absent phases remain unknown and retain the existing fallback.

OpenClaw's textSignature encoding is its own unchanged transport representation, not a new native Codex field. The lead also checked src/shared/chat-message-content.ts:26–80, the complete Codex conversation collector and assistant-message projector: native commentary filtering, unphased persisted narration and signed reasoning replay ownership remain unchanged. This direct source inspection resolves the review worker's missing-checkout limitation; it is not a claim of human review or live native Codex execution. The remaining rank-up request is completed exact-head CI; a queued review refresh does not replace that gate.

Exact-head CI run 33307266738 is now green. The long-running compact-small-35 shard passed without a retry. Both rank-up requests are addressed, and no accepted actionable finding remains. The final source review, 1,236 tests, full changed-file gate, build and real Gateway proof all cover the published head.

@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Aug 30, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 6:58 AM ET / 10:58 UTC.

ClawSweeper review

What this changes

The PR removes repeated assistant-text extraction and reply-directive parsing in the path from completed model output to channel reply payloads.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this member-authored, maintainer-labeled PR open. The reviewed extraction and payload changes preserve the covered phase, media, error, and delivery branches, but the required direct Codex protocol-source audit could not be completed because the sibling checkout is absent; that is a merge-decision gap, not a contributor defect.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is a focused net-reducing refactor with substantial stated validation, capped by the unavailable mandatory direct Codex contract audit.
Proof confidence 🌊 off-meta tidepool Not applicable: This member-authored internal refactor is exempt from the external-contributor proof gate; the PR body reports a real Gateway run, while the remaining gap is direct Codex contract inspection rather than contributor behavior proof.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This member-authored internal refactor is exempt from the external-contributor proof gate; the PR body reports a real Gateway run, while the remaining gap is direct Codex contract inspection rather than contributor behavior proof.
Evidence reviewed 6 items Changed phase owner: The introduced phase selector preserves explicit empty final-answer ownership, falls back to unphased text only when no final text exists, and retains the final-answer sanitizer for signed unphased blocks.
Payload owner and terminal caller: Payload preparation reuses directive parsing only for the selected fallback answer; terminal preparation passes the completed attempt’s assistant, streamed text, delivery facts, and abort state to this owner.
Existing behavioral coverage: Current tests cover final-over-commentary selection, empty final-answer suppression, legacy unphased fallback, signed unphased suppression, and payload fallback behavior.
Findings None None.
Security None None.

How this fits together

Embedded-agent output is separated into commentary, final text, thinking, errors, and media before channel delivery. The changed utilities select visible text and prepare the final reply payload used by terminal completion and streaming subscribers.

flowchart LR
  A[Provider response] --> B[Assistant text extraction]
  B --> C[Phase selection]
  C --> D[Reply payload preparation]
  D --> E[Terminal delivery]
  C --> F[Streaming subscribers]
  D --> G[Media and error handling]
Loading

Decision needed

Question Recommendation
Can a maintainer complete or confirm the required direct Codex protocol-source audit for this refactor before it merges? Complete the protocol audit: Compare the changed phase selection against the exact Codex text and reasoning protocol types, then merge if the contract matches.

Why: The PR’s claimed compatibility depends on native Codex phase and reasoning semantics, while the required sibling checkout was unavailable to this read-only review.

Before merge

  • Resolve merge risk (P1) - Final-answer and reasoning-phase compatibility with native Codex messages remains unverified by direct primary-source inspection; a wrong assumption could suppress or expose assistant text on existing provider paths.
  • Complete next step (P2) - A maintainer must complete the direct Codex protocol-source check required for this compatibility-sensitive refactor; no mechanical repair is identified.
Agent review details

Security

None.

PR surface

Source -87, Tests +1. Total -86 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 110 197 -87
Tests 6 16 15 +1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 126 212 -86

Review metrics

Metric Value Why it matters
Production versus test LOC production −87, tests +1 The refactor materially reduces hot-path production code while retaining the existing focused behavioral suites.

Merge-risk options

Maintainer options:

  1. Complete native protocol verification (recommended)
    Inspect the exact Codex protocol representation of phase-bearing text and signed reasoning before merging this response-selection refactor.
  2. Pause pending source access
    Keep the PR open until a reviewer can perform the mandatory direct dependency audit.

Technical review

Best possible solution:

Before merge, inspect the exact native Codex protocol types for phase-bearing text and reasoning items, then retain this net-reducing canonical preparation path only if those contracts match the reviewed final/commentary behavior.

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

Not applicable: this PR is a behavior-preserving performance refactor, not a report of a reproducible defect. Existing focused tests define the relevant phase and payload behavior, but no code was executed in this read-only review.

Is this the best way to solve the issue?

Unclear: the reviewed code simplifies the existing owner without an identified semantic regression, but direct Codex protocol-source verification is still required for the stated compatibility claim.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8e1cda9854ad.

Labels

Label justifications:

  • P3: This is an internal performance and simplification refactor without a reported user-facing regression.
  • merge-risk: 🚨 compatibility: It changes final-answer, commentary, and signed-reasoning selection that existing provider and channel paths consume.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This member-authored internal refactor is exempt from the external-contributor proof gate; the PR body reports a real Gateway run, while the remaining gap is direct Codex contract inspection rather than contributor behavior proof.

Evidence

What I checked:

  • Changed phase owner: The introduced phase selector preserves explicit empty final-answer ownership, falls back to unphased text only when no final text exists, and retains the final-answer sanitizer for signed unphased blocks. (src/agents/embedded-agent-utils.ts:50, 2c4ad2593df2)
  • Payload owner and terminal caller: Payload preparation reuses directive parsing only for the selected fallback answer; terminal preparation passes the completed attempt’s assistant, streamed text, delivery facts, and abort state to this owner. (src/agents/embedded-agent-runner/run/payloads.ts:266, 2c4ad2593df2)
  • Existing behavioral coverage: Current tests cover final-over-commentary selection, empty final-answer suppression, legacy unphased fallback, signed unphased suppression, and payload fallback behavior. (src/agents/embedded-agent-utils.test.ts:660, 2c4ad2593df2)
  • Current-main necessity: The fetched current main revision retains the pre-refactor extraction and payload preparation, so the central performance cleanup is not already implemented there. (src/agents/embedded-agent-utils.ts:50, 8e1cda9854ad)
  • Codex contract audit unavailable: The PR explicitly relies on native Codex phase and reasoning semantics, but the required sibling Codex source checkout was absent and no direct protocol-source inspection was possible in this read-only environment.
  • Area history: Recent current-main path history includes Peter Steinberger’s earlier payload-area work; the available shallow/promisor history cannot prove feature introduction for the exact current lines. (src/agents/embedded-agent-runner/run/payloads.ts:125, 8286e2502667)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: 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.

  • Complete direct inspection of the exact Codex phase and reasoning protocol sources before merge.

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 (1 earlier review cycle)
  • reviewed 2026-08-30T10:51:22.876Z sha 2c4ad25 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit 162c33e into main Aug 30, 2026
256 checks passed
@steipete
steipete deleted the codex/perf50-payload-preparation branch August 30, 2026 11:04
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 3, 2026
Block: inline raw-answer resolver in run/payloads.ts (drift residue).
Home: restored to upstream (drift residue).

Upstream moved resolveRawAssistantAnswerText into its owner
src/shared/assistant-answer-text.ts (0863f26 openclaw#150539, then
06e6c06 openclaw#148360). Our payloads.ts kept a private copy
(isAssistantTextContentBlockType, readAssistantTextContentBlock,
sanitizeCanonicalAssistantItemText, resolveRawAssistantAnswerParts).
It also kept assistantTextsHaveMedia / normalizedRawAnswerText and a
redundant !assistantTextsHaveMedia guard that 162c33e (openclaw#133264)
removed.

Restore upstream's import and media-comparison bytes. The continuation
need (one raw part per final-answer block, optionally keeping item
whitespace) moves to the owner as resolveRawAssistantAnswerParts;
resolveRawAssistantAnswerText now joins its parts and keeps upstream's
output for every input. payloads.ts keeps only rawAnswerHasContinuation,
the earlier-continuation per-hop split and preserveTextWhitespace.

Refs #1418

Co-Authored-By: Claude Opus 5.5 <[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 maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant