Skip to content

fix(agents): release completed turn memory - #177763

Merged
steipete merged 5 commits into
mainfrom
steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919
Oct 20, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Completed agent attempts could keep their transcripts alive through retained harness callbacks. Successful startup recovery also kept obsolete run records, while a pending prepared-registry completion observer retained the acquiring turn’s async context for the lifetime of a cached registry.

User Impact

Completed turns and successful recovery release their object graphs. Active work, finalization, transcript writes, resource claims, close errors, and failed-activation retry state keep their existing behavior. No configuration, storage-format, or retention-policy change.

Why This Change Was Made

  • Put post-dispatch attempt results in a child lexical scope outside retained harness callbacks, removing the retaining edge without clearing data needed by finalization or retry.
  • Reset the existing requester activator after fully successful startup activation; retain its progress on failure so retries do not resume completed work twice.
  • Remove the pending prepared-registry completion observer. Successful close deletes the view directly; failed close remains observable by shutdown.

Binding owners are per-object identity slots, including retained historical run records, not a separate global registry. Bounded terminal replies remain canonical delivery-retry evidence. AgentSession and SessionManager are attempt-owned; no idle-session LRU or competing owner is introduced.

Evidence and Measurement

Synthetic real-Gateway workloads used 5,000 sessions, 6,000 retained runs, ten traffic sessions, real read tools, inline images, output-limit recovery, and 16 KiB reasoning signatures. Concurrent A/B pairs held the exclusive measurement lock on separate 16-core halves (96–111 and 112–127), then swapped placement. Setup/analysis used cores 64–95; writes remained sequential and Dirty stayed below 2 GiB. No Testbox/Crabbox leases or production restart were used.

Two short pairs each completed 100 measured turns plus warmup:

Pair Baseline/candidate CPUs Post-GC heap MiB Median cohort wall ms Median main-thread CPU ms
1 112–127 / 96–111 599.27 → 559.25 (−6.68%) 4930.39 → 5010.55 (+1.63%) 2668.34 → 2723.21 (+2.06%)
2 96–111 / 112–127 595.36 → 578.16 (−2.89%) 4760.33 → 4789.35 (+0.61%) 2564.49 → 2662.66 (+3.83%)

The short-pair CPU increase is reported rather than called neutral. Cohort-paired mean CPU differences were +80.39/+79.62 ms (SD 86.20/179.86 ms). Baseline idle census retained 18 raw attempts and 18 snapshot arrays containing 126 entries; candidate retained zero. Immediate SessionManager/AgentSession counts were 30/30 versus 11/11.

Completed 60-minute soak

The paced soak completed 4,010 measured turns per side in approximately 60 minutes, with four clients, ten sessions, nine-second cohorts, and session resets every twenty cohorts. Every tool/replay assertion passed: 4,010 tool calls/results and 4,010 exact completed-signature replay checks per side. This is approximately 66.7 turns/minute, not model requests/minute.

Candidate census After warmup Settled Delayed idle
Raw attempts / message snapshots 0 / 0 0 / 0 0 / 0
SessionManager / AgentSession 10 / 10 1 / 1 0 / 0
Settled-turn callback targets 10 1 0
GatewayContextBindingOwner 7,327 7,269 7,213

The delayed capture began 42.96 seconds after the last turn, 30.01 seconds after the settled capture ended. Remaining objects named Agent are HTTP/HTTPS/Undici objects or prototypes, with no LLM mutableState/messages.

All 58 active forced-GC samples stayed between 577.661 and 613.721 MiB (−1.28% to +4.89% relative to the first active sample); final active growth was +4.58%. Same-reset-phase drift ranged from −1.93% to +4.01%, over up to 42 minutes. Final forced-GC heap was 612.810 MiB baseline / 611.943 MiB candidate. The idle-start to active-end comparison is +11.71% (547.815 → 611.943 MiB), so it is not presented as equivalent load. Initial/delayed-idle snapshot object self-size decreased 0.83% (640,560,120 → 635,249,218 bytes); this is distinct from process heapUsed.

Of the final 7,213 binding owners, 7,200 belong to the fixed fixture: 6,000 unique retained-run records plus 1,200 failed-activation retry duplicates. The large fixture intentionally exceeds startup worker capacity and must preserve those retry records. A separate successful-activation Gateway fixture proves cleanup: with twenty unique retained run IDs, obsolete duplicates fell from five to zero and total binding owners from 128 to 114. Both startup logs reported success.

Timing qualification

The hour’s timing is instrumented asymmetrically: only the candidate took an initial full heap snapshot. Its 334 unprofiled paired cohorts show CPU +11.51% (moving-block bootstrap 95% interval +10.67% to +12.35%) and wall +10.88%. Separately, 66 profiled cohorts, excluding the first boundary cohort, show CPU +10.51% and wall +9.77%. These increases are preserved, not called noise or attributed to the patch.

Node 26.8.2 provides a concrete confounder: taking a snapshot enables object-move tracking, but deleting it only removes the snapshot. Later GC moves incur a profiler mutex and object-ID map update. The benchmark preload does not clear that tracking. Candidate recorded 53.029 seconds of GC versus 16.738 seconds on baseline during the profiled interval, despite fewer GC events and 8.49% less retained sampled allocation.

Two fresh, swapped timing pairs with symmetric instrumentation completed successfully: no heap snapshots or retained sampling on either side, five-minute warmup, and three minutes / 200 measured turns per side in each pair.

Baseline/candidate CPUs Mean main-thread CPU ms CPU difference, 95% interval Wall difference, 95% interval
96–111 / 112–127 2461.77 → 2426.08 −1.45% [−4.17%, +1.80%] +0.28% [−1.60%, +2.86%]
112–127 / 96–111 2192.10 → 2182.68 −0.43% [−2.80%, +2.26%] +0.71% [−1.76%, +4.98%]

These paired differences show no regression beyond noise under the tested workload; they are not a CPU-speedup claim. The approximately 11% penalty did not recur without the one-sided snapshot. Both pairs matched 200 tool calls/results/replays, 400 reasoning responses, 214 recap requests, and 618 streams per side. The second pair also matched all 240 list polls; the first pair’s nineteen equal-poll-count cohorts had CPU −1.71%. Both started and ended at reset phase fourteen after 34 warmup cohorts. Starts differed by 2 ms and 86 ms; CPU assignment and outside-load records were verified. The hour is memory/lifetime evidence; these short symmetric pairs qualify timing, not an uninstrumented 60-minute latency result.

Validation

Regression proof is red on baseline and green with the fixes: twelve retained settled callbacks keep twelve snapshots on baseline and zero on candidate; superseded recovery rows collect after successful retry; acquiring async context collects while an independent registry claim remains open. Focused runner/settlement/harness/recovery tests passed 124 tests, startup registry eight, and donor resources five, including rollback and close-error handling. After the closed-mock repair, all 24 focused recovery tests passed again. Changed-file format/lint and diff checks passed. One local native-tsrs core lane passed; final production/test type checks passed in PR CI. Independent Codex review and current-head automated review are clean through P2.

The driver verifies the exact completed-response signature and rejects the incomplete reasoning-only signature. An initial assertion requiring the newest incomplete signature failed on unchanged baseline: replay intentionally omits reasoning-only length stops (#88656). The corrected assertion passed the second short pair and every soak turn. No provider replay policy changed. The first soak launch failed before traffic because the minimal runtime capsules lacked the enabled diagnostics plugin entrypoint; identical plugin assets were built for both sides and both configs validated before measurement.

Current-head CI run 39337840363 has one non-aggregate failure: checks-node-changed-compact-small-4, in src/agents/decision-inference.openai.integration.test.ts, “prepares the registered OpenAI image Decision route before auth (platform)”. It returned unavailable instead of ok; the assertion omitted its reason. The other seven cases passed. CI tested merge fa43770cccbe2d318f123643d8fce0e6f81f0817, whose tree equals the PR head tree and whose parents are the recorded main baseline and PR head. Five focused file runs on exact main parent 713ca224c42e67ada372cf53e3abd12c3868ee51 and five on PR head each passed all eight cases:

node scripts/run-vitest.mjs src/agents/decision-inference.openai.integration.test.ts --maxWorkers=1

Source inspection confirms no changed status-determining behavior during evaluation: the outer prepared lease prevents final disposal, the moved set deletion only affects shutdown enumeration, and the removed observer registered cleanup before the timed request. Run-loop and recovery are outside this path. This supports unrelated intermittent-failure attribution under the scoped landing exception; a cold five-second deadline is a hypothesis, not an established CI cause. No CI rerun was requested. All other applicable current-head checks passed, including source/architecture guards, lint, security review, types, and changed-test shards.

Earlier CI found an obsolete mock-baseline row and an undefined-response narrowing error in the synthetic driver; both were repaired and independently reviewed. An earlier unlimited-maintenance assertion passed its focused replay and did not recur on this head; no speculative fix is claimed.

Runtime delta: +2 lines (249 added / 247 removed), principally the child scope and ownership comment, required to release completed results without clearing data still needed by finalization and retry. The non-test/non-docs diff is +78 lines including the driver (+72), README (+5), and obsolete mock allowance removal (−1). No new production state, helper, API, or compatibility path.

Measured runtime base: 08e32fdb4df002c9d4eea158b855d6521dd1e916, plus the exact three production changes. All three files match PR head c0f4bde747da4af8d3ea978dcd529dbc475a66a4, based on 713ca224c42e67ada372cf53e3abd12c3868ee51. The pinned measurement driver predates only the equivalent defined-response guard. This is not claimed to be a full build of the newer PR base; PR CI validates that head. Production confirmation remains for the next already-planned batched restart.

@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 21:50
@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-19T22:54:30.813186Z c0f4bde 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: 31347d0b7b

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

Comment on lines +415 to +420
!input.some(
(item) =>
item?.type === "reasoning" &&
typeof item.encrypted_content === "string" &&
item.encrypted_content.length === 16 * 1024,
)

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.

P2 Badge Match replay to the immediately preceding reasoning signature

In the attempt-retention recovery request, the input can contain the reasoning signature from the initial tool-call response as well as the newer signature from the output-limit response. This predicate accepts any 16 KiB reasoning item, so dropping the newer signature while retaining the older one still increments reasoningReplayRequests and lets the benchmark report successful recovery replay. Track each generated signature by turn/response and require the continuation to contain the signature from the immediately preceding response.

AGENTS.md reference: AGENTS.md:L38-L38

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tightened the driver to match the exact completed-response signature per tool-call continuation and reject replay of the incomplete reasoning-only signature. Requiring the immediately preceding output-limit signature failed on unchanged baseline: the replay owner intentionally drops reasoning-only length stops (src/agents/embedded-agent-runner/replay-history.ts, introduced in #88656). The diagnostic run confirmed completed signatures were preserved exactly while incomplete signatures were omitted in all five sessions. The corrected assertion passed the real Gateway workload, lint, and independent review.

@steipete
steipete force-pushed the steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919 branch from 31347d0 to d00920d Compare October 19, 2026 21:57
@steipete steipete changed the title fix(agents): release settled attempt and recovery snapshots fix(agents): release completed turn memory Oct 19, 2026
@steipete
steipete force-pushed the steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919 branch from 0feeeda to 717ebe1 Compare October 19, 2026 22:21
@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. 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 attempt snapshots, successful recovery groups, and prepared-registry caller context.

Example: A Gateway completes tool-heavy turns while harness callbacks remain reachable.

  • Before: The reported baseline idle census retains 18 attempt snapshots containing 126 entries.
  • After: The reported candidate census retains zero completed attempt snapshots.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A small, coherent lifetime repair with useful Gateway measurements and focused regressions; the declared sustained-memory acceptance result is outstanding.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: A long-running Gateway retains completed agent-turn memory after the work finishes.
Reason: The maintainer-authored direction removes measured retention with minimal runtime change and explicitly acknowledges the measured CPU tradeoff.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes concrete memory-retention paths still present on main, with no introduced correctness or security defect found.

Priority: P2
Reviewed head: 717ebe1497aed3a29cac6ae169facfc205c7dfbf

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The declared 60-minute Gateway soak has no completed result showing post-GC growth within 10% and the final idle-retainer census.
Agent review details

How this fits together

The embedded runner processes harness results into retries or final replies; startup recovery and prepared-registry owners retain resources until their work settles.

flowchart TD
  A[Gateway turn] --> B[Embedded runner]
  B --> C[Harness callbacks]
  B --> D[Attempt results]
  D --> E[Retry or final reply]
  F[Startup recovery groups] --> G[Release completed references]
  H[Prepared registry resources] --> G
  E --> G
Loading

Technical review

Best possible solution:

Remove completed references at the existing lifecycle owners while preserving active retries, finalization inputs, resource claims, and close errors.

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

Current main contains the retaining callback scope, successful-activation group references, and pending registry observer; the PR supplies corresponding baseline-versus-candidate GC results, but this read-only review ran no target code.

Is this the best way to solve the issue?

The patch addresses reference ownership directly with the existing lifecycle mechanisms, and the added tests exercise distinct collection failures without new production scaffolding.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Embedded attempt processing keeps the original intent (ca9bbf6: The orchestration split preserved retry, recovery, and terminal handling; the new lexical scope leaves their processing and ordering intact.)
  • Prepared registry completion keeps the original intent (73b4086: Ephemeral prepared runtimes must retain admitted borrowers through cleanup; later retirement work preserved close failures for shutdown. Direct successful-close deletion preserves both contracts.)
  • Restored requester activation keeps the original intent (4645923: Independent requester groups preserve recovery progress through failures; resetting only after all groups succeed retains that retry behavior.)
  • Retention benchmark replay assertions keeps the original intent (Drop reasoning-only length turns from replay #88656: Reasoning-only token-limit turns contain incomplete provider state and must be omitted from replay while completed tool-call reasoning remains available.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 73b4086 adds src/agents/prepared-model-runtime.resources.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 73b4086ff658; files: src/agents/prepared-model-runtime.resources.ts)

PR surface

Source +2, Tests +119, Docs +8, Other +71. Total +200 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 249 247 +2
Tests 3 133 14 +119
Docs 2 10 2 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 72 1 +71
Total 9 464 264 +200

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +2 lines; tests +119 lines Runtime changes are 249 additions and 247 deletions, largely scope indentation; regression changes are 133 additions and 14 deletions covering three distinct retention boundaries.

Labels

Label changes:

  • add P2: Concrete completed-turn memory retention merits a focused repair; the evidence establishes no current outage or urgent user-facing regression.
  • 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: Concrete completed-turn memory retention merits a focused repair; the evidence establishes no current outage or urgent user-facing regression.
  • 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 19, 2026, 6:37 PM ET / 22:37 UTC.

@steipete
steipete force-pushed the steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919 branch from 717ebe1 to c0f4bde Compare October 19, 2026 22:51
@steipete
steipete merged commit 10049a6 into main Oct 20, 2026
167 of 170 checks passed
@steipete
steipete deleted the steipete/perf-micro-settled-attempt-snapshots-and-binding-owners-20260919 branch October 20, 2026 00:02
@steipete

Copy link
Copy Markdown
Contributor Author

Merged as 10049a6 under the scoped unrelated-CI exception.

The only non-aggregate CI failure was job 118352535436 in run 39337840363: src/agents/decision-inference.openai.integration.test.ts, “prepares the registered OpenAI image Decision route before auth (platform)”. Five focused runs on main parent 713ca22 and five on reviewed head c0f4bde each passed all eight tests. CI’s merge tree fa43770cccbe2d318f123643d8fce0e6f81f0817 exactly matched that reviewed head tree. Source inspection found no changed status-determining behavior while the test’s outer prepared lease is held. The original unavailable reason remains unknown; a cold-start deadline is a hypothesis, not a claimed fix. No CI rerun was requested. Other applicable checks and security gates passed, and independent/current-head reviews found no actionable defects.

The completed hour processed 4,010 turns per side. Delayed idle retained zero raw attempts, message snapshots, SessionManagers, AgentSessions, and settled-turn callbacks. Active forced-GC heap stayed within −1.28% to +4.89% of the first active sample. Two fresh symmetric timing pairs passed 200 turns per side each, with CPU differences −1.45% and −0.43% and confidence intervals spanning zero. Full measurements, the initial-idle comparison, and the one-sided heap-snapshot timing confounder are recorded in the PR body.

Production confirmation remains for the next already-planned batched restart; this task did not request or perform a production restart.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
* fix(agents): release settled attempt and recovery snapshots

* fix(agents): release prepared registry caller context

* test(perf): verify exact completed reasoning replay

* test(agents): preserve recovery mock exports

* fix(perf): narrow benchmark responses and remove stale mock debt
yozakura-ava pushed a commit to yozakura-ava/openclaw that referenced this pull request Oct 20, 2026
Upstream provenance: PR openclaw#177763, exact upstream commit 10049a6; adapted, not cherry-picked.

Adaptation: scope attempt-local dispatch, recovery, prepared-runtime, and terminal snapshots to one reclaimable block; remove completed prepared-registry views immediately after successful close. The upstream onSettledTurn WeakRef test and callback-specific changes are omitted because that callback contract is absent on 10.5.

Regression coverage: embedded run cleanup/custody, prepared-runtime startup registry, subagent queued recovery, guarded tsgo:core, oxlint, and oxfmt.

Rollback: revert this commit only.
yozakura-ava pushed a commit to yozakura-ava/openclaw that referenced this pull request Oct 20, 2026
Record openclaw#177763 exact provenance, ownership adaptation, contract deviation, focused gates, and rollback commit.
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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