Skip to content

perf(agents): release completed parents retained by fork replay - #173535

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-fork-replay-retention-20260919
Oct 15, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-fork-replay-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Prepared native-session fork snapshots kept the disposed parent AgentSession and SessionManager alive alongside their intentionally retained replay prefix. Large conversations therefore retained an extra copy of their history until snapshot eviction or cleanup.

User Impact

Completed parents can now be garbage-collected while later read-only forks still replay the prepared request. No configuration, schema, expiry, byte-budget, or run-registration policy changes.

Why This Change Was Made

The SDK transport was created inside createAgentSession, captured its full options, and shared the session factory's closure scope. A private transport factory now captures only the model registry, settings manager, and thinking flag. Per-request credential resolution, dynamic retry/attribution settings, and runtime binding remain intact.

The old inline construction is removed. Production delta: +12 lines (39 added / 27 removed); the extra private function/type boundary is necessary to isolate the retained closure rather than clear useful replay data. Test delta: +74 lines. The simplification pass found no second policy or compatibility path to retain.

Evidence

Isolated Linux sandbox, synthetic data, exact base 2aca37525ff0804790c29d9ab6fea1bb9e5f700e, real SDK session construction and native stream selection, fixture provider, forced GC. Six completed sessions with 8 MiB histories:

Retained after completion, relative to explicit snapshot cleanup Before After
Heap + replay buffers, six runs 96.18 MiB 48.02 MiB
Per completed oversized run 16.03 MiB 8.00 MiB
Live disposed AgentSession / SessionManager objects 12 0
Successful later fork yes yes

The fix removes approximately 8.03 MiB per run (50% of measured retention). The remaining 8 MiB per run is the intended prepared prefix. A separate twelve-run probe with 16.23 MiB prefixes stayed at 16.23 MiB for one session and plateaued at 48.69 MiB across distinct sessions under the existing 64 MiB budget; replacement, expiry, and cleanup released old data.

Registration investigation: the registration owner is a WeakMap. Twelve runs each through completion, abort, explicit finalizing-owner release, and lifecycle rotation left zero live handles, registrations, or 8 MiB SessionManagers. No registration-owner change was needed.

  • New forced-GC regression fails on the original SDK implementation (2 retained objects, expected 0) and passes with this change, including a later fork after parent collection.
  • sdk.test.ts: 23 passed; latest Vitest 7.01 s / wrapper 32.97 s (test execution about 1.3 s).
  • session-fork.test.ts: 28 passed.
  • runs.test.ts and runs.generation.test.ts: 33 passed.
  • SDK sibling files sdk.auth-migration.test.ts, sdk.metadata-admission.test.ts, and sdk.tool-outcomes.test.ts: 30 passed (single worker, 51.11 s wrapper).
  • Changed-file core lint, formatting, and git diff --check: passed. An initial root-config lint invocation triggered declaration preparation and was stopped; the successful check used the core config with preparation disabled.
  • Independent subagent review (autoreview route unavailable): scoped-clean, no actionable P0/P1/P2 findings. The helper rejected a provider mismatch; operator configuration was unchanged.
  • Initial PR CI caught a type mismatch in the new regression (AgentMessage[] versus provider Message[]). The test now uses the canonical convertToLlm boundary; focused tests/lint and independent review passed again. Production code and measurements are unchanged.
  • No Testbox/Crabbox lease. Broad checks delegated to PR CI.

Limits: this measures the real session/fork ownership boundary with a synthetic provider, not a live provider call or the complete production Gateway heap. It does not attribute all idle-process memory to this defect.

Final CI and inherited-failure attribution

Corrected head 5c04b86650d992e09e649022216552da1fcc268d, CI run 38821588178, attempt 1: all selected test lanes, build, production/test types, lint, docs, guards, and security-fast passed. The only root failure is checks-fast-baseline-ratchets; openclaw/ci-gate fails downstream.

The failure table labels it new because the older scheduled main job passed. Independent reproduction on the actual unchanged CI main parent proves it inherited:

  • Main parent 68166d8e61e94ce46aeeed9fe439e82e7da7114f: node --import ./scripts/tsx.mjs scripts/check-test-mock-exports.mts --base 68166d8e61e94ce46aeeed9fe439e82e7da7114f exits 1.
  • Exact CI merge e9a7a10816e4d7b27d44af31f13aca184853db3f (ordered parents: that main parent, corrected PR head): same command exits 1 with the identical entry below.
  • Both isolated Linux runs use the same existing sandbox with CPU/memory/priority limits; no production state, broad test suite, or CI rerun.
  • The failing test, baseline, ratchet implementation and its scanner/resolver inputs have identical Git objects between the main parent and tested merge. The merge adds only this PR's three files.
Shrink config/test-mock-exports-baseline.txt (run with --prune):
  ["extensions/codex/src/app-server/turn-router.mcp-app.test.ts","./protocol-validators.js","179c97d5d976dacea55cb1994ace0d7af200608a224466b9e57daa260410890f",1]

Landing under the authorized inherited-failure exception; the unrelated baseline is not changed in this PR.

Native scripts/pr merge-run could not start because installed tsx 4.23.12 differs from the trusted tooling requirement 4.23.15. Shared dependencies were left untouched; the operator-authorized exact-head GitHub API fallback is used for this inherited-only landing.

@clawsweeper

clawsweeper Bot commented Oct 15, 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 15, 2026 22:51
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling plugin: file-transfer size: S labels Oct 15, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T22:54:04.871650Z ab5f6ab 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

Inherited-failure landing evidence for reviewed head 5c04b86650d992e09e649022216552da1fcc268d:

CI run 38821588178 passed all selected tests, build, types, lint, docs, guards, and security checks. Its sole root failure is checks-fast-baseline-ratchets: the stale turn-router.mcp-app.test.ts / ./protocol-validators.js entry in config/test-mock-exports-baseline.txt.

The same check-test-mock-exports.mts --base 68166d8e61e94ce46aeeed9fe439e82e7da7114f command exits 1 with the identical entry on unchanged main parent 68166d8e61e94ce46aeeed9fe439e82e7da7114f and tested merge e9a7a10816e4d7b27d44af31f13aca184853db3f, in the isolated Linux sandbox. Relevant source objects are identical. The scheduled-main classifier used an older passing run; actual-parent reproduction establishes inheritance. Full output and scope are recorded in the PR body.

Independent review is clean; focused SDK/fork/run tests pass, including 30 SDK sibling tests. No CI rerun or unrelated baseline edit. Native merge tooling could not start due its installed dependency mismatch; using the authorized exact-head API fallback under the inherited-failure exception.

@steipete
steipete merged commit 6ef7f2a into main Oct 15, 2026
131 of 136 checks passed
@steipete
steipete deleted the steipete/perf-micro-fork-replay-retention-20260919 branch October 15, 2026 23:23
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR isolates the replay transport closure so retained fork snapshots can release completed parent sessions and transcript managers.

Example: Six completed sessions each retain an 8 MiB prepared replay prefix in the reported isolated probe.

  • Before: Retained memory was 96.18 MiB, with 12 disposed session and manager objects still alive.
  • After: Retained memory was 48.02 MiB, with zero disposed parent objects alive and later replay still succeeding.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, source-supported repair with meaningful in-process retention coverage; shipped-entry-point proof and attribution of the failing CI check remain unavailable.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its supplied Linux GC measurements exercise the real SDK and fork owners with a fixture provider, not a live Gateway or provider.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Fork-enabled conversations retain completed parent histories in addition to their intentionally retained request prefixes.
Reason: The reported memory reduction is substantial, the repair is narrow, and the maintainer-authored direction preserves the existing fork contract.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a concrete retention defect with a focused change and meaningful GC coverage; no introduced correctness or security defect was found.

Priority: P2
Reviewed head: 5c04b86650d992e09e649022216552da1fcc268d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence exercises synthetic-provider session construction and replay, rather than a shipped Gateway heap scenario.
Agent review details

How this fits together

The session SDK assembles the agent's provider stream; background fork snapshots retain that stream and prepared request data for later read-only inference.

flowchart LR
  A[Session SDK] --> B[Isolated stream factory]
  B --> C[Provider runtime]
  D[Fork snapshot] --> B
  D --> E[Prepared request prefix]
  F[Background side question] --> D
Loading

Technical review

Best possible solution:

Retain the isolated transport factory and GC regression while preserving the existing replay prefix, runtime binding, and cleanup policies.

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

Source shows snapshots retaining the inline SDK closure and its options; the supplied synthetic-provider probe and regression report collection failure before the fix and success afterward, but this review executed no target code.

Is this the best way to solve the issue?

The extraction fixes the retaining closure at its producer, preserves dynamic credential and settings resolution, and avoids weakening useful replay retention.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Lifecycle-owned provider streaming keeps the original intent (cc57514: Give each model registry its own provider runtime rather than relying on process-global routing.)
  • Explicit thinking selection keeps the original intent (218baa9: Carry explicit reasoning selection into provider requests.)
  • Post-completion fork replay keeps the original intent (164bd67: Allow background side questions to reuse a parent's prepared context after completion.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced diff extracts the existing request logic into a private factory, preserves per-request auth and settings reads, and binds the same lifecycle runtime before returning the stream. (src/agents/sessions/sdk.ts:153, 5c04b86650d9)
  • Retention owner and current main: Snapshots retain streamFn for replay; current main still constructs that function inside createAgentSession with a reference to its full options. The SDK file has no difference between the pinned merge base and fetched main. (src/agents/embedded-agent-runner/session-fork.ts:186, dbc41ff76ba1)
  • Independent retention contract: The regression constructs real SDK sessions, captures native replay, disposes parents, forces GC with an unowned control, checks weak references, and then successfully invokes a later fork; the body reports failure on the original implementation and passage after extraction. (src/agents/sessions/sdk.test.ts:196, 5c04b86650d9)
  • Original fork contract: The merged implementation at feat(plugins): fork a session's live context for background side questions #170146 intentionally supports forks after parent completion; this PR preserves that capability while removing unnecessary parent retention. Public docs: docs/plugins/sdk-runtime.md. (docs/plugins/sdk-runtime.md:120, 164bd6756af1)
  • CI remains unresolved: Exact-head baseline ratchets report mock-exports failed, and the aggregate gate is red. Annotations do not identify the offending factory; log retrieval redirects to a blocked Azure host, so neither diff-caused nor inherited attribution is established. (5c04b86650d9)
  • Repository policy and inspection limits: Read the complete root, agent, and docs instructions and applied ownership, performance, and test-value guidance. No maintainer-notes directory exists. Some historical fork blobs are unavailable locally; commit history, current source, and merged PR bodies establish the relevant intent. The checkout remains clean. (AGENTS.md:1, 5c04b86650d9)

Likely related people:

  • Ayaan Zaidi: Raw commit 164bd67 adds docs/plugins/sdk-runtime.md:112 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 164bd6756af1; files: docs/plugins/sdk-runtime.md)

PR surface

Source +12, Tests +74, Docs +2. Total +88 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 39 27 +12
Tests 1 74 0 +74
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 116 28 +88

Review metrics

Metric Value Why it matters
Production versus test growth Production +12 net lines; tests +74 lines. The private factory creates the necessary closure boundary; the regression protects parent collection and continued replay without adding a production test seam.

Labels

Label changes:

  • add P2: Unnecessary completed-session retention increases memory use for fork-enabled conversations, without evidence of an urgent outage.
  • 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: Unnecessary completed-session retention increases memory use for fork-enabled conversations, without evidence of an urgent outage.
  • 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 October 15, 2026, 7:23 PM ET / 23:23 UTC.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…claw#173535)

* perf(agents): release completed parents retained by fork replay

* test(agents): convert fork replay fixture messages at provider boundary
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 plugin: file-transfer size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant