Skip to content

improve: allocate less while preparing subagent context - #203039

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-subagent-read-snapshot-prompt-prepare-20260919
Nov 21, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-subagent-read-snapshot-prompt-prepare-20260919

Conversation

@steipete

@steipete steipete commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Preparing a turn's subagent context restores retained payloads for durable registry rows and then restores their live replacements again. The first restored object is immediately discarded, adding allocation and CPU work to every affected turn.

User Impact

Subagent prompt content stays identical while registry reads allocate less. There are no configuration, schema, retention, permissions, or API changes.

Why This Change Was Made

The existing registry read owner now finishes merging durable facts, publications, and live overrides before restoring the final selected rows. This removes duplicate restoration while retaining live ownership vetoes and payload provenance. Production LOC is net zero (9 added, 9 removed); regression coverage adds 18 lines and the reproducible synthetic workload is 123 lines. No cache is added.

The turn-context renderer needs task text, pending results, and yielded-child dependencies, so a session-key-only read cannot preserve its output. This change keeps that read contract and removes the redundant work inside its owner.

Evidence

The prepared-read regression fails on the original code with two payload restorations for one final live row and passes after the fix with one. Full task text and current live metadata are preserved. All 104 focused tests pass across registry reads, refresh/accounting, prompt rendering, memory, and prompt-prefix stability (135.42 seconds wrapper wall).

Measurement acceptance was recorded before the campaign: identical prompt bytes, lower allocation beyond A/A variation, fewer restorations, and no 20% or greater wall/CPU regression. The committed workload exercises the actual turn-context renderer with 700 synthetic SQLite rows, a 100-level requester chain, 60 suspended results, 4 KiB tasks, and 8 KiB result payloads. Five serial A1/A2/B rounds reverse arm order on alternating rounds; each sample uses 50 warm timing calls and 20 allocation calls. Setup/imports are excluded. Main-thread sampled allocation includes objects collected by minor and major GC. The affected path does not scan workspaces or agent-session databases. This is owner-level synthetic proof, not whole-Gateway throughput.

Per preparation, median / p95 Baseline A1 Baseline A2 Candidate
Sampled allocation, bytes 25,312,542 / 25,359,435 25,154,320 / 25,393,645 23,203,560 / 23,217,543
Main-thread CPU, ms 14.487 / 21.197 15.587 / 16.729 13.988 / 17.060
Owner wall, ms 34.865 / 115.092 36.716 / 52.656 37.114 / 56.260

Allocation falls 7.96% against the combined baseline median (25,209,802 → 23,203,560 bytes). A/A allocation medians differ 0.63%; all candidate allocation samples are below every baseline sample. Combined main-thread CPU medians are 14.997 → 13.988 ms; wall medians are 36.150 → 37.114 ms (+2.7%). Host load ranged 14.23–34.61, and timing spread is substantial: no latency or statistically established CPU improvement is claimed. No median/p95 metric crosses the predeclared 20% regression threshold.

First-read observations are separate: A1/A2/B wall medians 476.5/509.5/535.0 ms and main-thread CPU 28.367/32.805/32.332 ms. These include lazy owner setup and are noisy observations, not a cold-start improvement claim. Across all 15 samples, the prompt SHA-256 is 4e22de8c9c6a51a2ec0c75695f08c297c2248c24795885cd322a380d3dcb7bae.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/subagent-prompt-snapshot.ts <arm> [cpu-profile-path] in baseline and candidate checkouts, using the same workload file. Five A1/A2/B rounds, reversed on alternate rounds; Node 26.12.1 on macOS. Allocation excludes worker heaps; main-thread CPU excludes worker CPU. Worker/read scope is unchanged.

Independent Codex autoreview of the full local candidate against 4c7701017b653, including snapshot/memory/payload owner context, is scoped-clean through P2 with no actionable findings. pnpm check:changed --staged ran all selected gates. Core and test typechecks, production lint, format, boundary guards and import cycles passed. Benchmark type/lint issues were corrected and both affected checks pass. The remaining dead-export findings are inherited CLI-update issues introduced by b229b2664537d / #200578: exposeGlobalPackageThroughRelease, resolveGitReleaseCheckout, and writeGitUpdateResultFixture. The same three findings reproduce with pnpm deadcode:exports on the exact main parent 4c7701017b653; this is a main validation regression, not ignored noise. Final Codex autoreview after the benchmark-only correction is scoped-clean through P2. No Control UI import reaches the changed production owner.

Exact-head CI run 44892652133, attempt 2 passed. Attempt 1 hit the 60-second no-output watchdog before any assertion result in server-runtime-services.correlated-recovery.test.ts; all six tests then passed locally with the same limit. One diagnosed startup-stall retry of failed jobs passed on the unchanged head, with no timeout or test changes. ClawSweeper final-head review reports zero findings and no open items.

Merge durable, published, and live registry rows before restoring only the final selected owners. Preserve prompt bytes and live lifecycle precedence while removing duplicate payload copies from turn-context preparation.
@clawsweeper

clawsweeper Bot commented Nov 21, 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 scripts Repository scripts agents Agent runtime and tooling size: S labels Nov 21, 2026
@steipete
steipete marked this pull request as ready for review November 21, 2026 10:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T10:07:21.048148Z f1bf598 Draft marked ready
ℹ️ 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.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review the final selected-row hydration order, live ownership vetoes, and unchanged prompt output on f1bf598. Focused tests and independent Codex autoreview are clean; synthetic A/A/candidate measurements are in the PR body.

@clawsweeper

clawsweeper Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 21, 2026
@clawsweeper

clawsweeper Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR restores subagent payloads after merging durable, published, and live rows, avoiding restoration of rows that are immediately replaced.

Example: The retained run has a 1,400-character task and a compact live replacement labeled "current live label".

  • Before: The prepared read restores two objects before returning the full task with the live label.
  • After: The prepared read restores only the surviving object and returns the same task and live label.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-consistent, with useful reported measurements and regression coverage; performance evidence remains an in-process synthetic workload.
Proof confidence 🦐 gold shrimp (3/6) This internal performance change preserves user-visible semantics; the supplied evidence exercises the production renderer in a synthetic process and supports allocation and prompt-equality claims, without establishing whole-Gateway throughput.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Preparing context performs avoidable allocation as retained subagent records accumulate.
Reason: The maintainer-authored direction removes demonstrated redundant work with a small change and reports an allocation improvement beyond baseline variation.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR removes redundant payload restoration while preserving selection, live ownership vetoes, and payload provenance; no actionable correctness or security findings were found.

Priority: P2
Reviewed head: f1bf5987f2e44f96c35bdb1a341b83dc1ed8978f

Before merge

None.

Findings

None.

Agent review details

How this fits together

The registry read owner combines persisted payloads with current publications and live lifecycle facts, then supplies selected full records to prompt rendering, registration, and descendant readers.

flowchart TD
  A[Durable registry rows] --> D[Merge selected records]
  B[Committed publications] --> D
  C[Live registry overrides] --> D
  D --> E[Restore surviving payloads]
  E --> F[Prepared read consumers]
  F --> G[Subagent prompt context]
Loading

Technical review

Best possible solution:

Keep hydration in the existing registry read owner and apply it once to each surviving selected record.

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

The original merge code restores compact durable records before restoring their live replacements, making duplicate work source-reproducible; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change removes work at its existing owner without adding state or changing selection contracts, and the focused regression protects both restoration count and returned content.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Selected full-record payload restoration keeps the original intent (f4f4b19: Release settled payload text from resident memory while restoring durable text for selected full reads and preserving lifecycle ownership.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit ed68038 adds src/agents/subagents/registry/subagent-registry-read-cache.ts:465 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ed68038bc859; files: src/agents/subagents/registry/subagent-registry-read-cache.ts)

PR surface

Source 0, Tests +18, Other +123. Total +141 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 9 9 0
Tests 1 18 0 +18
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 123 0 +123
Total 3 150 9 +141

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 P2: This is a bounded allocation improvement on subagent context preparation with unchanged intended output.
  • 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.

Label justifications:

  • P2: This is a bounded allocation improvement on subagent context preparation with unchanged intended output.
  • 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.

Reviewed November 21, 2026, 5:10 AM ET / 10:10 UTC.

@steipete
steipete merged commit 966eda4 into main Nov 21, 2026
301 of 308 checks passed
@steipete
steipete deleted the steipete/perf-micro-subagent-read-snapshot-prompt-prepare-20260919 branch November 21, 2026 10:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 21, 2026
…3044

* origin/main:
  fix(ci): decouple boundary fixture from timing inventory (#203026)
  fix(ci): shard capable compatibility UI targets (#203042)
  perf(agents): restore selected subagent payloads once (#203039)
  fix: keep standalone context from completing QA tool steps
  perf(sessions): reuse sealed ownership for context projections (#203040)
  refactor(hooks): separate event predicates from hook registry (#203017)
  fix(ci): align update export audits with their consumers (#203030)
  fix: keep cold baseline checks within the existing heap limit
vincentkoc added a commit that referenced this pull request Nov 21, 2026
* feat: open shared sessions in their source Control UI

* feat: open shared sessions in their source Control UI

OpenClaw-Publication: a3826b6b-5899-8ff2-a1b5-84961c64219f

* Merge remote-tracking branch 'origin/main' into land/open-original-203044

* origin/main:
  fix(ci): decouple boundary fixture from timing inventory (#203026)
  fix(ci): shard capable compatibility UI targets (#203042)
  perf(agents): restore selected subagent payloads once (#203039)
  fix: keep standalone context from completing QA tool steps
  perf(sessions): reuse sealed ownership for context projections (#203040)
  refactor(hooks): separate event predicates from hook registry (#203017)
  fix(ci): align update export audits with their consumers (#203030)
  fix: keep cold baseline checks within the existing heap limit

* fix(session-share): accept the runtime config snapshot in the source link resolver

The stored-session link resolver took a mutable config, so the plugin's readonly
runtime snapshot failed production and test typechecks. Accept the snapshot type.

Document the real Open original setup: allow the link command on the receiver
Gateway, set the source Control UI origin, reinstall the source node with all
three commands, then approve the widened surface. Move the section ahead of
Security boundary and add a troubleshooting entry.

Assert through the Gateway catalog list that a provider-supplied link survives
streamed and final rows, and drop the menu unit test the browser fixture covers.

* Merge remote-tracking branch 'origin/main' into land/open-original-203044

* origin/main:
  refactor(test): remove duplicate token startup wait case (#203087)
  fix: keep Plugin SDK declarations within the build limit
  fix(ci): remove unused hook type exports (#203074)
  fix(test): exercise the sign-in callback path guard (#203075)
  refactor(tts): separate caption eligibility from text helpers (#203068)
  test: reuse worker preload options (#203058)
  refactor(test): share Bun native-policy test launcher (#203064)
  fix(cron): a chat-created automation's failure notice reaches that chat (#203056)
  refactor(test): remove duplicate claw origin rejection case (#203067)
  refactor(channels): move chunk-mode lookup to streaming readers (#203047)
  refactor: separate skill queries from workspace discovery (#203045)
  fix: resume new chat turns in retained tasks after a restart
  refactor: separate usage pricing preparation from formatting (#203043)
  fix: avoid repeated filesystem probes before agent turns (#203057)
  perf(agents): preserve sealed history during endpoint compaction (#203037)
  fix(test): give deferred identity fixtures read scope (#203053)
  refactor(test): remove redundant channel catalog facade (#203052)
  refactor(cli): isolate daemon port presentation (#203020)
  refactor(cron): isolate CLI input parsing (#203031)

* chore(plugin-sdk): record the approved session-discussion surface growth

Open original adds two exports to openclaw/plugin-sdk/session-discussion: the
stored-session Control UI path resolver and the session path parser. Raise the
public export and callable budgets by two for them.

Use neutral fixtures for the rejected-origin and rejected-query URL tests so the
fixtures do not resemble credentials; the same rejections are covered.

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 22, 2026
Merge durable, published, and live registry rows before restoring only the final selected owners. Preserve prompt bytes and live lifecycle precedence while removing duplicate payload copies from turn-context preparation.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 22, 2026
* feat: open shared sessions in their source Control UI

* feat: open shared sessions in their source Control UI

OpenClaw-Publication: a3826b6b-5899-8ff2-a1b5-84961c64219f

* Merge remote-tracking branch 'origin/main' into land/open-original-203044

* origin/main:
  fix(ci): decouple boundary fixture from timing inventory (openclaw#203026)
  fix(ci): shard capable compatibility UI targets (openclaw#203042)
  perf(agents): restore selected subagent payloads once (openclaw#203039)
  fix: keep standalone context from completing QA tool steps
  perf(sessions): reuse sealed ownership for context projections (openclaw#203040)
  refactor(hooks): separate event predicates from hook registry (openclaw#203017)
  fix(ci): align update export audits with their consumers (openclaw#203030)
  fix: keep cold baseline checks within the existing heap limit

* fix(session-share): accept the runtime config snapshot in the source link resolver

The stored-session link resolver took a mutable config, so the plugin's readonly
runtime snapshot failed production and test typechecks. Accept the snapshot type.

Document the real Open original setup: allow the link command on the receiver
Gateway, set the source Control UI origin, reinstall the source node with all
three commands, then approve the widened surface. Move the section ahead of
Security boundary and add a troubleshooting entry.

Assert through the Gateway catalog list that a provider-supplied link survives
streamed and final rows, and drop the menu unit test the browser fixture covers.

* Merge remote-tracking branch 'origin/main' into land/open-original-203044

* origin/main:
  refactor(test): remove duplicate token startup wait case (openclaw#203087)
  fix: keep Plugin SDK declarations within the build limit
  fix(ci): remove unused hook type exports (openclaw#203074)
  fix(test): exercise the sign-in callback path guard (openclaw#203075)
  refactor(tts): separate caption eligibility from text helpers (openclaw#203068)
  test: reuse worker preload options (openclaw#203058)
  refactor(test): share Bun native-policy test launcher (openclaw#203064)
  fix(cron): a chat-created automation's failure notice reaches that chat (openclaw#203056)
  refactor(test): remove duplicate claw origin rejection case (openclaw#203067)
  refactor(channels): move chunk-mode lookup to streaming readers (openclaw#203047)
  refactor: separate skill queries from workspace discovery (openclaw#203045)
  fix: resume new chat turns in retained tasks after a restart
  refactor: separate usage pricing preparation from formatting (openclaw#203043)
  fix: avoid repeated filesystem probes before agent turns (openclaw#203057)
  perf(agents): preserve sealed history during endpoint compaction (openclaw#203037)
  fix(test): give deferred identity fixtures read scope (openclaw#203053)
  refactor(test): remove redundant channel catalog facade (openclaw#203052)
  refactor(cli): isolate daemon port presentation (openclaw#203020)
  refactor(cron): isolate CLI input parsing (openclaw#203031)

* chore(plugin-sdk): record the approved session-discussion surface growth

Open original adds two exports to openclaw/plugin-sdk/session-discussion: the
stored-session Control UI path resolver and the session path parser. Raise the
public export and callable budgets by two for them.

Use neutral fixtures for the rejected-origin and rejected-query URL tests so the
fixtures do not resemble credentials; the same rejections are covered.

Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: vincentkoc <[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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: S 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