Skip to content

improve: reduce Gateway stalls during compaction rewrites - #202547

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-compaction-transcript-clones-20260919
Nov 20, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-compaction-transcript-clones-20260919

Conversation

@steipete

@steipete steipete commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Rewriting a few messages during compaction copies unchanged conversation history on the Gateway thread, delaying other chats and creating avoidable garbage.

User Impact

Compaction transcript rewrites retain immutable history instead of making it writable and copying it again. Saved messages, replacement output, SDK mutation behavior, and commit checks stay unchanged. No configuration or migration is needed.

Why This Change Was Made

Matching and replay only read the branch, but both used the public writable accessor. On hydrated histories that detaches every payload before the rewrite snapshot can share it. Both reads now use the existing internal branch reader. The snapshot owner still copies mutable SDK data and private navigation containers; no new sharing policy or cache is introduced. Production delta is +2 lines (an import and ownership comment).

The initial-context projection still needs its clone: its fresh array borrows nested entries and SDK data. Freezing it in place would violate mutation isolation. This PR changes only the proven redundant writable exposure in the rewrite path.

Evidence

The regression fails on the exact base at the unchanged-payload identity assertion and passes with the fix. It also rejects mutation of shared history and proves subsequent writable SDK edits cannot change retained model context or durable history. All 92 focused tests pass, including existing opaque aliases, stale commit, metadata, notifications, plugin reads, and prompt-prefix stability. Isolated Codex autoreview through P2 is clean.

The committed benchmark exercises initial-context publication and a real two-entry rewrite/commit on a 1,700-message, 21,158,679-byte synthetic persisted history. Five counterbalanced A/A and five A/B pairs use five measured operations per process; allocation is measured in separate collected-inclusive sampling runs. All 200 measured outputs match an independently constructed expected result and have identical iteration-specific complete-context digests across arms. SQL setup/hydration is excluded; commit is included. This is owner-boundary proof, not whole-Gateway or provider-inference performance.

Original campaign, median across five processes Baseline Candidate
Rewrite mean thread CPU 322.904 ms 15.839 ms
Rewrite p50 wall 333.094 ms 22.289 ms
Rewrite sampled allocation 277.521 MB 9.624 MB
Initial-context mean thread CPU 61.265 ms 62.431 ms
Initial-context sampled allocation 140.770 MB 140.986 MB

Rewrite CPU improves 95.1% and allocation 96.5%. A/A rewrite CPU differs 0.84%, allocation 0.41%. Separate CPU profiles support the owner diagnosis: inclusive cloneTranscriptView samples fall from 626.28 to 34.84 ms, and rewrite preparation from 206.61 to 11.94 ms, across one warmup and one measured operation.

Accepted tail limitation: original pooled initial-context p95 was 66.166 → 90.280 ms (+36.4%), despite this code being unchanged. An additional A/A control and five counterbalanced A/B pairs, now ten measured operations per process, retain this concern: initial-context pooled p95 67.471 → 87.750 ms (+30.1%), mean CPU 61.051 → 62.532 ms (+2.4%), median wall 61.017 → 61.320 ms (+0.5%). Rewrite pooled p95 improves 364.983 → 40.632 ms and mean CPU 323.445 → 15.886 ms in that qualification. All additional outputs match. Shared-host scheduling contributes to some spikes (135 ms wall / 71 ms CPU), but this is not proof that the tail difference is harmless. No samples were discarded. The initial-context clone is retained, and no first-stall elimination claim is made.

The Team perf-loop lead accepted this limitation as an agent acting under Peter's standing unattended-operations instruction, not as Peter. Rationale: this fixes the rewrite path identified in production as a 2.5-second main-thread stall; synthetic proof reduces rewrite CPU 95.1% and allocation 96.5%, with all 320 measured output comparisons identical. The initial-context path is unchanged because its projection borrows mutable SDK data. Its median latency and allocation are effectively unchanged; the roughly +20 ms p95 (67.5 → 87.7 ms) on that untouched path at small sample size is accepted as unattributed. Production delta is two lines. Acceptance removes only the performance hold; exact-head CI and final-head ClawSweeper must still pass.

Focused command: node scripts/run-vitest.mjs src/agents/embedded-agent-runner/transcript-rewrite.test.ts src/agents/embedded-agent-runner/transcript-rewrite-metadata.test.ts src/agents/embedded-agent-runner/transcript-rewrite-plugin-reads.test.ts src/agents/embedded-agent-runner/transcript-rewrite-notifications.test.ts src/agents/sessions/session-manager-maintenance-async.test.ts src/agents/sessions/session-manager-codec.test.ts src/agents/agent-tools.prefix-stability.test.ts --maxWorkers=1 (92 tests; 176.30 s including compilation and four shards).

pnpm check:changed completed: all guards pass except the original proof-code type/lint errors (both corrected and rechecked successfully) and an unrelated unused CronSchedule export introduced by #202416 at the exact base 44ec89e71877ef2194e18a028ab828b995203844. The same dead-export guard reproduces both findings in a clean worktree on that exact parent with frozen dependencies (exit 1). This remains a reported main regression, not a green full-check claim. Final-head CI run 44770160216 passed. ClawSweeper re-review on 8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11 has no findings and zero open before-merge items; it acknowledges the performance acceptance. Native scripts/pr merged that exact head as 018e2fb364bb977d8f537a671b8df0fa35933910, verified reachable from main. The regression fixture was corrected to await async open/appends after hosted Codex feedback; that final fixture fails on the exact base at the intended identity assertion and passes at final head 8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11. CI caught missing narrowing of async append IDs in the first fixture correction; existing expectDefined assertions now establish that contract. The affected test typecheck and regression pass, the assertion correction has a clean isolated Codex review, and the hosted thread is resolved. Production/benchmark source is unchanged. No browser-runtime module or visual behavior changes; import search under ui/src found no changed-module consumers.

Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark.
@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 20, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 20, 2026
@steipete
steipete marked this pull request as ready for review November 20, 2026 15:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T16:09:33.773175Z 8c72a97 New commits
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4a004a3342

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review final head 922648d447528b810d16fc3f80a80cb3fedca662. The earlier review lease was superseded before publication. The async fixture correction is proven red on the exact base and green on this head; its hosted Codex thread is resolved. The PR body now records the complete timing/allocation campaign, an additional five-pair tail qualification, ownership limits, and the explicit performance-owner acceptance hold. Production and benchmark source are unchanged from the first reviewed commit.

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head is now 8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11. CI found that the async fixture's append IDs needed narrowing; the test now uses existing expectDefined assertions. The affected typecheck and selected regression pass, and isolated Codex review of the correction is clean. No production or benchmark source changed. Please supersede the prior-head reservation and review this final head; the complete performance evidence and owner-acceptance hold are current in the PR body.

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR uses the existing internal read-only transcript accessor during rewrite matching and replay to avoid unnecessary history copies.

Example: Rewrite a tool result near the end of a persisted 1,700-message conversation.

  • Before: Writable branch access detaches unchanged message payloads before preparing the rewrite.
  • After: Unchanged immutable payloads remain shared while the replacement and commit use the existing rewrite owner.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, correct improvement supported by persisted-owner measurements and a meaningful isolation regression; the evidence remains scoped to an in-process benchmark.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal performance change is outside the contributor proof gate; supplied evidence exercises the real persisted rewrite owner on synthetic history, without claiming whole-Gateway latency results, and the inspected prepared images concern an unrelated Knowledge UI change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Transcript rewrites copy unchanged conversation history on the Gateway thread, delaying other chats and creating avoidable garbage.
Reason: The maintainer-authored direction removes measured redundant work through existing owners, and the recorded performance-tail tradeoff has been explicitly accepted.

Merge readiness

✅ Ready for maintainer review

Keep this useful, maintainer-authored PR open: the earlier performance hold is resolved, and the focused change has no actionable findings.

Priority: P2
Reviewed head: 8c72a97b5d3a4728e5c3f9bf3f4bad1c040c8f11

Before merge

None.

Findings

None.

Agent review details

How this fits together

Compaction and transcript-maintenance callers submit message replacements to the embedded runner, which prepares a detached SessionManager branch and commits it through the existing persistence owner.

flowchart TD
  A[Compaction or maintenance] --> B[Transcript rewrite]
  B --> C[Internal branch reader]
  C --> D[Detached rewrite snapshot]
  D --> E[Replay changed suffix]
  E --> F[Existing persistence commit]
Loading

Technical review

Best possible solution:

Use the existing internal branch reader at both read-only rewrite sites while retaining the snapshot owner's mutation isolation and atomic commit.

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

Current main's rewrite calls the writable accessor, whose implementation detaches hydrated payloads; the supplied regression and persisted-owner benchmark exercise this path, but no target code was run during this read-only review.

Is this the best way to solve the issue?

The two accessor substitutions are the smallest complete repair: they remove unnecessary writable exposure without adding state, changing public APIs, or moving persistence responsibility.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Rewrite branch reads and atomic publication keeps the original intent (b0ae5b6: Publish complete replacement branches atomically and preserve selected ancestry without reset amplification.)
  • Awaited rewrite persistence keeps the original intent (82a4cfb: Move bundled transcript mutations onto awaited writer-backed persistence while retaining SDK compatibility.)
  • Immutable internal reads and writable SDK views keeps the original intent (245cbaf: Share sealed history among internal readers and detach mutable data at public exposure boundaries.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 82a4cfb adds src/agents/embedded-agent-runner/transcript-rewrite.ts:179 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 82a4cfbe57d7; files: src/agents/embedded-agent-runner/transcript-rewrite.ts)
  • RoboClaw: Raw commit b0ae5b6 adds src/agents/embedded-agent-runner/transcript-rewrite.ts:186 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b0ae5b6793e5; files: src/agents/embedded-agent-runner/transcript-rewrite.ts)

PR surface

Source +2, Tests +39, Other +209. Total +250 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 4 2 +2
Tests 1 39 0 +39
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 209 0 +209
Total 3 252 2 +250

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.

Labels

Label changes:

  • 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.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on maintainer: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Avoidable full-history copying can delay unrelated Gateway work during transcript maintenance, and this PR provides a narrow measured improvement.
  • 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.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-20T16:15:46.936Z sha 8c72a97 :: blocked before merge. :: none

Reviewed November 20, 2026, 11:27 AM ET / 16:27 UTC (Revision 2).

@steipete

steipete commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Item 1 — Resolved: the performance owner explicitly accepted the tail limitation.

The Team perf-loop lead accepted it as an agent acting under Peter's standing unattended-operations instruction, not as Peter. The acceptance and rationale are now recorded in the PR body and were verified by readback. It releases the performance hold only; exact-head CI and this re-review still gate merge.

Rationale: the rewrite path identified in production as a 2.5-second main-thread stall drops synthetic CPU 95.1% and allocation 96.5%, with all 320 measured output comparisons identical. The two read-only substitutions are at transcript-rewrite.ts:164 and transcript-rewrite.ts:180. The initial-context clone at session-manager-codec.ts:298 is unchanged because its projection borrows mutable SDK data. Its median latency and allocation are effectively unchanged; the roughly +20 ms p95 (67.5 → 87.7 ms) on that untouched path at small n is accepted as unattributed. Production delta: +2 lines.

The evidence remains explicitly scoped to the real persisted transcript rewrite owner on a synthetic 1,700-message fixture. It does not claim a measured whole-Gateway or provider-inference latency improvement. The accepted initial-context optimization question is a separate follow-up, not part of this landing.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. labels Nov 20, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Nov 20, 2026
@steipete
steipete merged commit 018e2fb into main Nov 20, 2026
151 of 154 checks passed
@steipete
steipete deleted the steipete/perf-micro-compaction-transcript-clones-20260919 branch November 20, 2026 16:31
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…02547)

* perf(agents): preserve sealed history during transcript rewrites

Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark.

* test(agents): await rewrite regression seed persistence

* test(agents): require seeded transcript entry IDs
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
* perf(agents): preserve sealed history during transcript rewrites

Use the internal read-only branch boundary for rewrite matching and replay so hydrated payloads remain shared through preparation and publication. Preserve writable SDK and opaque graph isolation in the existing snapshot owner. Add mutation regression coverage and a synthetic compaction transcript benchmark.

* test(agents): await rewrite regression seed persistence

* test(agents): require seeded transcript entry IDs

(cherry picked from commit 018e2fb)
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 39782333d63dbb44633bd9b955f99a7948866e59)
(cherry picked from commit b0b733aa06dd55aecbabfa132df431bdc2779938)
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: 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