Skip to content

perf(gateway): release large event payloads from live text guards - #158643

Merged
steipete merged 2 commits into
mainfrom
perf/l47-live-text-event-retention
Sep 26, 2026
Merged

steipete merged 2 commits into
mainfrom
perf/l47-live-text-event-retention

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Buffered live chat can retain large agent-event payloads after only a small display preview is needed.

User Impact

Concurrent sessions use less retained Gateway heap. Live text, widget previews, claim revocation, and delivery behavior stay unchanged.

Why This Change Was Made

Bind the existing current-owner guard to the run ID, claim ID, and lifecycle generation instead of closing over the whole event. The authoritative run registry already validates the lifecycle generation, so remove the duplicate check at its caller.

Related work in the same file: #158489 (incremental projection), #158587 (wire deltas), #158581 (lineage), and #158574 (stream subscriptions). Their inspected diffs do not fix this retention path; this change leaves those owners intact.

Evidence

  • Actual createAgentEventHandler heap probe: 50 active runs, each receiving a synthetic widget result plus a 4 MiB numeric payload. After explicit GC, all 50 previews and current-owner guards remain present. Three interleaved before/after pairs: baseline 200.160 / 200.098 / 200.094 MiB; candidate 0.1369 / 0.1369 / 0.1369 MiB. Median retained heap: 200.098 → 0.137 MiB (99.93% lower). This isolates retained heap, not end-to-end latency.
  • node scripts/run-vitest.mjs src/gateway/server-chat.agent-events.test.ts --maxWorkers=1: 225 tests passed, 167.86 s wall after rebase (1% test execution; most time was worker artifact preparation). Existing coverage exercises released claims, reused run IDs, delayed text, lifecycle generations, and tool-only widget retirement; no nondeterministic GC test added to CI.
  • Production: +18 / -19 lines, net -1. Tests: 0.
  • Diff-scoped deslop complete; independent Codex autoreview scoped-clean at P0–P2, no accepted/actionable findings.
  • node scripts/check-changed.mjs: production typecheck and all preceding guards passed; core-test validation stopped at an unrelated UI E2E TS2459 (control-ui-retained-assets.e2e.test.ts:17 imports ControlUiRootState from control-ui.ts, which no longer exports it after perf(gateway): keep Control UI file reads off the event loop #158464). No files in that failure are changed here. Later gate stages remain unrun; hosted CI is authoritative.
  • Focused oxlint and git diff --check passed.
  • Rebased onto the landed incremental projection change; ownership hunks are unchanged.

Landing validation

Exact-head CI run 36217587509 failed with TS2459 in ui/src/e2e/control-ui-retained-assets.e2e.test.ts: the fixture imported ControlUiRootState from the retired module. This was an unrelated main regression, fixed by da8149b8ba7d88d76dbe7979986e307a4542e6f0. Merged main into this branch without conflicts (no rebase); the reviewed performance patch ID is unchanged. Candidate: 09599c1177eaf1ccb87d4e94eef04f8911bcb07b.

After the merge, node scripts/run-vitest.mjs src/gateway/server-chat.agent-events.test.ts src/gateway/server-chat.subagent-lineage.test.ts --maxWorkers=1 passed all 224 tests across two files in 72.12 seconds wall. No tests were added or changed by this PR. New-head CI replaces the failed run; no blind rerun was requested.

@clawsweeper

clawsweeper Bot commented Sep 26, 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 gateway Gateway runtime size: XS labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 04:21
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 1:20 AM ET / 05:20 UTC (Revision 2).

ClawSweeper review

What this changes

The Gateway chat handler binds run, claim, and lifecycle identifiers into deferred live-text guards so large agent-event payloads can be released.

Merge readiness

✅ Ready for maintainer review

Current main still retains whole events through deferred live-text guards. This PR addresses that distinct retention path, and the review found no introduced correctness defect.

Priority: P2
Reviewed head: 09599c1177eaf1ccb87d4e94eef04f8911bcb07b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative production patch has direct handler measurements and no identified correctness or security defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports an actual agent-event-handler probe with 50 synthetic 4 MiB widget events; after explicit GC, previews and guards remained while median retained heap fell from 200.098 to 0.137 MiB. The evidence covers handler retention rather than full Gateway latency. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports an actual agent-event-handler probe with 50 synthetic 4 MiB widget events; after explicit GC, previews and guards remained while median retained heap fell from 200.098 to 0.137 MiB. The evidence covers handler retention rather than full Gateway latency. No stored-data contract changes.
Evidence reviewed 7 items Introduced change: The PR replaces the event-capturing predicate with a guard bound to the run ID, claim ID, and lifecycle generation.
Still needed on main: Current main still defines the deferred predicate as a closure over the complete event.
Live ownership check: The authoritative registry rejects a mismatched current generation, a different run-owner generation, or a missing claim; a clear-requested owner is not active.
Findings None None.
Security None None.

How this fits together

Agent events enter the Gateway chat handler, which prepares live previews and queues client delivery. The run registry decides whether deferred output still belongs to an active run claim.

flowchart LR
  A[Agent event] --> B[Gateway chat handler]
  B --> C[Live preview]
  B --> D[Deferred text guard]
  D --> E[Run registry check]
  E --> F[Client delivery]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -1. Total -1 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 18 19 -1
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 18 19 -1

Review metrics

Metric Value Why it matters
Reported retained heap 200.098 → 0.137 MiB median across 50 runs The paired handler measurements target the memory retention this patch changes.

Technical review

Best possible solution:

Keep the small identity-bound guard and its delivery-time registry check as the single ownership path for buffered live text.

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

Yes. Main’s deferred closure visibly captures the event, and the PR describes a focused, repeated post-GC handler probe using large synthetic payloads.

Is this the best way to solve the issue?

Yes. Binding only the needed identifiers removes the reference to the full event while the registry retains the existing live-claim decision.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 0d7a4e817abc.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Concurrent live runs can retain substantial Gateway heap, but no urgent user-facing outage is established.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports an actual agent-event-handler probe with 50 synthetic 4 MiB widget events; after explicit GC, previews and guards remained while median retained heap fell from 200.098 to 0.137 MiB. The evidence covers handler retention rather than full Gateway latency. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports an actual agent-event-handler probe with 50 synthetic 4 MiB widget events; after explicit GC, previews and guards remained while median retained heap fell from 200.098 to 0.137 MiB. The evidence covers handler retention rather than full Gateway latency. No stored-data contract changes.

Evidence

What I checked:

  • Introduced change: The PR replaces the event-capturing predicate with a guard bound to the run ID, claim ID, and lifecycle generation. (src/gateway/server-chat.ts:1369, 09599c1177ea)
  • Still needed on main: Current main still defines the deferred predicate as a closure over the complete event. (src/gateway/server-chat.ts:1373, 0d7a4e817abc)
  • Live ownership check: The authoritative registry rejects a mismatched current generation, a different run-owner generation, or a missing claim; a clear-requested owner is not active. (src/infra/agent-run-registry-state.ts:22, 09599c1177ea)
  • Generation equivalence: The removed event-lifecycle getter reads the same run-registry generation that the owner-status check validates. (src/infra/agent-events.ts:158, 09599c1177ea)
  • Deferred delivery boundary: The broadcaster calls the retained predicate before delivering queued live text, while chat-run state also checks it before resolving buffered text. (src/gateway/server-broadcast.ts:429, 09599c1177ea)
  • Reported behavior proof: The PR body reports three paired explicit-GC measurements through the actual agent-event handler: 50 active runs retained their previews and guards while median retained heap fell from 200.098 to 0.137 MiB. This measures handler retention, not end-to-end latency. (09599c1177ea)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-26T04:27:49.063Z sha fa72e20 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 26, 2026
@steipete
steipete merged commit 09b24ba into main Sep 26, 2026
200 checks passed
@steipete
steipete deleted the perf/l47-live-text-event-retention branch September 26, 2026 05:33
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 26, 2026
* commit '66b812f26e725cd709e08860d2cb46ba496cd308': (70 commits)
  fix(gateway): preserve typed boxed-number coercion
  chore(ui): refresh control ui locales (#158689)
  fix(gateway): reset staged headers on authority errors (#158669)
  fix(workers): keep inbound staging stable during quota scans
  fix: preserve Telegram delivery after bot identity changes (#158612)
  fix(ui): keep automation starter prompts out of startup (#158482)
  fix(cli): distinguish configuration read failures from invalid input (#158671)
  test: remove retired progress coercion suppression allowance
  refactor(gateway): schedule worker placement maintenance (#158662)
  fix(daemon): keep native service checks within their timeout (#154565)
  fix(test): restore gateway steering fixture contracts (#158478)
  fix(acpx): use SDK filesystem publication boundary
  fix(agentsapi): load OpenClaw persona and workspace context (#158328)
  fix(gateway): drop progress snapshot coercion suppression
  fix(qa): accept native Codex truncation in cache evidence (#158454)
  fix(gateway): keep chat subscriptions stable during unrelated approvals (#158633)
  perf(gateway): release event payloads from live text guards (#158643)
  perf(sessions): reduce stalls when saving large chat messages (#158402)
  fix(qa): reject history-bearing utility requests without session affinity (#158496)
  test: allow intentional progress snapshot coercion
  ...
vincentkoc added a commit that referenced this pull request Sep 26, 2026
* fix(test): verify followup completion ordering

Exercise the real presentation settlement helper with asynchronous cleanup, preserve continuation and admission semantics, and unconditionally release and join the held work. Remote proof covers the strengthened ordering contract and both missing-await faults.

* fix(test): verify followup completion ordering

* chore: retain followup test branch ancestry

The current-main reconstruction preserves the original reviewed scope and supersedes its stale base. Keep the remotely qualified candidate tree unchanged while retaining the original PR ancestry for a non-force branch update.

* commit 'ff35145de21cf6296bec05e86bee37b5ed53bcb8':
  fix(test): verify followup completion ordering

* test(auto-reply): signal queued presentation entry

* chore: refresh followup test on boundary fix

* commit '66b812f26e725cd709e08860d2cb46ba496cd308': (70 commits)
  fix(gateway): preserve typed boxed-number coercion
  chore(ui): refresh control ui locales (#158689)
  fix(gateway): reset staged headers on authority errors (#158669)
  fix(workers): keep inbound staging stable during quota scans
  fix: preserve Telegram delivery after bot identity changes (#158612)
  fix(ui): keep automation starter prompts out of startup (#158482)
  fix(cli): distinguish configuration read failures from invalid input (#158671)
  test: remove retired progress coercion suppression allowance
  refactor(gateway): schedule worker placement maintenance (#158662)
  fix(daemon): keep native service checks within their timeout (#154565)
  fix(test): restore gateway steering fixture contracts (#158478)
  fix(acpx): use SDK filesystem publication boundary
  fix(agentsapi): load OpenClaw persona and workspace context (#158328)
  fix(gateway): drop progress snapshot coercion suppression
  fix(qa): accept native Codex truncation in cache evidence (#158454)
  fix(gateway): keep chat subscriptions stable during unrelated approvals (#158633)
  perf(gateway): release event payloads from live text guards (#158643)
  perf(sessions): reduce stalls when saving large chat messages (#158402)
  fix(qa): reject history-bearing utility requests without session affinity (#158496)
  test: allow intentional progress snapshot coercion
  ...

Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
* fix(test): verify followup completion ordering

Exercise the real presentation settlement helper with asynchronous cleanup, preserve continuation and admission semantics, and unconditionally release and join the held work. Remote proof covers the strengthened ordering contract and both missing-await faults.

* fix(test): verify followup completion ordering

* chore: retain followup test branch ancestry

The current-main reconstruction preserves the original reviewed scope and supersedes its stale base. Keep the remotely qualified candidate tree unchanged while retaining the original PR ancestry for a non-force branch update.

* commit 'ff35145de21cf6296bec05e86bee37b5ed53bcb8':
  fix(test): verify followup completion ordering

* test(auto-reply): signal queued presentation entry

* chore: refresh followup test on boundary fix

* commit '622be54be3ffe0fce27d6a4b147c76d4b19c528c': (70 commits)
  fix(gateway): preserve typed boxed-number coercion
  chore(ui): refresh control ui locales (openclaw#158689)
  fix(gateway): reset staged headers on authority errors (openclaw#158669)
  fix(workers): keep inbound staging stable during quota scans
  fix: preserve Telegram delivery after bot identity changes (openclaw#158612)
  fix(ui): keep automation starter prompts out of startup (openclaw#158482)
  fix(cli): distinguish configuration read failures from invalid input (openclaw#158671)
  test: remove retired progress coercion suppression allowance
  refactor(gateway): schedule worker placement maintenance (openclaw#158662)
  fix(daemon): keep native service checks within their timeout (openclaw#154565)
  fix(test): restore gateway steering fixture contracts (openclaw#158478)
  fix(acpx): use SDK filesystem publication boundary
  fix(agentsapi): load OpenClaw persona and workspace context (openclaw#158328)
  fix(gateway): drop progress snapshot coercion suppression
  fix(qa): accept native Codex truncation in cache evidence (openclaw#158454)
  fix(gateway): keep chat subscriptions stable during unrelated approvals (openclaw#158633)
  perf(gateway): release event payloads from live text guards (openclaw#158643)
  perf(sessions): reduce stalls when saving large chat messages (openclaw#158402)
  fix(qa): reject history-bearing utility requests without session affinity (openclaw#158496)
  test: allow intentional progress snapshot coercion
  ...

Co-authored-by: Vincent Koc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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