Skip to content

perf(agents): avoid duplicate active-computer preparation before turns - #185407

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-agent-turn-setup-20260919
Oct 27, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-agent-turn-setup-20260919

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Embedded agent turns refresh active-computer pairing context twice before the first model request, and slow system-prompt preparation lacks a useful subphase breakdown.

User Impact

Normal embedded turns do one less pairing refresh. Plugin harnesses retain their preparation boundary, and current-binding and admitted-run checks remain in place. Prompt construction order and bytes are preserved. Detailed system-prompt timings are available at the existing trace log level; no new configuration option or migration is required.

Why This Change Was Made

Prompt assembly already refreshes active-computer context immediately before consuming it. The earlier harness-selection refresh is redundant only for the built-in harness. This removes that duplicate work without adding a cache or weakening authorization.

The requested diagnostic detail is gated on trace logging: a separate incremental model showed that unconditional subphase bookkeeping would cost more than this small saving. The existing turn-start harness now supports 100 historical tool-call turns, two MCP servers with 40 tools each, and memory-core among 40 plugins. It verifies the history at the provider boundary and all 80 consumed MCP catalog entries. Usage is in the scripts' headers.

The setup audit found a dependency chain: tool-base feeds bundle/MCP preparation, bundle tools feed the policy/catalog, catalog capabilities and bootstrap feed the system prompt, and prepared tools/prompt plus the transcript lifecycle lock feed session runtime. Catalog registration has owned cleanup and permission refresh changes its facts. Bootstrap/bundle and some prompt reads may permit overlap, but the measured whole prompt was only 2.67 ms p50; this change does not introduce parallel failure/drain machinery without an expensive overlap to justify it. Auth publication, skill hydration, and transcript/session-manager changes remain with their owning lanes.

Evidence

The call-count regression failed on the baseline (built-in outer refresh expected 0, observed 1; plugin case passed), then passed with the change. Independent subagent review (autoreview route unavailable) is clean after addressing the measurement-harness findings. The configured autoreview route was rejected by its operator-config check; no operator configuration was changed.

The owner-work model uses a real synthetic 64-device pairing store, 2,000 operations per arm, AB/BA order, and separate untraced timing and allocation passes. It is not a full-turn benchmark. Two refreshes versus one reduced mean main-thread CPU from 15.61 to 8.32 µs/op and sampled allocation from 10,986 to 5,500 B/op. Both timing pairs had zero GC. A separate incremental model including the default-level trace guard retained the saving: 15.85 to 9.89 µs/op, 16,818 to 11,513 B/op. This is a small improvement, not an explanation for multi-second startup stalls.

Isolated Gateway phase distributions

Built dist baseline a7fe06b17a966a1a1a518f805f85c7cbfaf9fee5 with timing-only instrumentation versus the same source plus the refresh deletion. Both ran at trace level, where the final diagnostic gate leaves the measured instrumentation enabled. Each arm used 10,800 retained synthetic sessions, 40 plugins, 65 WebSockets, four concurrent mock-provider turns with real tool execution, sidebar/list/search churn, one warmup, and 40 measured warm turns. All 44 provider-history checks per arm and all four sessions' 80-tool catalog checks passed.

These sequential loaded-host runs are descriptive, not a causal estimate of whole-Gateway speedup. One-minute host load was 90.7→75.1 for baseline and 48.1→46.5 for candidate. The baseline fixture was reused after setup/proof-harness failures; the candidate used fresh equivalent inventory. No production Gateway was touched. The bounded duplicate-work fast-path protocol was used instead of a ten-minute multipair stress campaign. Memory-core was active, but search/embeddings were disabled; no active computer was attached to the Gateway fixture. Allocation was measured at the owner, not as a whole-Gateway rate.

Phase Baseline p50 / p95 (ms) Candidate p50 / p95 (ms)
Client ACK received → mock provider request received 7,265 / 13,959 1,445 / 1,771
Send → mock provider request received 7,706 / 16,704 1,556 / 2,115
Agent turn preparation 2,844 / 5,864 630 / 987
Skill snapshot hydration 575 / 2,127 93 / 168
Session runtime 781 / 2,524 198 / 352
History 259 / 1,467 64 / 167
Core/plugin tool preparation 397 / 1,128 10 / 200
Bundle/MCP tool preparation 3.75 / 38.11 3.55 / 9.00
Auth-profile resolution 183 / 1,218 27 / 62
System prompt 2.84 / 42.45 2.67 / 4.64

Each phase has 40 observations; p95 is descriptive below 200 samples. Nested phases overlap and cannot be summed. ACK timing pairs receipt timestamps for each turn, rather than subtracting percentiles; it is not a server ACK-sent/provider-write measurement. The warm p50 <1 s target remains unmet. Session/runtime, skill hydration, and loaded-host scheduling remain the large residual costs; this PR does not parallelize dependent preparation or modify their owners.

Gateway resource observation Baseline Candidate
Measured window 191.9 s 55.8 s
Main-thread CPU occupancy 33.1% 50.1%
GC seconds/minute 1.716 1.105
Event-loop p99 280.0 ms (n=3,605) 86.6 ms (n=2,197)
Client sessions.list p99 571.5 ms (n=2,715) 212.0 ms (n=658)
Server sessions.list handler p99 348.2 ms (n=2,715) 118.3 ms (n=658)
RSS before → after 2,700 → 2,956 MiB 3,320 → 3,165 MiB
Heap used before → after 711 → 1,085 MiB 758 → 808 MiB
Minor GC count / max pause 276 / 171.8 ms 143 / 50.4 ms
Major GC count / max pause 4 / 263.4 ms 4 / 80.2 ms

CPU occupancy reflects different throughput and polling work; RSS/heap are not retained-memory claims. Candidate list p99 and both major-GC distributions lack gate-sized samples. No adverse conclusion or large whole-Gateway speedup is claimed from these unequal-load arms.

Focused validation: 131 tests across harness selection, runtime prompt, attempt system prompt, and prompt-prefix stability; 29 closure tests; export-name collision guard; changed-file lint/format; git diff --check. The context-test extraction and trace gate were rechecked with their affected tests. No Testbox lease was used. PR CI supplies broad validation.

Production growth is the requested trace-only attribution and preservation of the plugin harness contract; no parallel fast path or cache was introduced. The oversized harness test file shrinks by moving its related context cases into a sibling module. Runtime source is +23 net lines: +3 preserve the separate plugin-harness preparation contract and +20 provide the requested trace-only phase attribution. The remainder is reproducible measurement tooling, documentation, and tests. The final integration onto e5aa4489f728 preserves the subscriber-visible reporting added by #185389, including its four retained 2,000-entry histories. The table above remains evidence from the earlier matched protocol, before that reporting change; it is not mixed with the integration smoke. The production change is unchanged by the rebase. The later #185368 conflict was only adjacent harness setup blocks; both are retained. A fresh integrated Gateway smoke passed one warm round (four measured turns plus four warmup turns): all eight provider requests replayed the 100-turn history, all four sessions consumed 80 MCP tools, and subscriber assistant/tool receipts were recorded. It used the already-built candidate runtime with the integrated source harness; this validates tooling integration, not a new performance comparison. The 14 turn-start report tests also passed. The first CI run found an incomplete logger mock in attempt-session.test.ts. Adding isEnabled fixed the runtime test failures, then the next CI run correctly rejected that changed partial mock. The final repair removes the unused logger mock entirely and prunes its single grandfathered exception with the canonical mock-export guard; no new baseline exception is added. All 23 tests in the file and the mock-export guard pass locally. The final rebase was conflict-free, and range-diff reports all three commits unchanged.

@clawsweeper

clawsweeper Bot commented Oct 27, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 27, 2026
@steipete
steipete marked this pull request as ready for review October 27, 2026 03:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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 ✅ Completed 2026-10-27T04:38:52.686637Z 82ee077 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The subscriber-visible session-start harness is merged in #185389. Use one tooling checkout containing that change against each already-built Gateway revision, with fresh output directories and the same sandbox mode:

node --import ./scripts/tsx.mjs scripts/perf/turn-start-phases.ts --entry /path/to/base/dist/entry.js --output .local/session-start-base --port 52000
node --import ./scripts/tsx.mjs scripts/perf/turn-start-phases.ts --entry /path/to/candidate/dist/entry.js --output .local/session-start-candidate --port 52010

For sandbox proof, add --sandbox-image openclaw-sandbox:bookworm-slim to both commands. Defaults: 10,800 sessions, 40 plugins, 65 clients, four concurrent turns, long retained histories, sidebar/list/search/history churn, and 40 fresh plus 40 warm samples. --cold-rounds 2 --warm-rounds 2 gives a shorter descriptive smoke run (eight samples per cohort).

summary.json now has run-correlated ACK/provider-request/subscriber-text/tool-start waterfalls and p50/p90 distributions. Existing diagnostics.scope names remain overlapping round/cohort aggregates, not invented per-run spans. Counterbalance revision order and use A/A controls before attributing adverse results. Details: docs/reference/session-start-measurement.md.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR removes duplicate active-computer preparation for embedded turns, adds trace-level prompt timings, and extends performance measurement tooling.

Example: An embedded turn prepares context for synthetic-computer.

  • Before: Harness dispatch and prompt preparation both refresh its pairing context.
  • After: Prompt preparation refreshes it once; plugin harnesses retain their dispatch refresh.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, narrowly owned runtime improvement with bounded performance claims; the changed logger fixture still fails a required ratchet.
Proof confidence 🐚 platinum hermit (4/6) Maintainer-authored proof exemption applies; supplied evidence records an isolated built Gateway exercising prompt phases, retained history, and MCP catalogs, alongside a separate synthetic pairing-owner comparison.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Embedded turns repeat pairing preparation before reaching the model, and slow prompt preparation lacks useful phase attribution.
Reason: The maintainer-authored direction removes measured duplicate work through existing owners; added flags affect measurement scripts rather than runtime configuration.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the optimization is useful and the earlier logger failure is fixed, but the updated mock now fails the exact-head mock-export ratchet.

Priority: P2
Reviewed head: 970c8f52bed49082e9e72d15fa7ce5465d9f985b

Before merge

  • Preserve real exports in the updated logger mock (P2) - Adding isEnabled fixes the earlier runtime failure but changes this closed mock factory's fingerprint. The mock-export ratchet hashes factory tokens, while config/test-mock-exports-baseline.txt still allows only the previous factory. This replacement has neither real-module pass-through nor an adjacent mock-isolation explanation, so it is rejected as new mock debt; exact-head checks-fast-baseline-ratchets reports mock-exports failed. Preserve the real module and logger members while overriding the fixture behavior, or explain necessary isolation, then prune the obsolete baseline entry and run the affected test and ratchet.

Findings

  • [P2] Preserve real exports in the updated logger mock — src/agents/embedded-agent-runner/run/attempt-session.test.ts:84
Agent review details

How this fits together

Harness selection dispatches admitted agent turns; prompt preparation combines requester-scoped computer context, tools, memory, and runtime facts into the model request.

flowchart TD
  A[Admitted agent turn] --> B[Harness selection]
  B --> C[Built-in prompt preparation]
  B --> D[Plugin context preparation]
  C --> E[Current requester computer context]
  D --> E
  E --> F[Model request]
Loading

Technical review

Best possible solution:

Retain the runtime optimization and repair the logger mock through export preservation or justified isolation, pruning its obsolete baseline entry.

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

Source confirms duplicate preparation on main, and exact-head CI plus the fingerprinting implementation establish the changed-mock failure; no target code was executed during review.

Is this the best way to solve the issue?

Skipping the redundant built-in refresh uses the existing consuming owner without caching, while trace-only timing avoids unconditional instrumentation cost.

Full review comments:

  • [P2] Preserve real exports in the updated logger mock — src/agents/embedded-agent-runner/run/attempt-session.test.ts:84
    Adding isEnabled fixes the earlier runtime failure but changes this closed mock factory's fingerprint. The mock-export ratchet hashes factory tokens, while config/test-mock-exports-baseline.txt still allows only the previous factory. This replacement has neither real-module pass-through nor an adjacent mock-isolation explanation, so it is rejected as new mock debt; exact-head checks-fast-baseline-ratchets reports mock-exports failed. Preserve the real module and logger members while overriding the fixture behavior, or explain necessary isolation, then prune the obsolete baseline entry and run the affected test and ratchet.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Active-computer preparation keeps the original intent (05117d9: Worker-backed pairing reads required asynchronous preparation before synchronous context projection; requester scoping followed in fe609d4.)
  • Prompt context ordering and TTS preparation keeps the original intent (fix: apply workspace permission changes to active runs #132407: Permission refresh owns prepared prompt context; the patch preserves sequential memory/watch preparation, currentness assertions, and TTS preference precedence.)
  • Routine trace overhead keeps the original intent (refactor(agents): remove routine trace bookkeeping #174836: Routine trace projections were removed to reduce work; the added subphase observations are explicitly gated on trace logging.)
  • Turn-start measurement keeps the original intent (test(perf): measure subscriber-visible session starts #185389: Measure subscriber-visible starts with retained histories and run-correlated receipts; the introduced diff preserves those measurements while adding richer context.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/embedded-agent-runner/run/attempt-session.test.ts --maxWorkers=1
  • pnpm check:test-mock-exports --base 1891d83
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4c5e755 adds src/agents/harness/selection.ts:612 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4c5e755c3f8e; files: src/agents/harness/selection.ts)
  • Wesley: Raw commit bae5127 adds src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts:293 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: bae5127ea3ae; files: src/agents/embedded-agent-runner/run/attempt-system-prompt-prepare.ts)

PR surface

Source +114, Tests -41, Docs +8, Other +447. Total +528 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 137 23 +114
Tests 2 3 44 -41
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 3 526 79 +447
Total 9 674 146 +528

Review metrics

Metric Value Why it matters
Production versus tests Production +46/-23; tests +94/-44 Runtime growth provides trace-only attribution and preserves plugin preparation; test growth includes a context-case extraction and the focused preparation regression.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A small turn-preparation improvement has a focused, nonurgent CI repair.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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-27T04:06:21.068Z sha dc159491328f0c31590b9b356f9158f44b520932 :: needs changes before merge. :: [P2] Preserve isEnabled in the session-preparation logger mock

Reviewed October 27, 2026, 12:29 AM ET / 04:29 UTC (Revision 2).

@steipete
steipete force-pushed the steipete/perf-micro-agent-turn-setup-20260919 branch 2 times, most recently from b158a2d to 970c8f5 Compare October 27, 2026 04:14
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed both items on 970c8f52bed49082e9e72d15fa7ce5465d9f985b: the session-preparation logger fixture now supplies isEnabled (all 23 tests pass locally, and the formerly failing CI shard is green), and the rebase preserves #185389's subscriber receipts, waterfalls, and retained long histories alongside rich-context mode. A fresh integration run verified all eight historical-context requests, all four consumed 80-tool MCP catalogs, and subscriber assistant/tool receipts. The PR body keeps the earlier matched performance protocol separate from this integration proof. Independent review is clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 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. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 27, 2026
Avoid the duplicate early refresh for the embedded harness while preserving plugin harness preparation and live authority checks. Add trace-level system-prompt subphases and rich-history turn-start measurement with MCP catalog verification.
@steipete
steipete force-pushed the steipete/perf-micro-agent-turn-setup-20260919 branch from 970c8f5 to 82ee077 Compare October 27, 2026 04:36
@steipete

Copy link
Copy Markdown
Contributor Author

Resolved the remaining mock-export finding on 82ee077607b1247d43c31cf4ce8f47a02e5567fb by deleting the unused logger mock entirely and pruning its single obsolete baseline entry with the canonical guard. This preserves the real logger without adding an isolation exception. All 23 focused tests pass locally; both the session-preparation shard and baseline-ratchet job are now green on this exact head. Independent review and the final-head Codex review are clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 31ec9d8 into main Oct 27, 2026
119 checks passed
@steipete
steipete deleted the steipete/perf-micro-agent-turn-setup-20260919 branch October 27, 2026 04:50
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
openclaw#185407)

* perf(agents): prepare active computer context at its consuming boundary

Avoid the duplicate early refresh for the embedded harness while preserving plugin harness preparation and live authority checks. Add trace-level system-prompt subphases and rich-history turn-start measurement with MCP catalog verification.

* test(agents): complete the prompt preparation logger fixture

* test(agents): remove unused prompt preparation logger mock
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant