Skip to content

fix(agents): release prompt history after completed runs - #176804

Merged
steipete merged 5 commits into
mainfrom
steipete/perf-micro-attempt-continuation-retention-20260919
Oct 19, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/perf-micro-attempt-continuation-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes heap growth when completed tool-heavy agent runs leave their full recovery prompts reachable through retained attempt callbacks and copied harness parameters.

User Impact

Completed runs release temporary recovery history. Active retries preserve their accumulated messages, and accepted transcript writes finish with the original run's prepared message, visibility, attribution, and callbacks. No configuration, schema, stored-transcript, or prompt-prefix change is required.

Why This Change Was Made

The logical run now releases the borrowed prompt/message payload when replacing a continuation and at disposal, including copies of its envelope retained by outer harness layers. Transcript preparation captures only needed fields; cache-touch completion captures only its timestamp.

A reused session manager captures one run context before append admission. That context owns transformations, callbacks, prepared user state, run ID, and persistence mode. Its cleanup runs after the actual transcript drain, including drains that outlast the bounded teardown wait. Old cleanup and old mode setters cannot mutate a newer run. Callback retirement preserves visibility and attribution needed for synthetic-result cleanup.

The change removes whole-attempt closure capture, shared mutable run policy, the positional rebinding API, and the callback-generation counter. Runtime code grows by 89 lines to preserve the accepted-write and retry-history contracts at these lifetime boundaries. The existing benchmark grows by 169 tooling lines plus 13 README lines to exercise tools, images, recovery, and post-GC resources; no new benchmark entry point or runtime manager is added.

Evidence

The original GC regressions retained all 20 continuations on baseline c2549f8295d09f520f119de44d77e1c7dc25779a, while an unowned control collected. Each fixed regression retains zero:

Retained callback owner Baseline continuations Fixed
Session notification / user persistence 20 / 20 0 / 20
Transcript writer 20 / 20 0 / 20
Cache-touch success callback 20 / 20 0 / 20

A separate regression keeps copies of completed attempt parameters alive: reachable message arrays fall from 40/40 to 0/40. It also protects message order and identity, caller-owned arrays, and recovery calls that omit new messages.

Delayed-write regressions failed before their corresponding fixes. They now prove that in-flight and queued writes retain the accepting run's callbacks, prepared envelopes, private visibility, assistant preparation, and run ID across rebinding. Other focused tests cover context-bound mode setters, synthetic cleanup after retirement, success/abort cleanup, prompt-prefix stability, and the benchmark protocol. The final context correction passed 113 tests across five guard/lifecycle files; its final fixture correction passed all 18 wrapper tests. Changed-file formatting/lint and independent review passed. The one permitted local core typecheck (native tsrs) passed before the final refinements; exact-head PR CI supplies the broad and final type proof. No Testbox/Crabbox validation lease or CI rerun was used.

Paired Gateway measurements

Acceptance rule: identical completed synthetic workloads and tool/recovery counts; collectible callback-owned continuations with a live GC control; no completed-continuation prompt payloads; no heap/timing regression beyond run variation. Two concurrent A/B pairs run under an exclusive lock on separate 16-core halves, swapping halves in pair 2. Compare candidate minus baseline within each pair.

Each side completes 110 runs (10 warmup and 100 measured, in cohorts of 10), with 300 read calls/results, 100 output-limit continuations/recoveries, and 300 image-bearing requests. Each synthetic fixture has 5,000 sessions, 6,000 retained runs, 200 approvals, 100 cron jobs, and 12 projects; its databases total 91,033,600 bytes (86.82 MiB).

Final measurement Baseline Fixed Fixed minus baseline
Pair 1 post-GC heap 616.78 MiB 616.56 MiB -0.22 MiB
Pair 1 main-thread CPU 29.430 s 29.423 s -0.02%
Pair 1 median cohort time 4.906 s 5.028 s +2.49%
Pair 2 post-GC heap 629.13 MiB 614.31 MiB -14.83 MiB
Pair 2 main-thread CPU 28.068 s 29.079 s +3.60%
Pair 2 median cohort time 4.816 s 4.939 s +2.56%

Median cohort time increased about 2.5% in both pairs. Individual cohort times overlapped broadly (roughly 4.6–6.2 seconds); nearest-rank p95 shifted −0.87% / +0.90% (10 cohorts per side, so p95 equals the maximum). CPU changed −0.02% / +3.60%. These measurements do not establish a speedup or a material latency regression; the landing evidence is removal of retained continuation payloads. Other post-warmup heap growth remains.

Workload command, run concurrently for the two isolated artifacts under the CPU/lock rule above:

node --import ./scripts/tsx.mjs scripts/perf/transcript-broadcast-measure.ts \
  --entry <variant>/dist/entry.js --state-dir <isolated-fixture> \
  --port <gateway-port> --mock-port <model-port> --scenario attempt-retention \
  --clients 1 --runs 10 --rounds 10 --chunks 1 --prompt-kib 128

The final candidate side also used --heap-snapshot.

The final snapshot contains 40 reachable continuation envelopes from completed run IDs, all with empty message arrays and empty prompts. None of the five reported callback paths remains. An equivalent baseline snapshot from the prior identical-source/workload campaign had 37 nonempty envelopes with seven messages each. Unique string self bytes reachable through continuation payloads fall from 15,331,224 to zero. This is reachability accounting, not dominator-retained bytes or a claim that every byte was uniquely owned by those envelopes.

The runtime artifacts compare pinned baseline c2549f8295d09f520f119de44d77e1c7dc25779a against that baseline with eight runtime source files captured from final head 907e3536079ad39524c15bfd5fc2a852e5c6b249; all source hashes match. This isolates the selected files, not a full latest-main performance comparison. The workload uses real isolated Gateway RPCs with a synthetic HTTP model, ten reused child-session IDs, tools, and PNG input. It does not measure live-model or model-driven subagent spawning behavior.

Build limitation: filtered runtime preparation hit unrelated Canvas-asset and baseline CLI-packaging checks. Both sides then used identical targeted runtime compilation/postbuild commands; no failed full build is represented as passing. A port-conflicted setup attempt was discarded and fresh fixtures used. Snapshot diagnostics retain their 30-second deadline; much larger snapshots can fail explicitly with a timeout.

PR CI

Final-head CI completed on 907e3536079ad39524c15bfd5fc2a852e5c6b249. Core/test types, focused owning lanes, and security review passed. The only underlying failure is the mock-export ratchet, plus its aggregate gates: test/scripts/ci-node-test-plan.test.ts:3297 mocks ../../scripts/lib/ci-test-timings.mts without pass-through/isolation annotation.

This is inherited. The PR head, tested merge ff2b76604b05b5669cca5a15a78c28101f37a713, and its main parent de561f3ea0b2f69dfacea6d3b4d67ca3e4989634 have identical test and ledger blobs (8c5a6d152b15828c44931615b4102534aa2f1d29 and d9c221e0b548925364ff34fdcba83f559008928f). A scoped reproduction on the benchmark host used the actual native parser, mock scanner, and ledger predicate on only that reported file/module: all three revisions exit 1 with the identical missing-factory fingerprint 8c74b1e63618912d9ac86d6697e483f02edeae751b9edb61b44c668c7f9db59c. No full suite or global ratchet was run for attribution. The operator-authorized inherited-failure exception applies; no CI rerun or rebase was performed to chase green.

The earlier PR-caused fixture type error was corrected using the existing typed assistant fixture and is green on this head. Independent reviews are clean; the two queued-write ownership findings are fixed. The optional larger-snapshot timeout suggestion is deferred with the limitation documented above.

@clawsweeper

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

chatgpt-codex-connector Bot commented Oct 19, 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-19T03:27:08.640068Z 907e353 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 scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 19, 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: f7c833b53e

ℹ️ 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
steipete force-pushed the steipete/perf-micro-attempt-continuation-retention-20260919 branch 2 times, most recently from a8e54d3 to 9604071 Compare October 19, 2026 02:36

@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: 9604071c12

ℹ️ 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: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. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR releases completed recovery payloads and retires attempt callbacks after accepted transcript writes drain.

Example: An agent completes repeated image-bearing runs with three read tools and an output-limit recovery.

  • Before: The supplied baseline snapshot retained 37 completed continuation envelopes, each holding seven messages.
  • After: The supplied fixed snapshot retained envelope shells with no messages or prompt text.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong behavior evidence supports the focused ownership repair, but the exact-head extension typecheck failure remains unattributed.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied paired runs exercise the real Gateway agent RPC, HTTP provider transport, images, read tools, and output-limit recovery using synthetic isolated state; matching workload counts and fixed snapshots show completed continuation payloads released, with final runtime hashes matched to the reviewed head.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Completed tool-heavy recovery runs can leave temporary prompt history reachable and increase Gateway heap usage.
Reason: The maintainer-authored direction addresses measured retained payloads while preserving retries and accepted-write settlement.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a demonstrated retention path still present on main; no introduced correctness defect was verified.

Priority: P2
Reviewed head: 9604071c12c168fc6e1a6f30a601e37bb8733783

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded runner carries recovery history between attempts, while session-manager guards transform and persist messages; cleanup must release completed history without interrupting accepted writes.

flowchart TD
  A[Agent RPC] --> B[Logical run prompt state]
  B --> C[Embedded attempt]
  C --> D[Guarded session manager]
  D --> E[Transcript persistence]
  C --> F[Transcript lifecycle drain]
  F --> G[Release attempt callbacks]
  B --> H[Release completed recovery payloads]
Loading

Technical review

Best possible solution:

Release recovery payloads at the logical-run owner and retire callback bindings only after their accepted writes settle.

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

Source identifies the retained continuation and closure paths, supported by supplied baseline/fixed GC regressions and Gateway snapshot results; this review executed no reproduction.

Is this the best way to solve the issue?

The change uses the existing logical-run, session-manager, and transcript-drain owners without adding a competing cleanup manager, and preserves active recovery history.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Recovery continuation payloads keeps the original intent (be4c0b1: Preserve the current request and completed work across overload retries and subsequent plugin refreshes.)
  • Reused session-manager prepared-user state keeps the original intent (b440340: Refresh prepared messages, recorders, replay keys, and suppression when a manager serves another attempt.)
  • Transcript visibility keeps the original intent (1cbb6c2: Keep private completion output internal while allowing the next ordinary turn to remain visible.)
  • Transcript drain and retained actor release keeps the original intent (5843d60: Retain the exact session actor for accepted transcript descendants, including after a bounded teardown timeout.)
  • Cache-touch timestamp keeps the original intent (c27999b: Avoid pruning warm caches during tool loops; the PR preserves timestamp behavior while narrowing the retained callback scope.)
  • Gateway resource profiling keeps the original intent (778a1b7: Measure completed Gateway workload allocations separately from live heap and RSS; post-GC sampling extends that existing benchmark owner.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit be4c0b1 adds src/agents/embedded-agent-runner/run/session-prompt-state.ts:72 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: be4c0b17a630; files: src/agents/embedded-agent-runner/run/session-prompt-state.ts)
  • Josh Avant: Raw commit b440340 adds src/agents/session-tool-result-guard-wrapper.ts:122 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b4403408e29d; files: src/agents/session-tool-result-guard-wrapper.ts)
  • Vincent Koc: Raw commit 1cbb6c2 adds src/agents/session-tool-result-guard-wrapper.ts:144 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1cbb6c271ae1; files: src/agents/session-tool-result-guard-wrapper.ts)

PR surface

Source +88, Tests +203, Docs +20, Other +169. Total +480 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 290 202 +88
Tests 6 206 3 +203
Docs 2 20 0 +20
Config 0 0 0 0
Generated 0 0 0 0
Other 3 216 47 +169
Total 19 732 252 +480

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +290/−202 lines; tests +206/−3 lines Net runtime growth of 88 lines supplies narrow closure capture, payload release, and callback lifetime handling; tests cover distinct retention and settlement boundaries.

Labels

Label changes:

  • add P2: Completed recovery history unnecessarily retains heap, with a demonstrated focused repair and no established urgent availability incident.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Completed recovery history unnecessarily retains heap, with a demonstrated focused repair and no established urgent availability incident.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 18, 2026, 10:59 PM ET / October 19, 2026, 02:59 UTC.

@steipete
steipete force-pushed the steipete/perf-micro-attempt-continuation-retention-20260919 branch from 9604071 to 1f2fe8e Compare October 19, 2026 03:06

@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: 1f2fe8e391

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

Release run-owned continuation history and per-attempt callback bindings without interrupting accepted transcript writes. Narrow retained writer and cache-touch callback scopes, and refresh callbacks when session managers are reused.

Regression proof: three 20-attempt WeakRef checks fail on the base and collect every completed continuation with the fix. Add a synthetic image/tool/recovery Gateway workload for retained-heap measurements.
@steipete
steipete force-pushed the steipete/perf-micro-attempt-continuation-retention-20260919 branch from 1f2fe8e to 907e353 Compare October 19, 2026 03:22
@steipete

Copy link
Copy Markdown
Contributor Author

Final head: 907e353. The final two swapped-core pairs and snapshot are in the PR body: 40 completed continuation envelopes retain zero prompt/messages; median cohort times are about 2.5% slower, with overlapping spread and mixed p95/CPU results. No speedup is claimed. Independent review is clean.

The only underlying CI failure is checks-fast-baseline-ratchets at test/scripts/ci-node-test-plan.test.ts:3297 (ci-test-timings mock). The PR head, tested merge ff2b76604b05b5669cca5a15a78c28101f37a713, and main parent de561f3 have identical test/ledger blobs. Scoped reproduction using the actual native parser, scanner, and ledger predicate fails identically on all three with fingerprint 8c74b1e63618912d9ac86d6697e483f02edeae751b9edb61b44c668c7f9db59c. Its aggregate gates are the only other red checks; the remaining checks, including final test types and security review, passed or were intentionally skipped. Landing uses the standing inherited-failure exception; no CI rerun was requested.

@clawsweeper re-review

@steipete
steipete merged commit 1929324 into main Oct 19, 2026
144 of 147 checks passed
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete deleted the steipete/perf-micro-attempt-continuation-retention-20260919 branch October 19, 2026 03:34
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
…6804)

* fix(agents): release prompt history after completed runs

Release run-owned continuation history and per-attempt callback bindings without interrupting accepted transcript writes. Narrow retained writer and cache-touch callback scopes, and refresh callbacks when session managers are reused.

Regression proof: three 20-attempt WeakRef checks fail on the base and collect every completed continuation with the fix. Add a synthetic image/tool/recovery Gateway workload for retained-heap measurements.

* fix(agents): bind accepted transcript writes to their callbacks

* fix(agents): release continuation payloads at their run owner

* fix(agents): preserve run context for queued transcript writes

* test(agents): use typed assistant fixture for retired cleanup
amittell added a commit to amittell/openclaw that referenced this pull request Oct 21, 2026
Merges upstream main at b90b2cf.

- scripts/pr-lib/wrapper-components.txt: keep main's new inventory entries and this branch's 18 reference-collector imports; no entry is duplicated.
- src/agents/embedded-agent-tool-media.ts: keep main's pushUniqueMessagingMediaUrl return value (openclaw#175022). collectStructuredMedia keeps this branch's capped, acceptMediaUrl-gated push, which already keys attachment metadata by the normalized accepted URL.
- src/agents/session-tool-result-guard-wrapper.ts: main's openclaw#176804 gives each run its own transcript context and rebuilds it when a guarded manager is reused. The local-media trust set now lives on that context: the trustedLocalMediaToolNames option seeds it, setTrustedLocalMediaToolNames replaces it on the current context, and a reuse that passes no set inherits the previous context's, so a same-run helper keeps the run's trust and an accepted write keeps the set of the context it captured.
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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