Skip to content

perf(agents): build session forks only when requested - #182844

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-fork-pay-on-fork-20260919
Oct 24, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-fork-pay-on-fork-20260919

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every normal embedded model request paid to prepare and retain a replay snapshot for an optional session fork, even when no caller ever forked the session.

User Impact

forkSession now prepares its request only when called. Existing sessions can be forked after runtime cleanup or restart, including compacted history, without first sending another normal message. Forks still return text and usage, cannot execute tools, and remain bound to current session/model authority.

Why This Change Was Made

The active session and persisted transcript already own conversation history. Forks borrow the current live context or reconstruct the transcript's model view, hydrate its pinned prompt/tool checkpoint through the existing worker, and use the normal provider payload builders. This removes request capture, publication copies, expiry timers, and the separate snapshot budget/store rather than adding an opt-in capture path or plugin contract.

Stored continuation remains a possible optimization for qualifying completed OpenAI Responses requests. The current continuation owner claims parent state and is process-local; ChatGPT uses connection-scoped continuation with store:false, while other providers and restarted sessions still need reconstruction. This change uses one complete reconstruction path. The actual production endpoint/store setting was not inspected, and stored continuation was not benchmarked against reconstruction.

Unchanged native Responses prefixes, tool schemas, and instructions remain identical in the integration proof. All reconstructed forks, including live forks, omit parent cache identity because they do not share the complete one-shot request preparation. Completed forks honor the configured channel history window. Cache reuse is best effort elsewhere: older routes without a prompt pin rebuild their configured/bootstrap instructions, and transient hook additions or explicit run-only cache keys cannot be recovered after completion. Parent one-shot hooks are never rerun. Current credentials, proxy/TLS policy, pending-call pairing, and hosted/local tool denial remain enforced. Forks replay already-admitted tool-result projections without changing parent pruning state, including durable pre-compaction checkpoints and branch/reset boundaries. Normal turns and forks share one image-policy converter; blocked inline and deferred images cannot reach the provider.

Runtime production LOC: −24. The requested production diff excluding tests, test-support files, and docs/* is −362, including removal/update of obsolete benchmark machinery. Test code is −275 LOC.

Evidence

  • Final repair proof: real embedded runtime integration 4 passed, direct fork transport 19 passed, and prompt-prefix stability 11 passed. The separate image-policy/SDK and session-manager run passed 66 existing/new tests; its new cold-fork fixture initially needed a durable branch append, then passed independently. Projection replay 12 passed, including another pass after the sibling extraction, and native WebSocket continuation/idle siblings 12 passed. The expanded scoped typecheck passed.
  • Gateway transport regression: 1 passed with compacted durable history, the configured channel history window, no process-local parent capture, and no dispatch for an unauthorized reader. Exact baseline owner/caller 42f68fade98da4f30f56a182a3392700f62ef2d5 fails the persisted-history case with the original missing-parent-snapshot error. The history-window assertion separately failed on the initial PR head before its repair.
  • Native Responses prefixes, images/tool results, live and completed request affinity omission, pending tools, and tool-denial precedence are asserted at actual transport boundaries. Native WebSockets verify cache-identity omission with both absent and explicitly supplied parent keys, while preserving the parent's continuation.
  • Import/source-closure guards: 22 passed again after the final sibling extraction. Export-name collision and line-cap guards passed. Import-cycle check reports 0 cycles; the new persisted-data assertion has its owner invariant documented.
  • Changed-file formatting/type-aware lint, targeted pnpm tsgo:core, and the expanded typecheck scoped to the seven affected fork/image/projection test files passed.
  • Independent subagent review (autoreview route unavailable): actionable findings were fixed and final repairs reviewed clean. The configured autoreview helper refused the requested provider route; no operator configuration was changed.
  • Initial PR CI found a test fixture type mismatch, benchmark lint issue, missing assertion invariant, and a type-dependency cycle; all are repaired in the current head. The plugin lifecycle shard also reported two inherited failures, documented below. The final head’s failed shard reports exactly the same two inherited plugin-lifecycle failures. All other selected final-head checks passed, including PostgreSQL conformance, architecture, docs, agent-runtime quality, and all six security-boundary checks. The aggregate CI gate reflects the inherited shard failure. No CI rerun was requested.

Mock-provider cache-read usage proves usage forwarding alongside exact wire-prefix assertions; this is not live provider billing/cache-effectiveness evidence.

Inherited CI Evidence

Both unrelated plugin lifecycle assertions expect restartRequired: false after a bundled-plugin reload, while the owner changed in #182403 returns true.

  • src/gateway/server-plugins.lifecycle.channels.test.ts:405, “hands off webhook accounts…”: identical assertion in scheduled main CI at 28d61de4e4d1870d6f2765282eabaaa71f317ec4.
  • src/gateway/server-plugins.lifecycle.test.ts:459, “keeps Gateway available after timeout cleanup refuses replacement”: reproduced against exact main source 4d49d348a5c21381bdca622d053faa3b4f98e3b4 with node scripts/run-vitest.mjs src/gateway/server-plugins.lifecycle.test.ts --maxWorkers=1 (3 passed, 1 failed, same false→true assertion, 57.14s). The lane patch was temporarily reversed and restored with byte-for-byte verification; no unrelated source was changed.

Measurement Protocol

Two concurrent, CPU-swapped pairs completed under the shared guard on the isolated Linux sandbox. The committed workload runs 27,000 ordinary requests over 200 synthetic sessions with 256 KiB prepared inputs and 75% continuation suffixes, using the actual stream-selection/capture/request-encoding owners. This is a fixed-count owner workload, not a production Gateway or elapsed-hour soak.

Count, untraced timing/GC/loop, collected-object allocation, and forced-GC retention passes are separate. Concurrent pairs swap interleaved CPUs with synchronized warm/measurement starts and the shared production guard. Acceptance is zero fork-specific capture/publication/expiry work, identical parent request counts/encoded bytes, and no material regression under the predeclared absolute GC/loop rules. Retention counters are reported separately because external/ArrayBuffer accounting overlaps.

Metric Pair 1 baseline → candidate Pair 2 baseline → candidate Mean paired delta
Process CPU, µs/turn 198.62 → 30.52 196.75 → 31.32 −166.76 µs (−84.36%)
Main-thread CPU, µs/turn 165.22 → 28.07 172.54 → 28.83 −140.43 µs (−83.15%)
Sampled allocation, bytes/turn 300,740 → 69,580 300,623 → 69,522 −231,130 bytes (−76.87%)
Untraced total GC, ms/turn 0.012521 → 0.001637 0.013688 → 0.001618 −0.011476 ms (−87.55%)
Request p95, ms (27,000/side) 0.212850 → 0.104257 0.262484 → 0.105929 −0.132574 ms
Request p99, ms (27,000/side) 0.367983 → 0.211187 0.486971 → 0.214372 −0.214698 ms
Maximum single GC pause, ms 7.345226 → 0.224347 12.980896 → 0.224497 Both lower

Each measured side encoded exactly 1,771,857,720 bytes. Measured starts were simultaneous in both timing pairs and within 1 ms in the separate allocation/retention pairs. The 1,000-request count pass reduced fork-capture V8 serializations 2,000 → 0 and expiry timers 1,000 → 0. Remaining JSON/Blob construction is ordinary provider request encoding. No provider network calls or forks occur in this default-turn workload.

The separate forced-GC retention pass removed 50.05 MiB of ArrayBuffer backing storage in both pairs (52,477,322 → 32 bytes). External deltas were 319,744 → 72 bytes. JS heapUsed deltas were −4,250,216 → 232,808 and −4,243,360 → 232,784 bytes, so this does not prove a lower JS heapUsed delta. RSS growth was 384,827,392 → 11,534,336 and 447,549,440 → 3,145,728 bytes; allocator context only. These overlapping counters are not summed.

Untraced per-kind GC (count / total ms / maximum ms):

Pair / side Minor Major Incremental
1 baseline 59 / 46.775 / 2.557 86 / 269.067 / 7.345 86 / 22.212 / 0.371
1 candidate 422 / 44.200 / 0.224 0 / 0 / n/a 0 / 0 / n/a
2 baseline 176 / 146.834 / 2.985 50 / 205.240 / 12.981 50 / 17.494 / 4.514
2 candidate 422 / 43.699 / 0.224 0 / 0 / n/a 0 / 0 / n/a

Loop p95/p99/max was 12.886/14.909/15.630 → 10.297/10.330/10.494 ms in pair 1 and 14.074/22.561/29.835 → 10.379/10.461/10.519 ms in pair 2. Counts were 406/428 baseline and 75/77 candidate, so loop tails are context only. GC pause percentiles likewise lack paired sample counts. No promotion claim is made. No adverse total-GC or maximum-pause gate fired; rejection-control A/A pairs were therefore unnecessary.

The 27,000-request sequence equals an hour only at the chosen 450 requests/minute. It is not an elapsed-hour Gateway soak, a verified production route census, or whole-Gateway CPU/cache billing evidence. The sandbox was removed after results were collected. One initial barrier setup failed before measurement and produced no result; atomic publication fixed it before the valid passes. No measured pauses or windows were trimmed.

@clawsweeper

clawsweeper Bot commented Oct 24, 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 October 24, 2026 19:59
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-24T21:15:38.611169Z 412f17f 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling plugin: file-transfer size: XL labels Oct 24, 2026

@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: 180f769393

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

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR builds session-fork requests from live context or persisted history when requested instead of retaining snapshots during normal turns.

Example: Request “Review the parent” for the persisted session agent:research:telegram:direct:fork-transport-parent without a process-local parent snapshot.

  • Before: The fork fails with the missing prepared-parent error.
  • After: The supplied Gateway-runtime regression returns “fork-ok” while retaining the compaction summary and applying dmHistoryLimit: 1.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and the prior findings are repaired; supporting evidence reaches production owners and local transport, but does not qualify whole-Gateway performance or live provider cache effectiveness.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence exercises real reconstruction owners and local HTTP transport, including forbidden-reader and revocation cases, while performance measurements remain synthetic owner-level evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary model turns prepare optional fork snapshots, while completed sessions cannot be forked after those process-local snapshots disappear.
Reason: The maintainer-authored direction removes recurring work and enables persisted-history forks through existing owners, with the cache tradeoff stated explicitly.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored optimization removes eager fork work, repairs the prior findings, and has no remaining actionable defect found in the reviewed diff.

Priority: P2
Reviewed head: 412f17fe717fc1031f08fb8e434a87b9f020654c

Before merge

None.

Findings

None.

Agent review details

How this fits together

Plugin fork requests pass through Gateway session-read authorization, reconstruct the model context, and call a guarded provider transport that returns text and usage without executing tools.

flowchart TD
  A[Plugin fork request] --> B[Session read authority]
  B --> C[Live attempt or persisted transcript]
  C --> D[Context reconstruction]
  D --> E[Guarded provider transport]
  E --> F[Text and usage]
Loading

Technical review

Best possible solution:

Land the single reconstruction path with its existing authority guards and documented best-effort cache contract.

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

Current-main source confirms eager capture on ordinary requests and failure when no snapshot exists; the supplied regression records the persisted-history case failing on its baseline and passing after reconstruction.

Is this the best way to solve the issue?

Removing the separate snapshot store and reusing live-session, transcript, projection, and provider owners is a coherent complete solution; its weaker cache guarantee is explicitly accepted.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Prepared-request capture and cache parity changes intended behavior with a stated reason (164bd67: The original capability preserved exact parent request prefixes and cache affinity for background side questions.)
  • Snapshot retention, accounting, and expiry changes intended behavior with a stated reason (59f0420: The snapshot owner needed bounded detached data and cleanup; removing that owner also removes its retention machinery and obsolete probes.)
  • Normal-turn image filtering keeps the original intent (bb46b79: Merged runtime internalization carried the session image-blocking converter; this change preserves inline blocking and shares deferred-image suppression with fork reconstruction.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -24, Tests -275, Docs -6, Other -337. Total -642 across 34 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 22 608 632 -24
Tests 7 668 943 -275
Docs 2 67 73 -6
Config 0 0 0 0
Generated 0 0 0 0
Other 3 349 686 -337
Total 34 1692 2334 -642

Review metrics

Metric Value Why it matters
Runtime versus test LOC Runtime +608/-632; tests +668/-943 The change removes the snapshot owner and its obsolete tests while adding reconstruction and distinct transport, history, projection, and image-policy coverage.

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 author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This reduces normal-turn overhead and improves optional session forks without evidence of an urgent runtime outage.
  • merge-risk: 🚨 compatibility: The plugin-visible fork behavior changes from prepared-payload cache parity to reconstruction with best-effort cache reuse; the maintainer-authored PR explicitly accepts and documents this tradeoff.
  • 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-10-24T20:17:43.072Z sha 180f769393dc469d711bad850ddb7f25d7161ad6 :: needs changes before merge. :: [P2] Apply the configured history window before reconstructing completed forks | [P2] Omit inherited cache identity for independently rebuilt requests

Reviewed October 24, 2026, 5:31 PM ET / 21:31 UTC (Revision 2).

@steipete
steipete force-pushed the steipete/perf-micro-fork-pay-on-fork-20260919 branch from 180f769 to d4de242 Compare October 24, 2026 20:22

@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: d4de242c3f

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

Rebuild read-only fork requests from live session context or durable history. Remove eager request snapshots, publication copies, and expiry/budget machinery; preserve tool denial, current authority, and pending-call pairing. Existing history can be forked after restart, with best-effort cache reuse for reconstructed context.
@steipete
steipete force-pushed the steipete/perf-micro-fork-pay-on-fork-20260919 branch from d4de242 to 412f17f Compare October 24, 2026 21:15
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed all four review findings on 412f17fe717fc1031f08fb8e434a87b9f020654c:

  • Reconstructed forks omit parent cache identity at the final payload boundary, including native WebSockets, while leaving the parent's continuation untouched.
  • Completed forks use the owning channel history-window policy and preserve compaction summaries.
  • Live and cold forks replay the parent's recorded tool-result projections without advancing pruning state. Durable checkpoint replay respects compaction, branch, and reset boundaries.
  • Normal turns and forks share the image-policy converter, covering inline and deferred images before provider materialization.

Focused proof passed: embedded-runtime integration (4), fork transport (19), prompt-prefix stability (11), native WebSocket siblings (12), projection owner (12), cold persisted reconstruction (1), and import/source closure (22). Image-policy SDK coverage and the expanded scoped typecheck also passed. Independent subagent review (autoreview route unavailable) is clean. The PR body records paired CPU/allocation/GC measurements and the limits of the retention and mock-provider cache evidence.

The final-head failed shard contains only the two inherited plugin-lifecycle assertions documented in the PR: server-plugins.lifecycle.channels.test.ts:405 and server-plugins.lifecycle.test.ts:459, both expecting restartRequired: false after the upstream bundled-reload contract changed to true in #182403. The former matches scheduled main CI; the latter was reproduced on exact unchanged main source 4d49d348a5c21381bdca622d053faa3b4f98e3b4 (3 passed, 1 failed). Both files remain byte-identical from that baseline through this head. No unrelated tests were changed and no CI rerun was requested.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. 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 author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Oct 24, 2026
@steipete
steipete merged commit cb00966 into main Oct 24, 2026
183 of 188 checks passed
@steipete
steipete deleted the steipete/perf-micro-fork-pay-on-fork-20260919 branch October 24, 2026 21:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
Remove ordinary-turn fork capture, snapshot retention, expiry timers, and publication copies. Build tool-free fork requests from current live context or the persisted transcript only when requested, preserving current session authority, tool-result projections, image policy, history limits, and pending-call pairing.

Sessions with history can fork after cleanup or restart without first sending another normal message. Reconstructed forks omit parent cache identity; cache reuse remains best effort when transient request preparation cannot be reproduced.

Release-note context and paired performance evidence are recorded in PR openclaw#182844.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: file-transfer rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL 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